CPAN423 Enterprise Java Programming

Total Page:16

File Type:pdf, Size:1020Kb

CPAN423 Enterprise Java Programming

CPAN423 Enterprise Java Programming

Lecture #1: An Introduction to Servlets

Java is one of the programming languages that are used to build web applications. Servlets are java applications running on the server, to process the requests sent by the client and to send responses back. Any servlet must implement Servlet interface. The servlet package defines two abstract classes that implement Servlet interfaces, which are GenericServlet (from the javax.servlet package) and HTTPServlet (from the javax.servlet.http package). The HttpServlet extends the javax.servlet.GenericServlet and is used to handle HTTP requests.

Following are methods of interface Servlet  void init() This method is automatically called once during a servlet's execution cycle to initialize the servlet.  servletConfig getServletConfig() Returns a reference to an object that implements interface servletConfig. This object provides access to the servlet configuration information.  void service(HttpServletRequest req, HttpServletResponse res) Which is the first method get called on every servlet to respond to the client request. Both HttpServletRequest object ( req) and HttpServletRespond object ( res) provides an access to input and output stream that allows the servlet to read data from the client and send data to the client. Service method determines the request type and then call either doPost or doGet method of class HttpServlet in response to post or get request respectively.  String getServerInfo() Defines the servlet information, like author and version  void destroy() Called when the server terminates a servlet.

When the server runs the servlet, it creates an HttpServletRequest and HttpServletResponse object and passes them to service method, which in turn passes them to doPost, or doGet methods.

1 Class HTTPServlet define the following methods:

 void doPost(HttpServletRequest req, HttpServletResponse res) Process HTTP Post request.  void doGet(HttpServletRequest req, HttpServletResponse res) Process HTTP get request.  void doDelete(HttpServletRequest req, HttpServletResponse res) Process Delete request. Called in response to an HTTP delete request to delete a file from the server.  void doOption(HttpServletRequest req, HttpServletResponse res) Process Option request. Called in response to an HTTP options request to send information to the client regarding the HTTP options supported by the server.  void doPut(HttpServletRequest req, HttpServletResponse res) Process Put request. Called in response to HTTP request to store a file on the server.  void doTrace(HttpServletRequest req, HttpServletResponse res) Used for debugging. It returns an HTML page containing the header information sent by the client.

Following are some of the methods of interface HTTPServletResponse  void addCookie(Cookie cookie) Sends a new cookie to the client.  void addHeader(java.lang.String name, java.lang.String value) Adds a header.  void setStatus(int sc) Sets the HTTP status.  void setHeader(java.lang.String name, java.lang.String value) Sets a header.  void sendRedirect(java.lang.String location) Redirects the client to another page.  PrintWriter getWriter() Returns a PrintWriter with the proper character encoding for writing data to the client.  void setContentType(java.lang.String type) Sets the response content type.

Some of the methods of interface HTTPServletRequest are listed below:  String getAuthType() Gets the authentication type.

2  Cookie [] getCookies() Returns an array of all cookies sent by the client.  String getHeader(java.lang.String name) Returns the first value for the requested header.  Enumeration getHeaderNames() Returns an enumeration of all the headers sent by the client.  Enumeration getHeader(java.lang.String name) Returns all the values of the requested header.  String getMethod() Returns the HTTP method used by the client.  String getQueryString() Returns the request query string.  String getRequestedSessionId() Returns the session id.  HttpSession getSession() Returns the current session. Create one if necessary.  HttpSession getSession(boolean create) Returns a session.  String getParameter(java.lang.String name) Returns a form’s parameter.  Enumeration getParameterNames() Returns an enumeration of all the form parameter names.  String [] getParameterValues() Returns all the values of the form parameters.  void SetAttribute(java.lang.String name, java.lang.Object o) Sets an attribute value.  void removeAttribute(java.lang.String uri) Removes an attribute.  RequestDispatcher getRequestDispatcher(java.lang.String uri) Returns a request dispatcher for forwarding.

