About Java and JRuby Development
JEE, Spring, Guice
Hibernate, Java Persistence (JPA)
and various Web Frameworks

First Java Servlets and JSP Tutorial

We want to create a small web application (library), that illustrates the usage of JavaServer Pages combined with Java Servlets. We use the JavaServer Pages to display data (presentation) and the servlets to control and call the business logic of the web application.

First we shortly explain the characteristics of these two technologies.

Generals

Author:

Sascha Wolski

www.laliluna.de/tutorials.html

Date:


September, 23th 2004




Source code:


http://www.laliluna.de/assets/tutorials/java-servlets-jsp-tutorial.zip


The sources does not contain the project files. So create a project first and copy the sources to this projects.


PDF Version des Tutorials:


http://www.laliluna.de/assets/tutorials/java-servlets-jsp-tutorial-en.pdf


Development Tools


Eclipse 3.x




Optional:


MyEclipse plugin 3.8


(A cheap and quite powerful Extension to Eclipse to develop Web Applications and EJB (J2EE) Applications. I think that there is a test version availalable at MyEclipse.)




Application Server


Jboss 3.2.5


You may use Tomcat here if you like.


Java Servlets


Servlets represent java programs that run on a web server. They allow the developer to produce dynamic web sites with java.


A Servlet has the following tasks




Java Server Pages (JSP)

JavaServer Pages (JSP) are text documents, which are similar to HTML Files. But you find also java code in the JSP File. JavaServer Pages allow you to mix regular static HTML with dynamic generated contents of Java code. The java code is inserted in the HTML document on a JSP File, differently to a servlet, where the HTML code is embedded in the java code.

Create a new Web Projekt

Right click on the package explorer and choose New > Project.
Choose the wizard Web Project in J2EE.





Set a nice name for your project.




Class with dummy data

In this example we do not use a database binding. We use a class which provide the dummy data and some methods for add, update, delete. Create a new Package de.laliluna.tutorial.library in src of the project. Download the complete project an copy the file SimulatedDB.java from the folder /de/laliluna/tutorial/library in the package.



Create the class book

You can borrow a book in a library, so we need a class that represent the book.

Create a package de.laliluna.tutorial.library and a new class New > Class.






The object class book contains the following private properties as variables.

We create for the properties getter- and setter-methods, to access the private properties.



Open the class Book and add the properties and getter- and setter-methods. Add constructors to this class.

