CPAN423 Enterprise Java Programming
Total Page:16
File Type:pdf, Size:1020Kb
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
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
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:
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("
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:
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
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("
"); 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:
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("
}
}
Then we can use an HTML form called Enumparam.html that has the following content:
13
Welcome to Java Servlets, please login to receive the Servlet response.