The servlet context is the environment where the servlet runs. It is created by the servlet container to access information about the servlet environment. We can bind objects into the Servlet context, which make them accessible by all servlets in the same web application. There is one servlet context object per a web application. It enables us to set and get application level data among all parts of the application. To get the servlet Context, call the method getServletContext(). Once we have a ServletContext object, we can call any method in the ServletContext interface. The most important methods are: getAttribute and setAttribute, and removeAttribute.

3 Reading Data in Servlet Sent by HTML form :

In Java Servlet all the form element that send a request to the servlet is handled automatically, We can use getParameter method of HttpServletRequest class to get the data that a certain HTML field has by passing field name-case sensitive as parameter to this function. For example assume we have two HTML text fields named UserName and UserPassword. To get the data contained In these field in the servlet we use: String name; String password; name=request.getParameter(“UserName”); password=request.getParameter(“UserPassword”);

Assuming that the HttpServletRequest object named request in my Servlet. We can get all the parameter names by using getParameterNames method of HttpServletRequest, this method return an enumeration that contain the parameter names in an unspecified order. We have to import java.util.* and since nextElement returns an Object we have to cast it back to String type.

Reading HttpRequest headers from a Servlets: getHeader method of HttpServletRequest returns a String if the specific header was presented and null if not. Also there are some other method that read some common headers like: getCookies, getMethod, getProtocol, getRequestURI, and some others (refer to java documentation for full details ).

Generating the server response:

The server response consist of status line, some response headers , a blank line and the document for example: HTTP/1.1 200 OK Content-Type: text/html

example of HTML This is my page

4 In most cases all the headers are optional except for Contet-Type. Servlets can perform many tasks like forward the user to another site, indicate the type of the document and so on by manipulating the status line. To set the status code we use setStatus method of HttpServletResponse. We can use another method named setHeader to set the location of the new redirected page.

The status code falls into the following categories: 100-199 informational- user should respond with some action 200-299 request was successful 300-399 indicate that file has moved and requires Location header indicating the new address 400-499 error by client 500-599 error by the server

Invoking Other Web Resource Web components can invoke other web resources while they execute. This can be done using two techniques. The first is by including the content of another resource. The second is by forwarding a request to another resource. Both techniques require obtaining a RequestDispacher object. For example assume that we want to invoke another servlet called myServlet. Then we need to call getRequestDispatcher method of the ServletContent as shown below:

String adr="/myServlet"; RequestDispatcher dispatcher =getServletContext().getRequestDispatcher(adr);

After that we can either include the content of myServlet servlet : dispatcher.include(req,res);

Or we can forward the request to myServlet servler : dispatcher.forward(req,res);

Installing Java-based web server: To run a servlet you need a Java based web server. Many web servers are available for free to download including Resin and Tomcat:

 Resin Web server:

5 You can get Resin- Enterprise Edition from http://www.caucho.com .The file name of this server is in the format resin-ee-x.x.x.zip. This server supports many technologies including JSP ,Servlets , Javabeans, Enterprise Javabeans , and XML.

After you download and unzip this web server, you can run it by executing the file: resin-x.x.x\bin\httpd

One thing to mention here is that each server has its own configuration. To change the configuration of Resin, you need to edit the file conf/resin.conf .If you choose another web server for your development; you need to consult the documentation of this server.

HTML and JSP files should be stored in the folder resin-x.x.x\doc . To invoke an HTML file called file.html, type the following in the browser URL: http://localhost:8080/file.html

If you want to call a JSP file called file.jsp stored in the doc folder, you have to type the following in the browser URL: http://localhost:8080/file.jsp

Where localhost is server’s hostname and 8080 is the port that this server is listening to.

To develop servlets on Resin, the .java files can be saved in the folder resin- x.x.x\doc\WEB-INF\classes. Then the action attribute of the form should be: http://localhost:8080/servlet/servletfile

Where servletfile is the java class name (no extension is required).

 Tomcat Web Server: Another Java based web server is called Tomcat. You can download it from http://www.apache.org. Chapter 9 of the textbook explains in detail how to use this server to develop servlets.

 Deploying you web application:

