Servlet What is a Servlet? Servlets, similar to Applets, are applications running at server side to replace the old CGI programs. Most functions of Servlets can be realized by another Java technology - JSP. Servlet Lifecycle It seems that (actually not) Servlet begins from calling init method in its lifecycle. It is not thread-safe because the service method will not be called until the call to init returns. After the Servlet is initialized, the key method service (ServletRequest req, ServletResponse res) is called by every request, even concurrently. The method should be implemented in a thread-safe manner. If the Servlet needs to be unloaded unconditionally, the thread-safe destroy() method will be called. Servlet Functions HTTP GET - getQueryString A Template of A Servlet //import classes; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ATemplateServlet extends HttpServlet { private String filename; //initial some data coz this method is called only once public void init(ServletConfig config) throws ServletException { super.init(config);//may do it filename = config.getInitParameter("addressfile"); if(filename == null) throw new UnavailableException(this); } //to display the form page protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); //must do first PrintWriter out = res.getWriter(); //get a object of writer out.print("<head></head>"); out.print("...<form method=post action="myservlet">..."); out.close(); } //deal with the user data protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String email = req.getParameter("mydata"); //get the data String msg; dealWith(email); //write the result res.setContentType("text/html"); res.setHeader("pragma", "no-cache"); PrintWriter out = res.getWriter(); out.print("<head></head>"); out.print("blar,blar,..."); out.close(); } //since each request can call this method //be careful the share data - synchronized private synchronized boolean dealWith(String email) throws IOException { if(xxx)) return false; } } Web Sites
Servlet Tutorial Track session: Call another Servlet: getServletContext() .getRequestDispatcher("/servlet/AServlet?param="+data) .include(req, res); //or forward() for header Include an HTML file: getServletContext() .getResource("/html/mydoc.htm"); Set Cookie: Cookie aCookie = new Cookie("xxx", credentials); aCookie.setVersion(1); //not version 0 aCookie.setDomain(".mydomain.com");//indicate the server res.addCookie(authCookie); //ask client write the cookie Read Cookie: Cookie[] cookies = req.getCookies(); for(int i=0; i < cookies.length; i++) { String n = cookies[i].getName(); String d = cookies[i].getDomain(); if(n != null && n.equals("xxx") && d != null && d.equals(".mydomain.com")) { String credentials = cookies[i].getValue(); doSomething(credentials); break; } } Access a Database public class Demo extends HttpServlet { Connection con; public void init(ServletConfig config) throws ServletException { super.init(config); try { // jdbc-odbc Class.forName(sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection (jdbc:odbc:DemoTable", ", "); }catch (ClassNotFoundException e){ throw new UnavailableException(this, Couldnt load JdbcOdbcDriver"); }catch (SQLException e) { throw new UnavailableException(this, Couldnt get db connection"); } } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ String sql = SELECT * from DemoTable ORDER BY test_id"; try { res.setContentType(text/plain"); ServletOutputStream out = res.getOutputStream(); try { Statement stmt = con.createStatement(); if (stmt.execute(sql)) { ResultSet rs = stmt.getResultSet(); out.println(<TABLE>\n"); ResultSetMetaData rsmd = rs.getMetaData(); int numcols = rsmd.getColumnCount(); out.println(< TR >"); for (int i = 1; i < = numcols; i++) out.println(< TH >" + rsmd.getColumnLabel(i)); out.println(< /TR >\n"); while(rs.next()){ out.println(< TR >"); |