public class Book {<br><br>    private long id = 0;<br>    private String title = "";<br>    private String author = "";<br>    private boolean available = false;<br><br>    // Contructor<br>    public Book(){}<br>    //  Contructor to initial the properties<br>    public Book(long id, String author, String title, boolean available) {<br>        this.id = id;<br>        this.author = author;<br>        this.title = title;<br>        this.available = available;<br>    }<br><br>    public boolean isAvailable() {<br>        return available;<br>    }<br><br>    public void setAvailable(boolean available) {<br>        this.available = available;<br>    }<br><br>    public long getId() {<br>        return id;<br>    }<br><br>    public void setId(long id) {<br>        this.id = id;<br>    }<br><br>	public String getAuthor() {<br>		return author;<br>	}<br><br>	public void setAuthor(String author) {<br>		this.author = author;<br>	}<br><br>	public String getTitle() {<br>		return title;<br>	}<br><br>	public void setTitle(String title) {<br>		this.title = title;<br>	}<br>}






Create the servlets

In our example application we use two servlets, which are responsible for steering our web application.

Create a new package de.laliluna.tutorial.library.servlets in src of your project.

Right click on the package and choose New > Servlet.





Repeat the steps for the second servlet. Set the name of the servlet to ?BookList?.

Now you find the servlets in your package.






Edit the servlets

BookList.java

Open the servlet class BookList.java. This servlet loads a list of books and saves it in the request. Later in the JavaServer Page (jsp) we use the list to display the books.

Change the method doGet(…) like the following.

public void doGet(HttpServletRequest request, HttpServletResponse response)<br>			throws ServletException, IOException {<br><br>		//hole die session des requests<br>		HttpSession session = request.getSession();<br><br>		//initialisiere die Datenbank Klasse<br>		SimulateDB simulateDB = new SimulateDB();<br><br>		//lies alle B�cher aus der Datenbank Klasse<br>		Collection collection = simulateDB.getAllBooks(session);<br><br>		//setze die zur�ck gegebene Liste der B�cher im Request<br>		request.setAttribute("books", collection);<br><br>		//hole den Request Dispatcher f�r die JSP Datei<br>		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/jsp/bookList.jsp");<br><br>		//leite auf die JSP Datei zum Anzeigen der Liste weiter<br>		dispatcher.forward(request, response);		<br>}



In the doPost(…) method we call the method doGet(…), because we want to execute the same logic for each request GET or POST of the browser.

public void doPost(HttpServletRequest request, HttpServletResponse response)<br>			throws ServletException, IOException {<br><br>		//rufe die doGet(...) Methode auf<br>		this.doGet(request, response);<br><br>}


We finished the servlet, that gets all books of the library.

BookEdit.java

In the next step we want to edit the servlet class BookEdit.java. Later it should control add, edit, delete of the books.

Open the class BookEdit.java and change the method doGet(…) like the following. With the parameter do in the method doGet(…) we check which action is called.

When creating a book, it refers to the display jsp.

When the value edit is assigned to the parameter do, the book is loaded and saved in the request with the name book.

When deleting is choosen, the book is deleted and the application is forwarded to the servlet BookList to display the list of books.

public void doGet(HttpServletRequest request, HttpServletResponse response)<br>			throws ServletException, IOException {<br><br>		//hole die session des requests<br>		HttpSession session = request.getSession();<br><br>		//initialisiere die Datenbank Klasse<br>		SimulateDB simulateDB = new SimulateDB();<br><br>		//lies den Parameter do aus dem Request <br>		String action = request.getParameter("do");<br><br>		//lies den Parameter id aus dem Request<br>		long id = 0;<br>		try{<br>			id = Long.parseLong(request.getParameter("id"));<br>		}catch(NumberFormatException e){}<br><br>		//hinzuf�gen eines Buches<br>		if(action.equals("add")){<br><br>			//hole den Request Dispatcher f�r die JSP Datei<br>			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/jsp/bookAdd.jsp");<br><br>			//leite auf die JSP Datei zum Anlegen eines Buches weiter<br>			dispatcher.forward(request, response);	<br><br>		//bearbeiten eines Buches<br>		}else if(action.equals("edit")){<br><br>			//lies das Buch anhand seiner Id aus<br>			Book book = simulateDB.loadBookById(id, session);<br><br>			//setze das Buch Objekt im request<br>			request.setAttribute("book", book);<br><br>			//hole den Request Dispatcher f�r die JSP Datei<br>			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/jsp/bookEdit.jsp");<br><br>			//leite auf die JSP Datei zum Bearbeiten eines Buches weiter<br>			dispatcher.forward(request, response);	<br><br><br>		//l�schen eines Buches<br>		}else if(action.equals("delete")){<br><br>			//l�sche das Buch anhand der Id<br>			simulateDB.deleteBookById(id, session);<br><br>			//Redirect Weiterleitung zum BookList Servlet<br>			response.sendRedirect(request.getContextPath() + "/bookList");<br><br>		}<br><br>}



In this servlet we do not call the doGet(…) method within the method doPost(…). We distinguish between the GET or POST request of the browser.

If the browser sends a post request to the servlet (send a form with <form method=?post?>) the transfered data, in our case the properties of the book (author, title, …), will be processed.

Change the doPost(…) method to the following.
Within the method the transfered properties are read from the request and a new object book is created. The method saveToDB(…) of the database class saves the object book. After saving, the servlets it forwards to the servlet, that display the list of books.

public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {<br><br>		//hole die session des requests<br>		HttpSession session = request.getSession();<br><br>		//initialisiere die Datenbank Klasse<br>		SimulateDB simulateDB = new SimulateDB();<br><br>		//lies den Parameter id aus dem Request<br>		long id = 0;<br>		try{ id = Long.parseLong(request.getParameter("id")); }<br>		catch(NumberFormatException e){}<br><br>		//lies die Buch-Eigenschaften aus dem Request<br>		String author = request.getParameter("author");<br>		String title = request.getParameter("title");<br>		Boolean available = Boolean.valueOf(request.getParameter("available"));<br><br>		//erstelle ein neues Buch Objekt <br>		Book book = new Book(id, author, title, available.booleanValue());<br><br>		//speichere das Buch Objekt<br>		simulateDB.saveToDB(book, session);<br><br>		//Redirect Weiterleitung zum BookList Servlet<br>		response.sendRedirect(request.getContextPath() + "/bookList");<br>}

Create the jsp files

To display the list of books and the dialogs to add and edit a book, we create three jsp files.

Create a new folder jsp in /WebRoot and add the three new JavaServer Pages.






bookAdd.jsp

Open the first jsp file bookAdd.jsp. Later the JavaServer Page will display a form, where the user can add a book. This jsp file is only for adding new data and send this data to the servlet.

&lt;%<br>String path = request.getContextPath();<br>String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";<br>%&gt;<br><br>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;<br>&lt;html&gt;<br> &lt;head&gt;<br> &lt;base href="&lt;%=basePath%&gt;"&gt;<br><br> &lt;title&gt;Book add page&lt;/title&gt;<br> &lt;/head&gt;<br> &lt;body&gt;<br> &lt;form name="edit" action="bookEdit" method="post"&gt;<br> &lt;table border="1"&gt;<br> &lt;tbody&gt;<br> &lt;tr&gt;<br> &lt;td&gt;Author:&lt;/td&gt;<br> &lt;td&gt;&lt;input type="text" name="author" value=""&gt;&lt;/td&gt; <br> &lt;/tr&gt;&lt;tr&gt; <br> &lt;td&gt;Title:&lt;/td&gt; <br> &lt;td&gt;&lt;input type="text" name="title" value=""&gt;&lt;/td&gt;<br> &lt;/tr&gt;&lt;tr&gt;<br> &lt;td&gt;Available:&lt;/td&gt;<br> &lt;td&gt;&lt;input type="checkbox" name="available" value="true"&gt;&lt;/td&gt;<br> &lt;/tr&gt;&lt;tr&gt; <br> &lt;td colspan="2"&gt;&lt;input type="submit" name="btnSave" value="Save"&gt;&lt;/td&gt;<br> &lt;/tr&gt;<br> &lt;/tbody&gt;<br> &lt;/table&gt;<br> &lt;/form&gt;<br> &lt;/body&gt;<br>&lt;/html&gt;



bookEdit.jsp

The JavaServer Page bookEdit.jsp reads the object book from the request and set the properties to the values of the form fields. In the first line the package de.laliluna.tutorial.library and all subordinated packages are imported to the jsp file. It is called a jsp-directive. This directive is similar to the import command within a java class.

The source code looks like the following.

&lt;%@ page import="de.laliluna.tutorial.library.*" %&gt;<br>&lt;%<br>	//lies das Objekt book aus dem Request<br>	Book book = (Book)request.getAttribute("book");<br>%&gt;<br><br>&lt;%<br>String path = request.getContextPath();<br>String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";<br>%&gt;<br><br>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;<br>&lt;html&gt;<br> &lt;head&gt;<br> &lt;base href="&lt;%=basePath%&gt;"&gt;<br><br> &lt;title&gt;Book edit page&lt;/title&gt; <br> &lt;/head&gt; <br> &lt;body&gt;<br> &lt;form name="edit" action="bookEdit" method="post"&gt;<br> &lt;table border="1"&gt;<br> &lt;tbody&gt;<br> &lt;tr&gt; <br> &lt;td&gt;Author:&lt;/td&gt;<br> &lt;td&gt;&lt;input type="text" name="author" value="&lt;%=book.getAuthor()%&gt;"&gt;&lt;/td&gt; <br> &lt;/tr&gt;&lt;tr&gt; <br> &lt;td&gt;Title:&lt;/td&gt; <br> &lt;td&gt;&lt;input type="text" name="title" value="&lt;%=book.getTitle()%&gt;"&gt;&lt;/td&gt;<br> &lt;/tr&gt;&lt;tr&gt;<br> &lt;td&gt;Available:&lt;/td&gt;<br> &lt;td&gt;&lt;input type="checkbox" name="available" value="true" &lt;%<b> if</b>(book.isAvailable()) out.println("checked"); %&gt;&gt;&lt;/td&gt;<br> &lt;/tr&gt;&lt;tr&gt; <br> &lt;td colspan="2"&gt;&lt;input type="submit" name="btnSave" value="Save"&gt;&lt;/td&gt;<br> &lt;/tr&gt;<br> &lt;/tbody&gt;<br> &lt;/table&gt;<br> &lt;input type="hidden" name="id" value="&lt;%=book.getId()%&gt;"&gt;<br> &lt;/form&gt;<br> &lt;/body&gt;<br>&lt;/html&gt;


bookList.jsp

The jsp file bookList.jsp displays the list of books, saved by the servlet. An array list of books is read from the request and looped over. Within the for loop we print out the properties of the books with the method println(..).

&lt;%@ page language="java" import="java.util.*" %&gt;<br>&lt;%@ page import="de.laliluna.tutorial.library.*" %&gt;<br><br>&lt;%<br>String path = request.getContextPath();<br>String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";<br>%&gt;<br><br>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;<br>&lt;html&gt;<br> &lt;head&gt;<br> &lt;base href="&lt;%=basePath%&gt;"&gt;<br><br> &lt;title&gt;Book list page&lt;/title&gt;<br> &lt;/head&gt;<br> &lt;body&gt;<br> &lt;table border="1"&gt;<br> &lt;tbody&gt;<br> &lt;tr&gt;<br> &lt;td&gt;Author&lt;/td&gt;<br> &lt;td&gt;Book name&lt;/td&gt;<br> &lt;td&gt;Available&lt;/td&gt;<br> &lt;td&gt;&amp;nbsp;&lt;/td&gt;<br> &lt;td&gt;&amp;nbsp;&lt;/td&gt;<br> &lt;/tr&gt;<br> &lt;%	  <br>	  	//lies die Liste der B�cher aus dem Request<br>	  	ArrayList arrayList = (ArrayList)request.getAttribute("books");<br><br>	  	//loope �ber die Liste von B�chern und gibt die Eigenschaften aus<br><b>	  	for </b>(Iterator iter = arrayList.iterator(); iter.hasNext();) {<br>	  		Book element = (Book) iter.next();<br><br>			out.println("&lt;tr&gt;");<br>			out.println("&lt;td&gt;" + element.getAuthor() + "&lt;/td&gt;");<br>			out.println("&lt;td&gt;" + element.getTitle() + "&lt;/td&gt;");<br><b>			if</b>(element.isAvailable())<br>				out.println("&lt;td&gt;&lt;input type="checkbox" name="available" value="true" disabled checked&gt;&lt;/td&gt;");<br>			else<br>				out.println("&lt;td&gt;&lt;input type="checkbox" name="available" value="true" disabled&gt;&lt;/td&gt;");<br><br>			out.println("&lt;td&gt;&lt;a href="bookEdit?do=edit&amp;id=" + element.getId() + ""&gt;Edit&lt;/a&gt;&lt;/td&gt;");<br>			out.println("&lt;td&gt;&lt;a href="bookEdit?do=delete&amp;id=" + element.getId() + ""&gt;Delete&lt;/a&gt;&lt;/td&gt;");<br>			out.println("&lt;/tr&gt;");<br>	  	}<br>	  %&gt;<br> &lt;/tbody&gt;<br> &lt;/table&gt;<br> &lt;br&gt;<br> &lt;a href="bookEdit?do=add"&gt;Add a new book&lt;/a&gt;<br> &lt;/body&gt;<br>&lt;/html&gt;<br>



We have finished the JavaServer pages to display the data.



Default JSP

When the user call the project in the browser with http://localhost:8080/LibraryWeb/ , we want to redirect him to a welcome page. Create an index.jsp file in /WebRoot. This jsp file redirects to the page, which displays the list of books.

Change the source code to the following.

&lt;%<br>	//redirect to the book list servlet<br>	response.sendRedirect("bookList");<br>%&gt;





Edit the web.xml

In the next step, we edit the configuration file of the project, the web.xml.

Open the file web.xml and add the following configuration.

The tag <servlet-name> assigns a name to our servlet class. With this name we can identify the servlet in the web.xml. <servlet-class> define the class for this name. Within the tag <servlet-mapping> we assign a address (URL) to a servlet, so a user can later execute this servlet by calling this address in his browser.

The servlets are called with /bookList and /bookEdit.

&lt;web-app&gt;<br>&lt;servlet&gt;<br> &lt;servlet-name&gt;BookList&lt;/servlet-name&gt;<br> &lt;servlet-class&gt;de.laliluna.tutorial.library.servlets.BookList&lt;/servlet-class&gt;<br>&lt;/servlet&gt;<br>&lt;servlet-mapping&gt;<br> &lt;servlet-name&gt;BookList&lt;/servlet-name&gt;<br> &lt;url-pattern&gt;/bookList&lt;/url-pattern&gt;<br>&lt;/servlet-mapping&gt;<br><br>&lt;servlet&gt;<br> &lt;servlet-name&gt;BookEdit&lt;/servlet-name&gt;<br> &lt;servlet-class&gt;de.laliluna.tutorial.library.servlets.BookEdit&lt;/servlet-class&gt;<br>&lt;/servlet&gt;<br>&lt;servlet-mapping&gt;<br> &lt;servlet-name&gt;BookEdit&lt;/servlet-name&gt;<br> &lt;url-pattern&gt;/bookEdit&lt;/url-pattern&gt;<br>&lt;/servlet-mapping&gt;<br>&lt;/web-app&gt;



Thats all.



Test the application

Deploy the project to the jboss.


deploy-project.gif

Test your application http://localhost:8080/LibraryWeb