6 Instead of putting all you classes and files in doc folder and its subfolders, we can deploy them as separate web applications under the webapps folder. The path of this folder under Resin is resin-x.x.x\webapps. To deploy an application, a certain procedure must be followed. This procedure applies to both Resin and tomcat web servers:

 Create a folder called cpan423 under webapps folder. Any HTML or JSP file should be stored in cpan423 folder.  Under cpan423 folder create a folder called WEB-INF. WEB-INF contain the web application deployment descriptor file (web.xml). This file o Under WEB-INF create the following folders: . classes: contains the servlets classes and any other supporting classes. All the examples in this lecture will be deployed together in this folder. . lib: Contain any JAR file used in the web application. JARs can contain servlets and other supporting classes.

The resulting structure should look as follow:

webapps Cpan423 WEB-INF classes lib

The web descriptor file specifies the configuration for the web application. Following are the descriptor elements that must be included for each new servlet: Element Description Servlet Defines a servlet alias for later mapping using . This element should have servlet-name, servlet- class, init-param, load-on-startup and run-at as child elements. servlet-name The servlet's name (alias) servlet-class Specifies The class full name of the servlet init-param Initialize a parameter. load-on-startup Initialize the servlet when the server starts. run- at Times to execute the servlet automatically (Resin Extension). servlet-mapping Specify the URLs that invoke a servlet. This element should have servlet-

7 name and url-pattern as child elements. servlet-name Name of the servlet. url-pattern Matches a set of URLs for servlet mapping.

IN the following web.xml file, we will configure Hello servlet, from Ex 1:

HelloEx Hello /Hello HelloEx

You need to add servlet/ servlet-mapping entry for each servlet you add to your application.

Based on the above structure, if my servlet is called demo.java, then the action in the HTML form would be: http://localhost:8080/cpan423/demo If my HTML page is called demo.html, then I can invoke it from the browser by typing the following URL: http://localhost:8080/cpan423/demo.html

Notice that you can deploy each servlet independently by providing separate subfolder foe each under webapps folder. To do that, repeat the deployment steps mentioned above for each providing that you have to give each servlet different subfolder name.

Examples:

Ex1: servlet example In this example we will write Hello World Servlet, we will call it from the browser URL as we are using doGet method in the servlet.

8 import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class Hello extends HttpServlet { /* Handle HTTP get request */ public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { /* Identify the content type to the browser */ res.setContentType("text/html"); /* Obtain PrintWriter object to send response to the client */ PrintWriter out = res.getWriter(); out.println("Servlet Example"); out.println("Hello World"); out.println(""); } }

The servlet file (Hello.java) should be saved in the folder: resin-x.x.x\webapps\cpan423\WEB-INF\lasses

Remember that you need to configure the servlet in your web.xml by adding servlet/servlet-mapping entry as shown below:

HelloEx Hello /Hello HelloEx

9 To invoke this servlet from the deployment folder, type the following URL: http://localhost:8080/cpan423/Hello

Example 2: servlet example In this example, we will build a servlet to which we will pass username and password from an HTML form. The form that we will use is called demo.html and has the following content:

demo.html

Servlet call example

User name:

password:

