Jsp学习——servlet详解

一、servlet的生命周期

在《JSP学习 —— 开篇:JSP,servlet容器,Tomcat,servlet容器之间的关系》一文中,我已经对servlet的生命周期进行了简单阐述,现在,就来进行详细阐述:servlet其实就是一个Java类,它负责响应和处理页面消息。它的实例化方式有两种:一种是当web应用启动一开始,tomcat就对servlet进行初始化;另一种是当客户端请求一个servlet时,对应的servlet进行创建;创建时调用HttpServlet的Init(或用户自己重写的Init)函数进行初始化,之后调用service函数进行消息响应,最后调用destory方法进行收尾处理。对于其何时创建,如何创建,都不是由我们来控制的,而是由容器根据配置文件自己进行创建。

事实上,在标准MVC结构中,servlet只充当Control部分,它从来不对页面进行输出处理,也不进行业务逻辑处理,只是将页面消息进行对应的后台处理后(期间会和Model打交道),进行简单的页面跳转。

对于servlet类的配置,其实只要注意两点就足够了:一是指定servlet类名,二是指定该类要处理的动作。

  1. <pre class="html" name="code">  <servlet> 
  2.         <servlet-name>myServlet</servlet-name> 
  3.         <servlet-class>com.cancique.dao.LoginServlet</servlet-class> 
  4.   </servlet> 
  5. <servlet-mapping> 
  6.         <servlet-name>myServlet</servlet-name> 
  7.         <url-pattern>/login</url-pattern> 
  8.   </servlet-mapping></pre> 
  9. <pre></pre> 
  10. 对于sevlet的名字,暂时我们可以随意指定,对于只有一个servlet类的Web应用而言,是没必要注意的。 
  11. <p></p> 
  12. <p>要注意而且需要特别注意的时servlet-class和url-pattern,servlet-class指定servlet的类名,类名必须包含完整的包前缀,而url指定要处理的动作名,如:我在这里打算处理一个表单请求的action,</p> 
  13. <p></p> 
  14. <pre class="html" name="code"><form action = "login" id = "login" method = "post"></pre>要处理的action必须和url-pattern相同,否则servlet不能处理我们提交的请求,运行时会出错。<br> 
  15. <p></p> 
  16. <p>二、load-on-startup Servlet</p> 
  17. <p>一般来说,容器会将绝大多数servlet类的初始化都将在页面进行请求之后,然后根据请求找到对应的servlet再初始化,那么如果我们想将一个servlet类在WEB应用启动后尽早的执行初始化,那么只有靠load-on-startup配置参数了。这个配置参数同servlet的配置参数一起配置,它的参数值是个整型值,赋给它的值越小,它就越先初始化。</p> 
  18. <p></p> 
  19. <pre class="html" name="code"><servlet> 
  20.         <servlet-name>myServlet</servlet-name> 
  21.         <servlet-class>com.cancique.dao.LoginServlet</servlet-class> 
  22.                 <load-on-startup>1</load-on-startup> 
  23. </servlet> 
  24. <servlet-mapping> 
  25.         <servlet-name>myServlet</servlet-name> 
  26.         <url-pattern>/login</url-pattern> 
  27.   </servlet-mapping></pre> 
  28. <p></p> 
  29. <p>三、访问servlet的配置参数</p> 
  30. <p>我们在配置servlet时,还可以配置一些运行时用到的参数,这种参数可以通过ServletConfig类来解析,看起来和我前面讲到的《<span class="link_title"><a title="JSP学习——JSP基础知识(二)" href="http://blog.csdn.net/yangywyangyw/article/details/6672119">JSP学习——JSP基础知识(二)</a></span></p> 
  31. <h3></h3> 
  32. 》里面提到的application对象解析配置文件中数据库连接信息的参数很类似,不同的是application可以在任何地方进行解析,而ServletConfig对象只能在servlet中进行解析。比如:如果我们在servlet中需要得到数据库的连接信息以初始化DAO对象,那么可以在web.xml的servlet配置信息中增加一些配置参数: 
  33. <p></p> 
  34. <p></p> 
  35. <pre class="html" name="code">  <servlet> 
  36.         <servlet-name>myServlet</servlet-name> 
  37.         <servlet-class>com.cancique.dao.LoginServlet</servlet-class> 
  38.         <init-param> 
  39.             <param-name>driver</param-name> 
  40.             <param-value>com.mysql.jdbc.Driver</param-value> 
  41.         </init-param> 
  42.         <init-param> 
  43.             <param-name>url</param-name> 
  44.             <param-value>jdbc:mysql://localhost:3306/test_db</param-value> 
  45.         </init-param> 
  46.         <init-param> 
  47.             <param-name>user</param-name> 
  48.             <param-value>root</param-value> 
  49.         </init-param> 
  50.         <init-param> 
  51.             <param-name>pass</param-name> 
  52.             <param-value>900622</param-value> 
  53.         </init-param> 
  54.   </servlet> 
  55.    
  56.   <servlet-mapping> 
  57.         <servlet-name>myServlet</servlet-name> 
  58.         <url-pattern>/login</url-pattern> 
  59.   </servlet-mapping></pre> 
  60. <p>在需要用到这些参数的servlet类中,我们可以通过ServletConfig对象来解析:</p> 
  61. <p><pre class="html" name="code">           ServletConfig config = getServletConfig(); 
  62.             String driver = config.getInitParameter("driver"); 
  63.             String url = config.getInitParameter("url"); 
  64.             String user = config.getInitParameter("user"); 
  65.             String pass = config.getInitParameter("pass"); 
  66.             DbDao dao = DbDao.instance(driver,url,user,pass);</pre><p></p> 
  67. <p>四、综合应用:servlet作为MVC架构中Control层的实例——一个简单的登录验证</p> 
  68. <p>index.jsp页面代码如下:</p> 
  69. <p><pre class="html" name="code"><%@ page language="java" import="java.util.*" errorPage="error.jsp"%> 
  70. <%@ page pageEncoding="gb2312"%> 
  71. <%@page import="java.sql.SQLException"%> 
  72. <%@page import="java.net.ConnectException"%> 
  73. <%@page import="java.sql.DriverManager"%> 
  74. <%@page import="java.sql.*" %> 
  75. <html> 
  76.   <body> 
  77.         <form action = "login" id = "login" method = "post"> 
  78.             user name:<input type = "text" name = "username"><hr> 
  79.             user password:<input type = "text" name = "userpassword"><hr> 
  80.             <input type = "submit" value = "submit"><br> 
  81.         </form> 
  82.    </body> 
  83. </html> 
  84. </pre><br> 
  85. error.jsp页面代码如下:<p></p> 
  86. <p><pre class="html" name="code">login failed!</pre>success.jsp页面代码如下:<p></p> 
  87. <p><pre class="html" name="code">login successful!</pre>LoginServlet类代码如下:<p></p> 
  88. <p><pre class="java" name="code">package com.cancique.dao; 
  89.  
  90. import java.io.IOException; 
  91. import java.sql.*; 
  92.  
  93. import javax.servlet.RequestDispatcher; 
  94. import javax.servlet.ServletConfig; 
  95. import javax.servlet.ServletException; 
  96. import javax.servlet.http.HttpServlet; 
  97. import javax.servlet.http.HttpServletRequest; 
  98. import javax.servlet.http.HttpServletResponse; 
  99. import javax.servlet.http.HttpSession; 
  100.  
  101. public class LoginServlet extends HttpServlet{ 
  102.     public void service(HttpServletRequest request, 
  103.             HttpServletResponse response) 
  104.     { 
  105.         RequestDispatcher rd; //请求转发 
  106.         String username = request.getParameter("username"); 
  107.         String userpassword = request.getParameter("userpassword"); 
  108.         String errMsg = null
  109.         try 
  110.         { 
  111.             ServletConfig config = getServletConfig(); 
  112.             String driver = config.getInitParameter("driver"); 
  113.             String url = config.getInitParameter("url"); 
  114.             String user = config.getInitParameter("user"); 
  115.             String pass = config.getInitParameter("pass"); 
  116.             DbDao dao = DbDao.instance(driver,url,user,pass); 
  117.             String sql = "select userpassword from user_information where username = '" + username + "'"; 
  118.             ResultSet resultSet = dao.query(sql); 
  119.              
  120.             if(resultSet.next()) 
  121.             { 
  122.                 if(resultSet.getString("userpassword").equals(userpassword)) 
  123.                 { 
  124.                     HttpSession session = request.getSession(true); 
  125.                     session.setAttribute("username", username); 
  126.                     rd = request.getRequestDispatcher("/success.jsp"); 
  127.                     rd.forward(request, response); 
  128.                 } 
  129.                 else 
  130.                 { 
  131.                     errMsg +="密码错误!"; 
  132.                 } 
  133.             } 
  134.             else 
  135.             { 
  136.                 errMsg += "用户名错误!"; 
  137.             } 
  138.         }catch(Exception e) 
  139.         { 
  140.             rd = request.getRequestDispatcher("/error.jsp"); 
  141.             request.setAttribute("exception", "业务异常"); 
  142.             try { 
  143.                 rd.forward(request, response); 
  144.             } catch (ServletException e1) { 
  145.                 e1.printStackTrace(); 
  146.             } catch (IOException e1) { 
  147.                 e1.printStackTrace(); 
  148.             } 
  149.         } 
  150.     } 
  151. </pre>DbDao类代码如下(使用Singleton设计模式):<p></p> 
  152. <p><pre class="java" name="code">package com.cancique.dao; 
  153.  
  154. import java.sql.*; 
  155.  
  156.  
  157. public class DbDao { 
  158.     private static DbDao dao; 
  159.     private Connection conn; 
  160.     private String driver; 
  161.     private String url; 
  162.     private String username; 
  163.     private String pass; 
  164.      
  165.     private DbDao() 
  166.     {} 
  167.      
  168.     private DbDao(String driver,String url, 
  169.             String username,String pass) 
  170.     { 
  171.         this.driver = driver
  172.         this.url = url
  173.         this.username = username
  174.         this.pass = pass
  175.     } 
  176.  
  177.     public static DbDao getDao() { 
  178.         return dao; 
  179.     } 
  180.  
  181.     public static void setDao(DbDao dao) { 
  182.         DbDao.dao = dao
  183.     } 
  184.  
  185.     public String getDriver() { 
  186.         return driver; 
  187.     } 
  188.  
  189.     public void setDriver(String driver) { 
  190.         this.driver = driver
  191.     } 
  192.  
  193.     public String getUrl() { 
  194.         return url; 
  195.     } 
  196.  
  197.     public void setUrl(String url) { 
  198.         this.url = url
  199.     } 
  200.  
  201.     public String getUsername() { 
  202.         return username; 
  203.     } 
  204.  
  205.     public void setUsername(String username) { 
  206.         this.username = username
  207.     } 
  208.  
  209.     public String getPass() { 
  210.         return pass; 
  211.     } 
  212.  
  213.     public void setPass(String pass) { 
  214.         this.pass = pass
  215.     } 
  216.      
  217.     public void getConnection() throws ClassNotFoundException, SQLException 
  218.     { 
  219.         if(conn == null) 
  220.         { 
  221.             Class.forName(this.driver); 
  222.             conn = DriverManager.getConnection(url, username, pass); 
  223.         } 
  224.     } 
  225.      
  226.     public static DbDao instance(String driver,String url, 
  227.             String username,String pass) 
  228.     { 
  229.         if(dao == null) 
  230.         { 
  231.             dao = new DbDao(driver,url,username,pass); 
  232.         } 
  233.         return dao; 
  234.     } 
  235.      
  236.     public boolean insert(String sql) throws ClassNotFoundException, SQLException 
  237.     { 
  238.         getConnection(); 
  239.         Statement statement = conn.createStatement(); 
  240.         if(statement.executeUpdate(sql) != -1) 
  241.         { 
  242.             return false; 
  243.         } 
  244.         return true; 
  245.     } 
  246.      
  247.     public ResultSet query(String sql) throws ClassNotFoundException, SQLException 
  248.     { 
  249.         getConnection(); 
  250.         Statement statement = conn.createStatement(); 
  251.         return statement.executeQuery(sql); 
  252.     } 
  253.      
  254.     public void delete(String sql) throws ClassNotFoundException, SQLException 
  255.     { 
  256.         getConnection(); 
  257.         Statement statement = conn.createStatement(); 
  258.         statement.executeUpdate(sql); 
  259.     } 
  260.      
  261.     public void update(String sql) throws ClassNotFoundException, SQLException 
  262.     { 
  263.         getConnection(); 
  264.         Statement statement = conn.createStatement(); 
  265.         statement.executeUpdate(sql); 
  266.     } 
  267. }</pre>web.xml配置文件信息如下:<p></p> 
  268. <p><pre class="html" name="code"><?xml version="1.0" encoding="UTF-8"?> 
  269. <web-app version="2.5"  
  270.     xmlns="http://java.sun.com/xml/ns/javaee"  
  271.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  272.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  
  273.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 
  274.   <welcome-file-list> 
  275.     <welcome-file>index.jsp</welcome-file> 
  276.   </welcome-file-list> 
  277.   <servlet> 
  278.         <servlet-name>myServlet</servlet-name> 
  279.         <servlet-class>com.cancique.dao.LoginServlet</servlet-class> 
  280.         <init-param> 
  281.             <param-name>driver</param-name> 
  282.             <param-value>com.mysql.jdbc.Driver</param-value> 
  283.         </init-param> 
  284.         <init-param> 
  285.             <param-name>url</param-name> 
  286.             <param-value>jdbc:mysql://localhost:3306/test_db</param-value> 
  287.         </init-param> 
  288.         <init-param> 
  289.             <param-name>user</param-name> 
  290.             <param-value>root</param-value> 
  291.         </init-param> 
  292.         <init-param> 
  293.             <param-name>pass</param-name> 
  294.             <param-value>900622</param-value> 
  295.         </init-param> 
  296.         <load-on-startup>1</load-on-startup> 
  297.   </servlet> 
  298.    
  299.   <servlet-mapping> 
  300.         <servlet-name>myServlet</servlet-name> 
  301.         <url-pattern>/login</url-pattern> 
  302.   </servlet-mapping> 
  303. </web-app> 
  304. </pre><br> 
  305. <br> 
  306. <p></p> 
  307. <p><br> 
  308. </p> 
  309. <br> 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值