How to Create Barcode with Apache Tomcat using Java Servlet
- Install or verify your use of JDK 1.4.2 or above
- Unzip the trial, copy the barcode folder and its contents your Apache Tomcat webapps file
- Restart Apache Tomcat server by restarting the service
- Navigate to this URL to generate a barcode: http://localhost:8080/barcode/barcode?DATA=0123456789&TYPE=CODE128
- You can specify parameters in the URL to adjust barcode type and image settings
- You can insert barcode images in HTML / web page with image tag, using the barcodes created in Java Servlet:
<img src="http://localhost:8080/barcode/barcode?DATA=0123456789&TYPE=CODE128" />
How to Print Barcode Image in Java Servlet Class
OnBarcode also provides specific guide to encode barcode data, or customize barcode image:
- Sample code for Barcode Data Encoding - Creating GS1-Compatible Barcodes or encode Unicode into Java Barcodes
- Sample code for Barcode Image Setting - Generating barcodes in Java and adjust barcode image properties
Presented below is the simple Java api sampel code for printing barcode images in Java Servlet application. Copy the demo syntax to your program for barcoding. Code 128 encoding numeric string value is used as an example. For other input or special character text, please change the Java syntax for other barcode type.
import com.onbarcode.barcode.AbstractBarcode;
import com.onbarcode.barcode.Code128;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
public class BarcodeServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException
{
try {
Code128 barcode = new Code128();
barcode.setData("0123456789");
// Basic barcode size settings here
barcode.setX(2);
barcode.setY(60);
barcode.setLeftMargin(8);
barcode.setRightMargin(8);
//Customize barcode image format into Gif(0), Jpeg(1), and Png(3)
barcode.setImageFormat(0)
// Set generated barcode image resolution
barcode.setResolution(96);
// Set barcode rotation rate. 0 degree(0), 90 degree(1), 180 degree(2), 270 degree(3)
barcode.setRotate(0);
ServletOutputStream servletoutputstream = response.getOutputStream();
response.setContentType("image/jpeg");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// Generate Code-128 barcode & output to ServletOutputStream
barcode.drawBarcode(servletoutputstream);
} catch (Exception e) {
throw new ServletException(e);
}
}
}
Java Barcode Generation Guide for Linear & 2D Barcode Types
Java Barcoder Library SDK - Barcodes Generation
- Java Linear Barcodes Generation:
- Java 2D Barcodes Generation: Data Matrix, PDF417, QR Code
