Java Server Pages combined with servlets in action. Generals. Java Servlets



Similar documents
Creating Java EE Applications and Servlets with IntelliJ IDEA

Web Container Components Servlet JSP Tag Libraries

An introduction to web programming with Java

We are not repeating all the basics here. Have a look at the basic EJB tutorials before you start this tutorial.

How To Understand The Architecture Of Java 2Ee, J2Ee, And J2E (Java) In A Wordpress Blog Post

Controlling Web Application Behavior

J2EE-Application Server

Form Handling. Server-side Web Development and Programming. Form Handling. Server Page Model. Form data appended to request string

Java EE Introduction, Content. Component Architecture: Why and How Java EE: Enterprise Java

Web Applications. For live Java training, please see training courses at

Web Development in Java Live Demonstrations (Live demonstrations done using Eclipse for Java EE 4.3 and WildFly 8)

Introduction to J2EE Web Technologies

Author: Sascha Wolski Sebastian Hennebrueder Tutorials for Struts, EJB, xdoclet and eclipse.

Development. with NetBeans 5.0. A Quick Start in Basic Web and Struts Applications. Geertjan Wielenga

How to use JavaMail to send

Java Web Programming. Student Workbook

DTS Web Developers Guide

Developing an EJB3 Application. on WebSphere 6.1. using RAD 7.5

SSC - Web applications and development Introduction and Java Servlet (II)

JBoss Portlet Container. User Guide. Release 2.0

Web Application Programmer's Guide

This tutorial gives you an overview about the StrutsTestCases extension of JUnit and example how you can use it to test your Struts application.

Principles and Techniques of DBMS 5 Servlet

Handling the Client Request: Form Data

Implementing the Shop with EJB

Glassfish, JAVA EE, Servlets, JSP, EJB

Application Security

Database Applications Recitation 10. Project 3: CMUQFlix CMUQ s Movies Recommendation System

Java Servlet 3.0. Rajiv Mordani Spec Lead

PowerTier Web Development Tools 4

CS108, Stanford Handout #33 Young. HW5 Web

WebSphere and Message Driven Beans

PA165 - Lab session - Web Presentation Layer

Java Servlet Tutorial. Java Servlet Tutorial

Piotr Nowicki's Homepage. Java EE 6 SCWCD Mock Exam. "Simplicity is the ultimate sophistication." Important!

Session Tracking Customized Java EE Training:

Outline. CS 112 Introduction to Programming. Recap: HTML/CSS/Javascript. Admin. Outline

Managing Data on the World Wide-Web

Servlet 3.0. Alexis Moussine-Pouchkine. mercredi 13 avril 2011

JSP Java Server Pages

Web Application Architecture (based J2EE 1.4 Tutorial)

Pure server-side Web Applications with Java, JSP. Application Servers: the Essential Tool of Server-Side Programming. Install and Check Tomcat

Tutorial: Building a Web Application with Struts

Struts 2 - Practical examples

Ch-03 Web Applications

In this chapter, we lay the foundation for all our further discussions. We start

Struts Tools Tutorial. Version: M5

CHAPTER 9: SERVLET AND JSP FILTERS

CSI 2132 Lab 8. Outline. Web Programming JSP 23/03/2012

Building Web Applications with Servlets and JavaServer Pages

Servlet and JSP Filters

Virtual Open-Source Labs for Web Security Education

ShoreTel Enterprise Contact Center 8 Installing and Implementing Chat

Web Programming II JSP (Java Server Pages) ASP request processing. The Problem. The Problem. Enterprise Application Development using J2EE

Crystal Reports for Eclipse

Programming on the Web(CSC309F) Tutorial: Servlets && Tomcat TA:Wael Aboelsaadat

Multiple vulnerabilities in Apache Foundation Struts 2 framework. Csaba Barta and László Tóth

Servers, Dynamic Web Projects, and Servlets

CONTROLLING WEB APPLICATION BEHAVIOR WITH

JBoss SOAP Web Services User Guide. Version: M5

J2EE Web Development. Agenda. Application servers. What is J2EE? Main component types Application Scenarios J2EE APIs and Services.

Oracle Hyperion Financial Management Custom Pages Development Guide

ACM Crossroads Student Magazine The ACM's First Electronic Publication

NetBeans IDE Field Guide

Developing Web Applications using JavaServer Pages and Servlets

OPENRULES. Release TUTORIAL Cloud Application Development

Getting Started with Web Applications

Hello World RESTful web service tutorial

Class Focus: Web Applications that provide Dynamic Content

Setup and Administration for ISVs

Java 2 Web Developer Certification Study Guide Natalie Levi

Simplify Your Web App Development Using the Spring MVC Framework

Controller annotati. con Spring MVC 2.5

INTRODUCTION TO WEB TECHNOLOGY

