Building Web Applications Using Servlets - Java30
Building Web Applications Using Servlets - Java30
Table of Contents Chapter 1: Web/HTTP Overview Chapter 2: Servlets Technology Chapter 3: How to write servlets code? Chapter 4: Accessing Databases with JDBC Chapter 5: Getting Familiar with HTTP package Chapter 6: Session Management
Chapter 1
Web/HTTP Overview
Chapter 1 Outline
Overview of HTTP Protocol Request and Response System Architectures Developing Web Applications in Java
HTTP
What is HTTP?
Hyper Text Transfer Protocol. Stateless Protocol. Basic Scenario.
HTTP components:
HTTP Request. HTTP Response.
HTTP
1.Establishes Tcp/Ip connection.
Server
Client
2.Sends Request.
3.Receives Response.
Web Server
Client Browser
4.Closes connection.
URL
http://163.121.12.2/webindex
Protocol Actual Path URI
Example:
Get /servlet /default.jsp HTTP/1.1 Post / servlet /index.jsp HTTP/1.1
HTTP Response
HTTP Response consists of 3 components: 1. Response Line (Protocol/Version Status Code Description):
Examples:
HTTP/1.1 200 HTTP/1.1 404 OK error
Status Code Ranges: 100-199 informational, the client must respond with an action 200-299 : request is successful 300-399 : for Redirection , it includes a Location header indicating the new address 400-499 :indicates an error by the client 500-599 : indicates an error by the server
JavaTM Education & Technology Services
Copyright Information Technology Institute 10
System Architecture
Typically we got 3 logical layers between client browser and web server :
Handle UI & User Interaction Presentation Programming logic Business logic Data Base Acess The data layer
Web Server
ASP
Web container
Mobile
HTTP XML
Web Tier
Business
Desktop RMI
DB
COBOL
Legacy SOAP
EJB Container
SOAP
Application Server
JavaTM Education & Technology Services
17
Web Technologies
CGI (Common Gateway Interface) Cold Fusion Server Side Java Script (SSJS) PHP Servlet JSP ASP ASP.NET
JavaTM Education & Technology Services
18
Chapter 2
Servlets Technology
Chapter 2 Outline
Advantages of Servlets
Servlet Container
Servlet Life Cycle Building and Deploying a Web Application
What is a Servlet?
Browser
Servlet
Request
Process results (access database) Format results and produce HTML Send page back to client
Success or failure
Response
A Servlet is a Java program that runs on a server, that produces dynamic pages typically in response to client requests. Servlet main jobs:
It reads and process implicit and explicit data sent by the client Send the implicit / explicit data to the client with a proper format
Advantages of Servlets
Performance
Portability (supported by many web servers) Rapid development cycle (rich library , high-level utilities)
Secure
Inexpensive
Servlet Container What is a Servlet container ? Its actually the interface between the servlet class and the client requests. Is a container that is responsible for
loading , processing and unloading the servlets. Managing servlets.
Servlet
Web Server
Response
1 Load
2 Initialize init()
3 Execute service()
4
Destroy destroy()
The web application may also contain html pages, jsp pages, tld files (tag library descriptors), images or any other resource files.
JavaTM Education & Technology Services
29
What is the deployment descriptor ? Contains meta-data for a Web Application and that is used by the container when loading a Web Application.
It identifies all the elements contained in the web application for the servlet container to be able to know them It maps them into URL patterns to be able to call them as clients It contains configuration settings specific to that application.
5. Run Tomcat. 6. Open your browser (e.g. Internet Explorer) and invoke the servlet using its specific URL (http://domain-name/virtual-directory/servlet-url) Example: http://localhost:8080/iti/MyServletURL
JavaTM Education & Technology Services
Copyright Information Technology Institute 34
Chapter 3
How to write servlets code?
Chapter 3 Outline
Servlets package structure
javax.servlet package
Servlet Interface ServletConfig Interface The ServletContext Interface The ServletRequest Interface The ServletResponse interface The GenericServlet Wrapper class
javax.servlet
http
JSP
el
tagext
javax.servlet.*
javax.servlet.* (contd)
Servlet Interface
Servlet : its the basic interface , any servlet must implements it directly or indirectly It consists of 5 main methods :
init (ServletConfig config) service( ServletRequest , ServletResponse) destroy() getServletConfig() getServletInfo()
Servlet Example
The following code is a typical implementation of the interface:
import javax.servlet.*; import java.io.*; public class MyServlet implements Servlet { public void init(ServletConfig config) throws ServletException { System.out.println("I am inside the init method"); } public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); Write to the response PrintWriter out = response.getWriter(); out.println(<br>Welcome to Servlets and JSP Course"); System.out.println("I am inside the service method"); }
JavaTM Education & Technology Services
Copyright Information Technology Institute 41
SingleThreadModel Interface
The SingleThreadModel interface is used to prevent simultaneous access to instance variables by multiple threads. Only one request thread accesses a single instance of the servlet at a time. The server queues the requests and passes them one at a time to a single servlet instance. Or the server creates a pool of multiple instances, each handles one request at a time.(however, unsafe).
JavaTM Education & Technology Services
Copyright Information Technology Institute 43
ServletConfig Interface
The ServletConfig interface is used by a servlet to obtain any configuration information written specifically for it in the deployment descriptor file (web.xml). It is passed by the servlet container to the init(..) method as parameter. Such configuration information is better written in the xml file instead of hard coding it inside the servlets code. Such approach makes it easy to alter such information after the servlets source code has been compiled. Each servlet is passed its own set of configuration parameters.
JavaTM Education & Technology Services
Copyright Information Technology Institute 45
ServletConfig Example
The following code demonstrates the use of the config:
public class ServletConfigTest implements Servlet { ServletConfig myConfig; public void init(ServletConfig config) throws ServletException { myConfig = config; } public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { String str = myConfig.getInitParameter(AdminEmail); PrintWriter out = response.getWriter(); out.println (The administrator email is: + str); } }
JavaTM Education & Technology Services
Copyright Information Technology Institute 48
Lab Exercise
Assignment
Use servletConfig to pass variables from web.xml to the servlet and display it in the response.
Like DB connection Statement. DB user name and password.
<init-param> <param-name> DatabaseAddress </param-name> <param-value> 163.121.12.25 </param-value> </init-param>
<init-param> <param-name> userName </param-name> <param-value> iTi </param-value> </init-param> <init-param> <param-name> password </param-name> <param-value> iTi </param-value> </init-param> JavaTM Education & Technology Services
Copyright Information Technology Institute 50
ServletContext Interface
The context is the environment in which the servlets of a web application run. There is only one context per web application (i.e. all the servlets of a web application have references to the same context). The deployment descriptor (web.xml) can include tags (context params) that are general for the whole web application. The ServletContext interface defines a set of methods that a servlet uses in order to obtain such context parameters.
JavaTM Education & Technology Services
Copyright Information Technology Institute 51
In order to obtain a reference to the context, the following method of the ServletConfig interface is used: ServletContext getServletContext()
The whole <context-param> tag is repeated for each parameter. It should be placed at the beginning of the file.
JavaTM Education & Technology Services
Copyright Information Technology Institute 53
Example
public class servletContext implements Servlet { ServletConfig sConf; public void init(ServletConfig config) throws ServletException { sConf = config; } public void service(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException { ServletContext servletContext = sConf.getServletContext(); PrintWriter out = response.getWriter(); String str= servletContext. getInitParameter(AdminEmail); out.println(AdminEmail is: " + str); } ..}
JavaTM Education & Technology Services
Copyright Information Technology Institute 55
Example
public class servletContext implements Servlet { ServletConfig sConf; public void init(ServletConfig config) throws ServletException { sConf = config; } public void service(ServletRequest request,ServletResponse response)throws ServletException, IOException { ServletContext servletContext = sConf.getServletContext(); PrintWriter out = response.getWriter(); servletContext.setAttribute(MyPassword,iti); } ..}
JavaTM Education & Technology Services
Copyright Information Technology Institute 56
Setter Servlet
Example
public class servletContext implements Servlet { ServletConfig sConf; public void init(ServletConfig config) throws ServletException { sConf = config; } public void service(ServletRequest request,HttpServletResponse response)throws ServletException, IOException { ServletContext servletContext = sConf.getServletContext(); PrintWriter out = response.getWriter(); String str= servletContext.getAttribute(MyPassword); out.println(MyPassword is: " + str); } ..}
Getter Servlet
Servlet1
Servlet2
Servlet1
Servlet2
ServletConfig1
ServletConfig1
ServletConfig2
ServletConfig2
Web Application 2
Copyright Information Technology Institute
Web Application 1
JavaTM Education & Technology Services
58
Lab Exercise
Assignment
Sharing info between servlets: A servlet will assign a username and password attributes , and another servlet will display it Your servlets should read the initialized parameters given to them by <context-param> tag in web.xml
<context-param> <param-name>Country</param-name> <param-value>Egypt</param-value> </context-param>
ServletRequest Interface
The ServletRequest defines an object that is used to hold information coming from the user's request, including parameter name-value pairs, attributes, and an input stream. Commonly used methods:
Enumeration getParameterNames() String getParameter(String paramName) String[] getParameterValues(String paramName) String getRemoteHost()
In order for the servlet to get the parameters from the request, the following code is written in the service(..) method:
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String str = request.getParameter(MyName"); out.println(The user input is: + str); }
ServletResponse Interface
The ServletResponse interface defines an object that carries the servers response to the user (i.e. back to the clients browser). Commonly used methods:
PrintWriter getWriter() setContentType(String mimeType) setContentLength(int len)
ServletResponse Example
Sending response in Excel Sheet Format:
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { response.setContentType("application/vnd.ms-excel"); PrintWriter out = response.getWriter(); out.println("\t jan \t feb \t march \t total"); out.println("salary \t100 \t200 \t300 \t=sum(B2:D2)"); }
Chapter 4
Accessing Databases with JDBC
Chapter 4 Outline
Review on JDBC Steps to Work with a Database Sample Applications of Database Operations Online SQL Tool
Review on JDBC
JDBC API: set of Java interfaces for connecting to any DBMS and executing SQL statements. Packages are:
java.sql package: basic functionalities. javax.sql package: advanced functionalities.
JDBC Driver: Vendor-specific implementation of JDBC interfaces. Every DBMS has JDBC driver(s). Connection String: A special DBMS-specific string that is used to connect to the database, for example:
MS Access: jdbc:odbc:DataSourceName Oracle (thin): jdbc:oracle:thin:@host:port:sid
Second Step:
Obtain the connection through the Connection interface, for example: Connection con = DriverManager.getConnection( "jdbc:odbc:mydsn",userName",password");
Fourth Step:
After obtaining the ResultSet, extract data through the getter methods, for example:
while(rs.next()) { out.println(rs.getInt(1) + : + rs.getString( FNAME )); }
Note: You can get information about the retrieved ResultSet by using the method: getMetaData()
JavaTM Education & Technology Services
Copyright Information Technology Institute 72
By default, only one ResultSet object per Statement object can be open at the same time. If the default ResultSet object is obtained, then columns within each row should be read in left-to-right order, and each column should be read only once.
Lab Exercise
Login :
Write an HTML page that has two text input fields for the users name and mail, along with a submit button. Upon pressing the submit button, the page should send the data to a servlet. Checking the username and password against the database.
JavaTM Education & Technology Services
Copyright Information Technology Institute 78
Search: Bonus
develop a search servlet for products.
Chapter 5
Getting Familiar with HTTP Package
javax.servlet.http.*
javax.servlet.http.* (contd)
Classes
Cookie HttpServlet
The HTTPServlet Class It extends from javax.servlet.GenericServlet It contains extra methods like :
doPost() doGet () doOptions() doPut() doDelete() doTrace()
HttpServlet
doGet()
service()
Response
doPost()
HttpServlet Example
The following code demonstrates the use of the doGet(..) method:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(text/html); PrintWriter out = response.getWriter(); out.println("<HTML>"); out.println("<BODY>"); out.println("The servlet has received a GET request." + "Now, click on the button below."); out.println("<BR>"); out.println("<FORM METHOD=POST>"); out.println("<INPUT TYPE=SUBMIT VALUE=Submit>"); out.println("</FORM>"); out.println("</BODY>"); out.println("</HTML>"); }
JavaTM Education & Technology Services
Copyright Information Technology Institute 86
HttpServletRequest Interface
Common methods:
Enumeration getHeaderNames() String getHeader(String headerName) Enumeration getHeaders(String headerNames) String getQueryString() HttpSession getSession(boolean create) Cookie[] getCookies()
HttpServletResponse Interface
Common methods:
setStatus(int statusCode) sendRedirect(String newLocation) sendError(int statusCode, String msg) addCookie(Cookie cookie) setHeader(String headerName, String value) setIntHeader(String headerName, int value) setDateHeader(String headerName, long milliseconds)
Status Code
You have to set the status code and response headers before writing any document content to the response that will be sent back to the client. For the parameter of setStatus(..) method, you can either use explicit numbers of your own, or use the static constant values defined in the HttpServletResponse interface (e.g. for status code 404 use SC_NOT_FOUND).
Lab Exercise
Assignment
Assignment
Registration : add a user the database. Continue the login assignment of the last chapter by checking the username and password against the database instead of hard coding the check inside the servlet.
User the request dispatchers forward method to direct the user to a success page or failure page. Display :develop a servlet that views data employees data from the database (id, name, email, salary, etc) in a well formatted HTML table:
Provide the ability to add a new employee, edit, or delete an existing one.
The location parameter can either be the relative URL of a page or its fully qualified URL.
sendRedirect Example
The following code demonstrates the use of sendRedirect(..) method:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { . . out.println(<FORM method= POST>); out.println("<BR> Username: <INPUT TYPE=TEXT NAME=userName>"); out.println("<BR> Password: <INPUT TYPE=PASSWORD NAME=password>"); out.println("<BR> <INPUT TYPE=SUBMIT VALUE=Submit>"); out.println("</FORM>"); . . }
JavaTM Education & Technology Services
Copyright Information Technology Institute 96
Response Buffer
For committing a response, a servlet sends the string output only once when it finishes processing or when the buffer is full. Enabling/Increasing the size of the response buffer is useful in enhancing the servlets performance in case of large response content. It is ON by default and the default size is 8192 characters You can can specify the buffer size of the response, using the method: response.setBufferSize(..)
Note: Call this method before writing any output to the response.
JavaTM Education & Technology Services
Copyright Information Technology Institute 100
RequestDispatcher Interface
The RequestDispatcher interface has 2 methods only:
RequestDispatcher - include
The include(..) method is used to include the output of another servlet or the content of another page (html, JSP, etc) to the current servlet. This technique is famously used in websites to include a certain header or footer to all the pages of the website. It may also be used to include some common JavaScript functions to many web pages. The original servlet can write to the response before and after the included servlet or page writes to the response.
JavaTM Education & Technology Services
Copyright Information Technology Institute 102
RequestDispatcher - forward
The forward(..) method passes the processing of an HTTP request from the current servlet to another servlet or JSP (i.e. gives up the control for another servlet or jsp). It is up to the new servlet or JSP to write to the response object and then commit it to the client. Any output written to the response object by the original servlet will be lost (i.e. dont write to the response before forwarding to another servlet). The original servlet can perform some initial tasks on the request object before forwarding it (e.g. put additional attributes on it, which will be used by the new servlet or jsp).
JavaTM Education & Technology Services
Copyright Information Technology Institute 103
Using RequestDispatcher
There are two ways to get a dispatcher for the desired destination servlet or page. Either from the request, or from the context. From the ServletRequest:
getRequestDispatcher(String path)
//relative path or fully qualified path
getNamedDispatcher(String servletName)
// the servlet name in the web.xml file
JavaTM Education & Technology Services
Copyright Information Technology Institute 104
OR:
rd.forward(request, response); Note: If you use include or forward from a doPost method, then the doPost method of the second servlet will be invoked. If you use them from a doGet method, then the doGet method of the second servlet will be invoked. Therefore, it is advisable to implement both doGet and doPost in the destination servlet (write the code in one of the two methods, and call it from the other method).
JavaTM Education & Technology Services
Copyright Information Technology Institute 105
sendRedirect VS forward
sendRedirect(..):
goes through a round trip to the client side then back to the server. The clients original request will be lost. To pass information, append a query string to the new locations URL.
forward(..):
Redirects the request internally inside the server. Both the request and the response are passed to the new resource.
Lab Exercise
Chapter 6
Session Management
Chapter 6 Outline
Session Management Techniques URL Rewriting
Session Management
Session management is the ability to keep track of (maintain) the users state through several web pages. Remember: the problem with the HTTP protocol is that it is a stateless protocol. Session management is very useful for the following:
Identifying (remembering) the user during ecommerce sessions. Remembering usernames and passwords throughout multiple pages. Customizing websites view according to users preferences. Focused advertising.
The main idea of maintaining a session is to send a certain token (identifier) with the response.
JavaTM Education & Technology Services
Copyright Information Technology Institute 114
URL Rewriting
URL rewriting is simply appending token(s) to the URL of the next page or servlet. It starts by a question mark Tokens are strings in the form of parameter=value Tokens are separated by an ampersand (&) It is an easy way but has the following concerns:
Supports up to 2000 characters only. The parameters are exposed in the URL. You will need to encode special characters (e.g. spaces to + and special characters to %XX).
Example:
http://www.site.com/mySerevlet?param1=value1¶m2=value2
JavaTM Education & Technology Services
Copyright Information Technology Institute 116
Hidden Fields
Forms can include hidden fields among the normal input fields.
Therefore, information can be stored in hidden fields and then retrieved from the request in the next page or servlet. The concern is that the user can view the values of the hidden fields by viewing the html source of the page from within the browser.
Example:
out.print("<INPUT TYPE=HIDDEN Name=id VALUE= +myId+ ">");
Cookies
A cookie is a small piece of information (name and value) that is passed back and forth in the HTTP request and response. The cookie sent by a servlet to the client will be passed back to the server when the client requests another page from the same application. Cookies are represented as a class in the HTTP package.
Niether the name nor the value can contain commas, semicolons, white space, nor begin with a $ character.
JavaTM Education & Technology Services
Copyright Information Technology Institute 118
Cookies contd
To add a cookie to the response:
response.addCookie(c1);
Cookies contd
Cookies must be added to the response before writing any other response elements. Advantages of cookies:
The values of the cookies are not directly visible. You don't need to use a form tag. Cookies are not a serious security threat.
Cookies contd
You can detect whether a browser enables cookies or not, and display a message that asks the user to enable cookies. To detect this, you can do the scenario of adding a cookie to the response of the first servlet, then redirecting to a second servlet that checks the existence of the cookie in the request. To redirect the clients browser to another page you can use either of the following:
response.sendRedirect(..) <META HTTP-EQUIV=Refresh CONTENT=time to wait ;URL=url>
Note: in both cases you have to use a relative URL, not a fully qualified one.
JavaTM Education & Technology Services
Copyright Information Technology Institute 121
Cookies contd
A cookie can either be stored on session level or on persistence level. A session level cookie is a cookie that is stored in the browsers memory and deleted when the user quits the browser. A persistent cookie is stored on the clients hard disk. To make your cookie persistent, use the method setMaxAge(int seconds) before adding it to the response. Example: c1.setMaxAge(60*60*24*7); // One week
JavaTM Education & Technology Services
Copyright Information Technology Institute 122
Session Objects
The best and most powerful was is to use session objects (defined by the HTTPSession interface). For each user, the servlet container can create an HttpSession object that is associated with that user only. A session object acts like a Hashtable into which you can store any number of key/object pairs. It is accessible from other servlets or jsp pages in the same application (per user).
Servlet1
1
1234
Servlet2 3 Browser
HttpSession
Common methods:
Enumeration getAttributeNames() Object getAttribute(String key) void setAttribute(String key, Object value) void removeAttribute (String key) // e.g. log out long getCreationTime() String getId() long getLastAccessedTime() void setMaxInactiveInterval(int seconds) int getMaxInactiveInterval() ServletContext getServletContext() void invalidate() boolean isNew()
Invalidating a Session
A session can become invalid in 3 cases:
The default session timeout has elapsed (configured in the servlet container for all web applications). The maximum inactive interval time of the session has elapsed (specified by calling the method setMaxInactiveInterval(..)). The programmer decides to invalidate a session (by calling the invalidate() method).
Lab Exercise
If the user has disabled the use of cookies, send him an error message asking him to enable cookies. Bonus
2. User login
Keep user s login information on the session and access it in another page
References & Recommended Reading Core Servlets and JSP. Java for the Web with Servlets, JSP, and EJB. Manning JSTL in Action. Sun presentations. Oracle presentations. SCJWD study guide.