Then the servlet that will respond to the form request is called demo.java: import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class demo extends HttpServlet {

10 /* This servlet will handle both HTTP requests POST and GET. The work will be done in a user defined method called doTheWork */ public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { /* Identify the content type to the browser */

res.setContentType("text/html"); /* Obtain PrintWriter object to send response to the client */

PrintWriter out = res.getWriter(); doTheWork(req,out,"Get");

}

public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { /* Identify the content type to the browser */

res.setContentType("text/html"); /* Obtain PrintWriter object to send response to the client */

PrintWriter out = res.getWriter(); doTheWork(req,out,"Post");

} public void doTheWork(HttpServletRequest req,PrintWriter out,String method) {

11 String username=req.getParameter("uname"); String password=req.getParameter("password"); out.println("Servlets "); out.println("The respond for "+method +" method was :
"); out.println("Your name was:"+username+ " and password was: "+password+""); out.println(""); out.close(); } }

In the servlet we are just prompting the user with the method used to transfer the data, the username and password. The servlet class has been developed to handle both kinds of requests (GET and POST) as both methods doPost and doGet, pass their data to a user-defined method called doTheWork. So if you change the method from post to get in demo.html, you should receive a similar result.

The servlet file (demo.java) should be saved in the folder: resin-x.x.x\webapps\cpan423\WEB-INF\lasses and the demo.html should be saved in the folder: resin-x.x.x\webapps\Cpan423. The following configuration should be added to the web.xml file: demoEx demo /demo demoEx

The demo servlet is invoked from demo.html. To open demo.html in the browser, type the following URL: http://localhost:8080/cpan423/demo.html

Ex3: Reading data in a servlet

12 import javax.servlet.*; import javax.servlet.http.*; import java.util.*; import java.io.*; public class EnumParameter extends HttpServlet { public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println(" using Enumeration in Servlets"); /* Get an enumeration of the form parameters' names */ Enumeration param=req.getParameterNames(); /* Loop thruogh the enumeration to print the parameters sent by the form */ while(param.hasMoreElements()) { String paramName=(String)param.nextElement(); String paramValue[]=req.getParameterValues(paramName); out.println(paramName); for(int i=0;i"); } out.println("");

}

}

Then we can use an HTML form called Enumparam.html that has the following content:

13 Using Enumeration to get Form data

Welcome to Java Servlets, please login to receive the Servlet response.

Name:
Password
Hobbies Sport

Music

Games

Books

 

 

The servlet file (EnumParametere.java) should be saved in the folder: resin-x.x.x\webapps\cpan423\WEB-INF\lasses and the Enumparam.html should be saved in the folder: resin-x.x.x\webapps\cpan423. The following configuration should be added to the web.xml file:

14 EnumerationEx

EnumParameter /EnumParameter EnumerationEx

The EnumParameter servlet is invoked from Enumparam.html. To open Enumparam.html in the browser, type the following URL: http://localhost:8080/cpan423/Enumparam.html

Ex4: Reading header information import javax.servlet.*; import javax.servlet.http.*; import java.util.*; import java.io.*; public class readingHeaders extends HttpServlet {

public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println(" using Enumeration in Servlets"); /* Get all the headers sent by the client */ Enumeration headers=req.getHeaderNames(); out.println("

"); /* Loop through the headers ahd print them */

15 while(headers.hasMoreElements()) { String headerName=(String) headers.nextElement(); out.println("

");

} out.println("");

}

}

The servlet file (readingHeaders.java) should be saved in the folder: resin-x.x.x\webapps\cpan423\WEB-INF\lasses. The following configuration should be added to the web.xml file: readingHeadersEx readingHeaders /readingHeaders readingHeadersEx

To invoke this servlet from the deployment folder, type the following URL: http://localhost:8080/cpan423/readingHeaders

Ex5: Redirecting a Servlet to another page import javax.servlet.*; import javax.servlet.http.*; import java.util.*; import java.io.*; public class redirectServlet extends HttpServlet {

16 public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); // specify that the document was remove permanently res.setStatus(res.SC_MOVED_PERMANENTLY); // redirect the server to anothe page res.setHeader("Location","http://localhost:8080/cpan423/demo.html"); }

}

The servlet file (redirectServlet.java) should be saved in the folder: resin-x.x.x\webapps\Cpan423\WEB-INF\lasses. The following configuration should be added to the web.xml file: redirectEx

redirectServlet /redirectServlet redirectEx

To invoke this servlet from the deployment folder, type the following URL: http://localhost:8080/cpan423/redirectServlet

Ex6: connecting to database using Servlet

This example uses a form named db.html to query Customer table. The user must fill in Customer ID field .The operator must be included , for example “> 1” or “=1”. dbForm.html:

17 DB Servlet

DB Servlet


Enter the Customer Id:

The form will be submitted to dbServlet on the server: import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.io.*; import java.sql.*; public class dbServlet extends HttpServlet { Connection con; public void init() throws ServletException {

String driver="oracle.jdbc.OracleDriver"; try { // load Oracle thin JDBC driver Class.forName(driver);

//create connection String url="jdbc:oracle:thin:@munro.humber.ca:1521:msit"; con = DriverManager.getConnection(url,"user","password"); } catch (Exception e) { } }

public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html");

18 PrintWriter out = res.getWriter(); int cnt = 0;

try { Statement stmt = con.createStatement();

String sql = "";

out.println(""); out.println("DB Record Retrieval"); out.println(""); out.println("

"); out.println("
Header NameHeader Value
"+headerName+""+req.getHeader(header Name)+"
");

String CustId = req.getParameter("CustID"); if (!CustId.equals(""))

{ sql ="select id, firstName, lastName from emp where id "+ CustId;

ResultSet rs = stmt.executeQuery(sql); ResultSetMetaData rsmd=rs.getMetaData(); int col=rsmd.getColumnCount();

while (rs.next()) { out.println("

"); if (cnt == 0) { for(int j=1;j<=col;j++) out.println(""); out.println(""); }

for(int j=1;j<=col;j++) out.println("

");

out.println("

"); cnt++;

19 } if (cnt == 0) out.println("

"); out.println("
" +rsmd.getColumnName(j)+"
" +rs.getString(j) +"
No Matching Record Found
"); } else out.println("

you have not entered anything

"); out.println("

Go back to table selector form

"); } catch (Exception e) { out.println("Exception" + e ); }

} public void destroy() { try { con.close(); } catch(SQLException sle) {} }

}

Notice that you need to use your oracle ID and password in the statement: con = DriverManager.getConnection(url,"user","password");

To configure the oracle driver under resin, you can place the oracle driver ( classes12.zip file) in the folder: resin-x.x.x\lib. This will enable all of your application to use this driver. If you want to enable certain application to use this driver only, then you need to place this driver under WEB-INF\lib folder of the specified application. You need also to restart Resin for the changes to take effect.

The servlet file (dbServlet.java) should be saved in the folder: resin-x.x.x\webapps\cpan423\WEB-INF\lasses and the dbForm.html should be saved in the folder: resin-x.x.x\webapps\cpan423. The following configuration should be added to the web.xml file:

20 dbServlet

dbServlet /dbServlet dbServlet

The dbServlet servlet is invoked from dbForm.html. To open dbForm.html in the browser, type the following URL: http://localhost:8080/cpan423/dbForm.html

Ex7: using JNDI configuration to connect to Database from a Servlet

Instead of using the traditional way of connected to a database as shown in Ex6, we can use JNDI to do that. JNDI provides an application with a global naming tree designed for storing factory objects and configuration variables.

First we need to add the following configuration section to web.xml (Just before ):

dbServletJNDI

dbServletJNDI /dbServletJNDI dbServletJNDI

jdbc:oracle:thin:@munro.humber.ca:1521:msit user

21 password

Remember to use your user ID/password under oracle.

Following is the source code for dbServletJNDI.java: import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.sql.*; import javax.naming.*; import javax.sql.*; public class dbServletJNDI extends HttpServlet { DataSource ds; Connection con; public void init() throws ServletException { try { Context ic = (Context) new InitialContext(); ds = (DataSource) ic.lookup("java:comp/env/jdbc/test"); } catch (Exception e) { } }

public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

PrintWriter out = res.getWriter(); int cnt = 0;

try { con = ds.getConnection();

Statement stmt = con.createStatement();

22 String sql = "";

out.println(""); out.println("DB Record Retrieval"); out.println(""); out.println("

"); out.println("");

String CustId = req.getParameter("CustID"); if (!CustId.equals(""))

{ sql ="select id, firstName, lastName from emp where id "+ CustId;

ResultSet rs = stmt.executeQuery(sql); ResultSetMetaData rsmd=rs.getMetaData(); int col=rsmd.getColumnCount();

while (rs.next()) { out.println("

"); if (cnt == 0) { for(int j=1;j<=col;j++) out.println(""); out.println(""); }

for(int j=1;j<=col;j++) out.println("

");

out.println("

"); cnt++; } if (cnt == 0) out.println(""); out.println("
" +rsmd.getColumnName(j)+"
" +rs.getString(j) +"
No Matching Record Found
"); }

23 else out.println("

you have not entered anything

"); out.println("

Go back to table selector form

"); } catch (Exception e) { out.println("Exception" + e ); }

} public void destroy() { try { con.close(); } catch(SQLException sle) {} } }

And here is an HTML file called dbJNDI.html to invoke this servlet:

DB Servlet

DB Servlet


Enter the Customer Id:

Ex8: Invoking other Servlet

In this example we will see how we can include the content of another servlet while our servlet execute. Our servlet is called demoWithInclude.java

24 import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class demoWithInclude extends HttpServlet { public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { /* Identify the content type to the browser */ res.setContentType("text/html"); /* Obtain PrintWriter object to send response to the client */ PrintWriter out = res.getWriter(); String username=req.getParameter("uname"); String password=req.getParameter("password"); out.println("Servlets "); out.println("The respond for Post method was :
"); out.println("Your name was:"+username+ " and password was: "+password+""); /* Obtain a RequestDispatcher by calling getRequestDispatcher method of ServletContext, supplying a URL relative to the servlet root. */ String adr="/Footer"; RequestDispatcher dispatcher=getServletContext().getRequestDispatcher(adr); // we use include method to include the content of another servlet dispatcher.include(req,res); out.println(""); }

}

Footer Servlet has the following content: import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class Footer extends HttpServlet {

25 /* Since demoWithInclude Handles HTTP post request, Footer has to handle the same request method */ public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { /* Identify the content type to the browser */ res.setContentType("text/html"); /* Obtain PrintWriter object to send response to the client */ PrintWriter out = res.getWriter(); out.println("

Humber College
"); out.println("
School of Information Technology
"); out.println("
Computer Programming Department
");

} }

And following is an HTML file called demowithInclude.html used to invoke demoWithInclude Servlet

Test Servlet

Test Servlet

Enter your name:
Enter your password:

The servlet files should be saved in the folder resin- x.x.x\webapps\cpan423\WEB-INF\lasses and the HTML file should be saved in the folder: resin-x.x.x\webapps\cpan423. The following configuration should be added to the web.xml file:

26 footer Footer /footer footer

demoWithInclude

demoWithInclude /demoWithInclude demoWithInclude

Note:

 After you configure all the examples in this lecture, your web.xml should look as follows:

demoEx demo /demo demoEx

HelloEx Hello

27 /Hello HelloEx

EnumerationEx

EnumParameter /EnumParameter EnumerationEx

readingHeadersEx readingHeaders /readingHeaders readingHeadersEx

redirectEx

redirectServlet /redirectServlet redirectEx

dbServlet

dbServlet /dbServlet

28 dbServlet

dbServletJNDI

dbServletJNDI /dbServletJNDI dbServletJNDI

jdbc:oracle:thin:@sunserv1.humberc.on.ca:1521:orcl user password

 If you want to distribute a web application, you can package it into a Web Application Archive (WAR). Following is a batch file called createWAR.bat that can be used to create WAR file for our examples in this lecture. This file must be stored under cpan423 folder:

set path=%path%;C:\j2sdk_nb\j2sdk1.4.2\bin jar cvf cpan423.war .

Following is a description of each option: c : create a new archive file (war file). v: generate verbose output on the standard output f: specifiy the archive file name. In this case it is cpan423.war The dot (.) at the end of the command instructs the jar command to package all the files in the current directory. Once you have the war file, you can copy it to the webapps folder of your server. Resin will unpack it for you the next time it runs.

29

Recommended publications