WESTERNACHER OUTLOOK -MANAGER OPERATING MANUAL

Oracle Hyperion Financial Management Developer and Customization Guide

Web Application Development on a Linux System With a DB2 Database By Alan Andrea

2. Follow the installation directions and install the server on ccc

CS506 Web Design and Development Solved Online Quiz No. 01

Integrating Servlets and JSP: The Model View Controller (MVC) Architecture

Developing Java Web Applications with Jakarta Struts Framework

Intellicus Single Sign-on

2.8. Session management

7 Web Databases. Access to Web Databases: Servlets, Applets. Java Server Pages PHP, PEAR. Languages: Java, PHP, Python,...

Configure a SOAScheduler for a composite in SOA Suite 11g. By Robert Baumgartner, Senior Solution Architect ORACLE

Building Web Services with Apache Axis2

Introduction to Web Technologies

Wicket Application Development

WIRIS quizzes web services Getting started with PHP and Java

Developing WCM based WebSphere Portal application using IBM Rational Application Developer

WebNow. Installation and Setup Guide. ImageNow Version: 6.7.x Environment: Windows Web Application Server: Tomcat

Supplement IV.E: Tutorial for Tomcat. For Introduction to Java Programming By Y. Daniel Liang

SESM Tag Library. Configuring a Tag Library APPENDIX

Specialized Programme on Web Application Development using Open Source Tools

Transcription:

