How to implement Java servlets? |
Implement the interface javax.servlet.Servlet
by extending either the class GenericServlet (javax.servlet.GenericServlet) or
HttpServlet (javax.servlet.http.HttpServlet) .
Servlet methods
init() -- called when servlet starts to initialize services
service() -- called to process requests
- The entry point for the servlet (after init() is called)
- Called from the servlet container
- Decide what type of request is coming in and
then call the appropriate mehod
- HTTP GET requests --
doGet()
- HTTP POST requests --
doPost()
destroy() -- called by container before servlet process ends
- To clean up the state of the servlet
- Informing another application the servlet is stopping
getServletConfig() -- servlet can access information about servlet container
- Return a
ServletConfig object
(which stores information about the servlet's configuration)
getServletInfo() -- servlet container can access information about servlet
- Author
- Creation date
- Description
- Usage
- ...
Simple servlet example
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Hello extends HttpServlet
{
public void doGet (HttpServletRequest req,
HttpServletResponse res)
throws servletException, IOException
{
res.setContentType (“text/html; charset=‘UTF-8’”);
PrintWriter out = res.getWriter ();
out.println (“<html>”);
out.println(" <head>");
out.println(" <title>Servlet example</title>");
out.println(" </head>");
out.println(" <body>");
out.rintln(" <p>My first servlet<g;/p>");
out.println(" </body>");
out.println("</html>");
out.close();
}
}
http://apps-swe432.vse.gmu.edu:8080/swe432/servlet/offutt.Hello
HttpServletRequest
- Represent the HTTP request a browser sends to
a web application.
Thus, anything the browser may send is accessible
via the HttpServletRequest
- The request parameters are parameters
that are sent from the browser along with the request,
typically as part of the URL
or as part of the body of an HTTP request.
method call:
System.out.println (“aString”);
servlet parameters transmission:
http://www example com/servlet/PrintThis?arg=aString
multiple parameters are separated by '&'
http://www.example.com/servlet/PrintThis?color=red&arg=Mike&age=39
order of parameters does not matter
http://www.example.com/servlet/PrintThis?arg=Hello&color=red&age=39
empty string
http://www.example.com/servlet/PrintThis?arg=&color=red&age=39
-
To access the parameters from the HttpServletRequest object
http://www.example.com/servlet/PrintThis?arg=Hello&color=red&age=39
protected void doGet( HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String param1 = request.getParameter("arg");
String param2 = request.getParameter("color");
String param3 = request.getParameter("age");
}
- Most browsers give a warning before submitting POST data
for the second time -- to avoid duplicate submissions and updates
The page you are trying to view contains POSTDATA. If you resend the data,
any action the form carried out (such as a saerch or online purchase)
will be repeated. To resend the data, click OK. Otherwise, click Cancel.
(how many users understand this message?)
HttpServletResponse
- Standard output is sent directly back to the client browser
- Represent the HTTP response a web application sends back
to the browser, in response to the HTTP request
the browser sends to the web application.
- To send response back to the browser
- The Content-Type header (i.e., a response header)
that tells the browser the type of the content
to be sending back must be specified.
- text/html -- send html back to the browser
- text/plain -- send plain text back to the browser
- A
PrintWriter
from the HttpServletResponse object must be obtained
and use print() and println()
to write HTML to browser
Example html from
name.html
<html>
<head>
<title>Name</title>
</head>
<body>
<form method="post" action="http://cs.gmu.edu:8080/offutt/servlet/name">
Please enter your name:
<input type="text" name="yourname" value="your name">
<br />
<input type="submit" value="Submit" name="submit">
<input type="reset" value="Reset" name="reset">
</form>
</body>
</html>
Example servlet from
name.java
//Import Servlet Libraries
import javax.servlet.*;
import javax.servlet.http.*;
//Import Java Libraries
import java.io.*;
import java.util.*;
import java.lang.*;
public class name extends HttpServlet
{
public void doPost (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType ("text/html");
PrintWriter out = res.getWriter ();
out.print ("<html>\n");
out.print (" <head>\n");
out.print (" <title>SWE 432: Name reading and printing</title>\n");
out.print (" </head>\n");
out.print (" <body>\n");
out.print (" <center><h2>Name reading and printing</h2></center>\n");
out.print (" <hr />\n");
String Nm = req.getParameter("yourname");
out.print (" Your name is: <font color=green>");
out.print (Nm);
out.print (" </font>\n");
out.print (" </body>\n");
out.print ("</html>\n");
out.close ();
}
}
Redirecting to another URL from servlets
Servlets usually generate an HTML ile as a response,
but sometimes you might want to send the client to
a different servlet.
res.sendRedirect (“http://apps-swe432.vse.gmu.edu:8080/ ...”);
- The client will be sent to the specified URL
- Server tells the client
to generate another request to the new URL
- Browser then repeats the request to the new URL
- Control is transfered to a new URL and does not come back
Writing to file from servlets
- File must be in a publicly writeable directory
/data/apps-swe43/swe432/WEB-INF/data/
- Open a file
FileWriter outfile = new FileWriter("/data/apps-swe432/swe432/WEB-INF/data/info-file.txt");
Open a file in append mode
FileWriter outfile = new FileWriter("/data/apps-swe432/swe432/WEB-INF/data/info-file.txt", true);
- Write to a file
outfile.write( .... data to save .... );
- Close a file
outfile.close();
- Remember that we all share the
same directory ... include your
user name as part of the file name
|