Simple Servlet tutorial |
Simple Servlet tutorial
Regarding all zip files for download.
- All downloadable zip files contains a Netbeans IDE project with code examples.
- Needed tools for all examples/tutorials can be found in the right menu on this page.
Simple Servlet tutorial.
About this tutorial.
- This tutorial is an example of using Servlets. It is about registering cars to a Car-park and let the servlet response to the client with a list of all registered cars each time a new car is registered.
- We are not using any persistent storage in this example so all registered cars will be stored in a Vector which is stored in the user session object. Therefore, when the session is ended all data is gone. A similar Servlet application with use of persistent storage can be found in the Servlet Examples.
- It is recommended that you study all the subjects that are under Java Servlets menu.
- If you just want to look through the solution of this tutorial you can download it here
Need to know before this.
- Basic knowledge about HTML and CSS.
- You should have learned and understood everything under Java Basic.
Regarding all zip files for download.
- All downloadable zip files contains a Netbeans IDE project with code examples.
- Needed tools for all examples/tutorials can be found in the right menu on this page.
Create a Netbeans project
- As first action we need to create a project Netbeans with the name Servlet01.
Creating the Front-end.
-
We need a html form to register cars so
create a HTML page in Netbeans
with the name RegCars.html in a folder web.
Copy the below code into between the body tags of the RegCars.html file.
<h1>Registration of Cars</h1> <form action="/Servlet01/CarParkServlet" method="POST"> <table border="1px"> <tr> <td align="left" style="width:120px">RegNo:</td> <td align="left" style="width:120px">Cartype:</td> <td align="left" style="width:120px">Model:</td> <td align="left" style="width:120px">DayPrice:</td> </tr> <tr> <td align="left"><input type="text" style="width:120px" name="regNo" /></td> <td align="left"><input type="text" style="width:120px" name="cartype" /></td> <td align="left"><input type="text" style="width:120px" name="model" /></td> <td align="right"><input type="text" style="width:120px" name="dayPrice" /></td> </tr> </table> <p><input type="submit" value="Submit"/></p> </form>
When the user Submit this form our CarparkServlet, which we will create in the back-end part, come in action and handle this POST request which will contain the parameters: regNo, cartype, model and dayPrice.
For each new registered car, we want to have a car object that we add to a dynamic Vector on the session object, which exist in the servlet.
Creating the Back-end.
Create data transporter and controller.
To collect data for each registration we need a java class which we can use to create new objects for each car registration.
-
Create a Java class in Netbeans, Car, with the package lab.
Copy this code to your Car class:
private String regNo; private String cartype; private int model; private double dayPrice;
This is all the member variables of a Car object, but we need get/set accessors for all the member variables.
- Place the cursor after the last member variable and inside the class and right click to get the menu for inserting get/set accessors for all the member variables.
- Select Insert code... from the menu and then Getter and Setter ... from the new menu.
-
Select all fields and click the Generate button. You should now have
get/set accessors for all the member variables in the class.
We like to have an object that contain all the registered cars , with some kind of functionality and can be stored as an object on the Http Session object.
-
Create a Java class in Netbeans, CarPark, with the package lab.
Copy this code to your CarPark class:
private Vector<Car> cars; public CarPark() { cars= new Vector<Car>(); } public Vector<Car> getCars() { return cars; } public void addCar(Car car) { cars.add(car); }
-
Right click inside the class and select Fix Imports
The car's Vector variable member is meant to hold all registered cars.
The addCar() method is to add new car to the Vector, cars, and the getCars() method will return the Vector of all cars.
We have now the tools to hold the data and then we need the Servlet to control flow of data and in this case handling the presentation of registered cars.
Create the Servlet.
-
Create a Servlet in Netbeans
with the name CarParkServlet and package name show.
With help from Netbeans we have now created a Servlet that have a doGet() method and a doPost() method, which both call the processRequest() method.
In this way, we have a common handling for both GET and POST type requests.
It is now for us to put some code inside the try braces in the processRequest() method.
You must now replace the existing code inside the try braces in the method, processRequest(), using the code below.:// get the session object // if not exists - create one HttpSession session = request.getSession(); // get the carPark object from the session object CarPark carPark = (CarPark) session.getAttribute("carPark"); // if no carPark object exists on the session object - create one if (carPark == null) { carPark = new CarPark(); session.setAttribute("carPark", carPark); } // Test for any request parameters Enumeration enumr = request.getParameterNames(); if (enumr.hasMoreElements()) { // Register a new car only if the regNo have a value if (!request.getParameter("regNo").equals("")) { Car car = new Car(); car.setRegNo(request.getParameter("regNo")); car.setCartype(request.getParameter("cartype")); car.setModel(Integer.parseInt(request.getParameter("model"))); car.setDayPrice(Double.parseDouble(request.getParameter("dayPrice"))); carPark.addCar(car); // add a car to the carPark object } } // get all the cars that are regitered Vector<Car> cars = carPark.getCars(); // print out to the response a table header for all cars out.println("<html><body>"); out.println(" <h2>Registered Cars</h2>"); out.println(" <table border=\"1px\" >"); out.println(" <tr>"); out.println(" <td align=\"left\" style=\"width:120px\" >RegNo:</td>"); out.println(" <td align=\"left\" style=\"width:120px\">Cartype:</td>"); out.println(" <td align=\"left\" style=\"width:120px\">Model:</td>"); out.println(" <td align=\"left\" style=\"width:120px\">DayPrice:</td>"); out.println(" </tr>"); // If any car regitered - get each car and print out to the response // a table row for each car if (!cars.isEmpty()) { for (int i = 0; i < cars.size(); i++) { Car car = (Car) cars.get(i); out.println(" <tr>"); out.println(" <td align=\"left\">" + car.getRegNo() + "</td>"); out.println(" <td align=\"left\">" + car.getCartype() + "</td>"); out.println(" <td align=\"left\">" + String.valueOf(car.getModel()) + "</td>"); out.println(" <td align=\"left\">" + String.valueOf(car.getDayPrice()) + "</td>"); out.println(" </tr>"); } } out.println(" </table>"); out.println(" <p><a href=\"/Servlet01/RegCars.html\">Return" + "</a> car registration</p>"); out.println("</body></html>");
-
Right click inside the class, CarParkServlet, and select Fix Imports.
For more understanding please read the comments in this code.
Configuration.
The last thing to do is to change the welcome file name so open the web.xml file in the Configuration folder of the project, select Pages, and then change the Welcome File(s) to be RegCars.html.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>CarparkServlet</servlet-name>
<servlet-class>show.CarparkServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CarparkServlet</servlet-name>
<url-pattern>/CarparkServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>RegCars.html</welcome-file>
</welcome-file-list>
</web-app>
Run the Java Application.
- Right click the project, Servlet01, and select run from the menu.
- This will deploy the project to the web-server and start a session in you default browser with the url http://localhost:8090/Servlet01.
Enter RegNo, Cartype, Model, DayPrice and press the submit button.
Regarding all zip files for download.
- All downloaded zip files contains war-file(s) that can be imported to Eclipse IDE as a web war-file(s).
- Needed tools for all examples/tutorials can be found in the right menu on this page.
Simple Servlet tutorial.
About this tutorial.
- This tutorial is an example of using Servlets. It is about registering cars to a Car-park and let the servlet response to the client with a list of all registered cars each time a new car is registered.
- We are not using any persistent storage in this example so all registered cars will be stored in a Vector which is stored in the user session object. Therefore, when the session is ended all data is gone. A similar Servlet application with use of persistent storage can be found in the Servlet Examples.
- It is recommended that you study all the subjects that are under Java Servlets menu.
- If you just want to look through the solution of this tutorial you can download it here
Need to know before this.
- Basic knowledge about HTML and CSS.
- You should have learned and understood everything under Java Basic.
Regarding all zip files for download.
- All downloaded zip files contains war-file(s) that can be imported to Eclipse IDE as a web war-file(s).
- Needed tools for all examples/tutorials can be found in the right menu on this page.
Create a Netbeans project
- As first action we need to create a project Netbeans with the name Servlet01.
Creating the Front-end.
-
We need a html form to register cars so
create a HTML page in Netbeans
with the name RegCars.html in a folder ServletFormHandling/WebContent.
Copy the below code into between the body tags of the RegCars.html file:
<h1>Registration of Cars</h1> <form action="/Servlet01/CarParkServlet" method="POST"> <table border="1px"> <tr> <td align="left" style="width:120px">RegNo:</td> <td align="left" style="width:120px">Cartype:</td> <td align="left" style="width:120px">Model:</td> <td align="left" style="width:120px">DayPrice:</td> </tr> <tr> <td align="left"><input type="text" style="width:120px" name="regNo" /></td> <td align="left"><input type="text" style="width:120px" name="cartype" /></td> <td align="left"><input type="text" style="width:120px" name="model" /></td> <td align="right"><input type="text" style="width:120px" name="dayPrice" /></td> </tr> </table> <p><input type="submit" value="Submit"/></p> </form>
When the user Submit this form our CarparkServlet, which we will create in the back-end part, come in action and handle this POST request which will contain the parameters: regNo, cartype, model and dayPrice.
For each new registered car, we want to have a car object that we add to a dynamic Vector on the session object, which exist in the servlet.
Creating the Back-end.
Create data transporter and controller.
To collect data for each registration we need a java class which we can use to create new objects for each car registration.
-
Create a Java class in Netbeans, Car, with the package lab.
Copy this code to your Car class:
private String regNo; private String cartype; private int model; private double dayPrice;
This is all the member variables of a Car object, but we need get/set accessors for all the member variables.
- Place the cursor inside the class and right click to get a menu. Select "Source" from the menu and then "Generate Getters and Setters ..." from the next menu.
-
Select all fields in the window and click the OK button. You should now have
get/set accessors for all the member variables in the class.
We like to have an object that contain all the registered cars, with some kind of functionality and can be stored as an object on the Http Session object.
-
Create a Java class in Netbeans, CarPark, with the package lab.
Copy this code to your CarPark class:
private Vector<Car> cars; public CarPark() { cars= new Vector<Car>(); } public Vector<Car> getCars() { return cars; } public void addCar(Car car) { cars.add(car); }
-
Select the CarPark class and press Ctlr+Shift+O to organize Imports. (This will import the java.util.Vector)
The car's Vector variable member is meant to hold all registered cars.
The addCar() method is to add new car to the Vector, cars, and the getCars() method will return the Vector of all cars.
We have now the tools to hold the data and then we need the Servlet to control flow of data and in this case handling the presentation of registered cars.
Create the Servlet.
-
Create a Servlet in Netbeans
with the name CarParkServlet and package name show.
It is now for us to put some code inside the try braces in the doPost() method as we will use a POST request in the html-form.
You must now replace the existing code in the method, doPost(), using the code below:response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { // get the session object // if not exists - create one HttpSession session = request.getSession(); // get the carPark object from the session object CarPark carPark = (CarPark) session.getAttribute("carPark"); // if no carPark object exists on the session object - create one if (carPark == null) { carPark = new CarPark(); session.setAttribute("carPark", carPark); } // Test for any request parameters Enumeration enumr = request.getParameterNames(); if (enumr.hasMoreElements()) { // Register a new car only if the regNo have a value if (!request.getParameter("regNo").equals("")) { Car car = new Car(); car.setRegNo(request.getParameter("regNo")); car.setCartype(request.getParameter("cartype")); car.setModel(Integer.parseInt(request.getParameter("model"))); car.setDayPrice(Double.parseDouble(request.getParameter("dayPrice"))); carPark.addCar(car); // add a car to the carPark object } } // get all the cars that are regitered Vector<Car> cars = carPark.getCars(); // print out to the response a table header for all cars out.println("<html><body>"); out.println(" <h2>Registered Cars</h2>"); out.println(" <table border=\"1px\" >"); out.println(" <tr>"); out.println(" <td align=\"left\" style=\"width:120px\" >RegNo:</td>"); out.println(" <td align=\"left\" style=\"width:120px\">Cartype:</td>"); out.println(" <td align=\"left\" style=\"width:120px\">Model:</td>"); out.println(" <td align=\"left\" style=\"width:120px\">DayPrice:</td>"); out.println(" </tr>"); // If any car regitered - get each car and print out to the response // a table row for each car if (!cars.isEmpty()) { for (int i = 0; i < cars.size(); i++) { Car car = (Car) cars.get(i); out.println(" <tr>"); out.println(" <td align=\"left\">" + car.getRegNo() + "</td>"); out.println(" <td align=\"left\">" + car.getCartype() + "</td>"); out.println(" <td align=\"left\">" + String.valueOf(car.getModel()) + "</td>"); out.println(" <td align=\"left\">" + String.valueOf(car.getDayPrice()) + "</td>"); out.println(" </tr>"); } } out.println(" </table>"); out.println(" <p><a href=\"/Servlet01/RegCars.html\">Return" + "</a> car registration</p>"); out.println("</body></html>"); } finally { out.close(); }
-
Right click inside the class, CarParkServlet, and press Ctlr+Shift+O to organize Imports.
For more understanding please read the comments in this code.
Configuration.
The last thing to do is to change the welcome file name so open the web.xml file in the WebContent/WEB-INF folder of the project, select source, and then change the first Welcome File(s) to be RegCars.html (you can remove all other welcome-file tags).
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>ServletFinal01</display-name>
<welcome-file-list>
<welcome-file>RegCars.html</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>CarParkServlet</display-name>
<servlet-name>CarParkServlet</servlet-name>
<servlet-class>show.CarParkServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CarParkServlet</servlet-name>
<url-pattern>/CarParkServlet</url-pattern>
</servlet-mapping>
</web-app>
Run the Java Application.
- Eclipse will default use an internal browser for Web applications. I prefer to use an extern browser and this can be changed here.
- Right click the project, Servlet01, and select Run as -> Run on server from the menus.
- This will deploy the project to the web-server and start a session in your selected browser with the url http://localhost:7001/Servlet01.
Enter RegNo, Cartype, Model, DayPrice and press the submit button.
Installation procedures. |