Java Server Pages combined with servlets in action 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 http://www.laliluna.de/tutorials.html Tutorials for Struts, EJB, xdoclet and eclipse. Date: September, 23 th 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 It reads and processes data, which a user inputs in a HTML form on a web page. Other informations can be processed, e.g. what browser or system will be used. It generate results with the existing data, calls the business logic directly in the servlet or another class, which contains the logic or executes a database query. The results are formated. If the Browser expects an answer in the HTML format, then the results must be formatted in accordance with the standard. It is possible to return different formats of data with a servlet. (gif, jpeg, doc, etc.). Suitable answer parameters are set. Befor the servlet return the data to the browser, it sends some parameter. The parameter contains the format, that will returned by the servlet, what time the browser use to cache the site and some more.

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. id title author available 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 { private long id = 0; private String title = ""; private String author = ""; private boolean available = false; // Contructor public Book(){ // Contructor to initial the properties public Book(long id, String author, String title, boolean available) { this.id = id; this.author = author; this.title = title; this.available = available; public boolean isavailable() { return available;

public void setavailable(boolean available) { this.available = available; public long getid() { return id; public void setid(long id) { this.id = id; public String getauthor() { return author; public void setauthor(string author) { this.author = author; public String gettitle() { return title; public void settitle(string title) { this.title = title;

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) throws ServletException, IOException { //hole die session des requests HttpSession session = request.getsession(); //initialisiere die Datenbank Klasse SimulateDB simulatedb = new SimulateDB(); //lies alle Bücher aus der Datenbank Klasse Collection collection = simulatedb.getallbooks(session); //setze die zurück gegebene Liste der Bücher im Request request.setattribute("books", collection); //hole den Request Dispatcher für die JSP Datei RequestDispatcher dispatcher = getservletcontext(). getrequestdispatcher("/jsp/booklist.jsp"); //leite auf die JSP Datei zum Anzeigen der Liste weiter dispatcher.forward(request, response); 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) throws ServletException, IOException { //rufe die doget(...) Methode auf this.doget(request, response); 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) throws ServletException, IOException { //hole die session des requests HttpSession session = request.getsession();

//initialisiere die Datenbank Klasse SimulateDB simulatedb = new SimulateDB(); //lies den Parameter do aus dem Request String action = request.getparameter("do"); //lies den Parameter id aus dem Request long id = 0; try{ id = Long.parseLong(request.getParameter("id")); catch(numberformatexception e){ //hinzufügen eines Buches if(action.equals("add")){ //hole den Request Dispatcher für die JSP Datei RequestDispatcher dispatcher = getservletcontext(). getrequestdispatcher("/jsp/bookadd.jsp"); //leite auf die JSP Datei zum Anlegen eines Buches weiter dispatcher.forward(request, response); //bearbeiten eines Buches else if(action.equals("edit")){ //lies das Buch anhand seiner Id aus Book book = simulatedb.loadbookbyid(id, session); //setze das Buch Objekt im request request.setattribute("book", book); //hole den Request Dispatcher für die JSP Datei RequestDispatcher dispatcher = getservletcontext(). getrequestdispatcher("/jsp/bookedit.jsp"); //leite auf die JSP Datei zum Bearbeiten eines Buches weiter dispatcher.forward(request, response); //löschen eines Buches else if(action.equals("delete")){ //lösche das Buch anhand der Id simulatedb.deletebookbyid(id, session); //Redirect Weiterleitung zum BookList Servlet response.sendredirect(request.getcontextpath() + "/booklist"); 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 { //hole die session des requests HttpSession session = request.getsession();

//initialisiere die Datenbank Klasse SimulateDB simulatedb = new SimulateDB(); //lies den Parameter id aus dem Request long id = 0; try{ id = Long.parseLong(request.getParameter("id")); catch(numberformatexception e){ //lies die Buch-Eigenschaften aus dem Request String author = request.getparameter("author"); String title = request.getparameter("title"); Boolean available = Boolean.valueOf(request.getParameter ("available")); //erstelle ein neues Buch Objekt Book book = new Book(id, author, title, available.booleanvalue()); //speichere das Buch Objekt simulatedb.savetodb(book, session); //Redirect Weiterleitung zum BookList Servlet response.sendredirect(request.getcontextpath() + "/booklist"); 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 bookedit.jsp booklist.jsp 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. <% String path = request.getcontextpath(); String basepath = request.getscheme()+"://"+request.getservername() +":"+request.getserverport()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basepath%>"> <title>book add page</title> </head> <body> <form name="edit" action="bookedit" method="post"> <table border="1">

value=""></td> <tbody> <tr> <td>author:</td> <td><input type="text" name="author" </tr><tr> <td>title:</td> <td><input type="text" name="title" value=""></td> </tr><tr> <td>available:</td> <td><input type="checkbox" name="available" value="true"></td> </tr><tr> <td colspan="2"><input type="submit" name="btnsave" value="save"></td> </tr> </tbody> </table> </form> </body> </html> 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. <%@ page import="de.laliluna.tutorial.library.*" %> <% //lies das Objekt book aus dem Request Book book = (Book)request.getAttribute("book"); %> <% String path = request.getcontextpath(); String basepath = request.getscheme()+"://"+request.getservername() +":"+request.getserverport()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basepath%>"> <title>book edit page</title> </head> <body> <form name="edit" action="bookedit" method="post"> <table border="1"> <tbody> <tr> <td>author:</td> <td><input type="text" name="author" value="<% =book.getauthor()%>"></td> </tr><tr> <td>title:</td> <td><input type="text" name="title" value="<% =book.gettitle()%>"></td> </tr><tr> <td>available:</td> <td><input type="checkbox" name="available" value="true" <% if(book.isavailable()) out.println("checked"); %>></td> </tr><tr>

<td colspan="2"><input type="submit" name="btnsave" value="save"></td> </tr> </tbody> </table> <input type="hidden" name="id" value="<%=book.getid()%>"> </form> </body> </html> 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(..). <%@ page language="java" import="java.util.*" %> <%@ page import="de.laliluna.tutorial.library.*" %> <% String path = request.getcontextpath(); String basepath = request.getscheme()+"://"+request.getservername() +":"+request.getserverport()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basepath%>"> <title>book list page</title> </head> <body> <table border="1"> <tbody> <tr> <td>author</td> <td>book name</td> <td>available</td> <td> </td> <td> </td> </tr> <% //lies die Liste der Bücher aus dem Request ArrayList arraylist = (ArrayList)request.getAttribute("books"); //loope über die Liste von Büchern und gibt die Eigenschaften aus for (Iterator iter = arraylist.iterator(); iter.hasnext();) { Book element = (Book) iter.next(); out.println("<tr>"); out.println("<td>" + element.getauthor() + "</td>"); out.println("<td>" + element.gettitle() + "</td>"); if(element.isavailable()) out.println("<td><input type=\"checkbox\" name=\"available\" value=\"true\" disabled checked></td>"); else out.println("<td><input type=\"checkbox\" name=\"available\" value=\"true\" disabled></td>"); out.println("<td><a href=\"bookedit?do=edit&id=" + element.getid() + "\">Edit</a></td>"); out.println("<td><a href=\"bookedit?do=delete&id=" + element.getid() + "\">Delete</a></td>"); out.println("</tr>"); %>

</tbody> </table> <br> <a href="bookedit?do=add">add a new book</a> </body> </html> 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. <% %> //redirect to the book list servlet response.sendredirect("booklist"); 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. <web-app> <servlet> <servlet-name>booklist</servlet-name> <servlet-class>de.laliluna.tutorial.library.servlets.booklist</servletclass> </servlet> <servlet-mapping> <servlet-name>booklist</servlet-name> <url-pattern>/booklist</url-pattern> </servlet-mapping> <servlet> <servlet-name>bookedit</servlet-name> <servlet-class>de.laliluna.tutorial.library.servlets.bookedit</servletclass> </servlet> <servlet-mapping> <servlet-name>bookedit</servlet-name> <url-pattern>/bookedit</url-pattern> </servlet-mapping> </web-app> Thats all.

Test the application Deploy the project to the jboss. Test your application http://localhost:8080/libraryweb