一、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类名,二是指定该类要处理的动作。
- <pre class="html" name="code"> <servlet>
- <servlet-name>myServlet</servlet-name>
- <servlet-class>com.cancique.dao.LoginServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>myServlet</servlet-name>
- <url-pattern>/login</url-pattern>
- </servlet-mapping></pre>
- <pre></pre>
- 对于sevlet的名字,暂时我们可以随意指定,对于只有一个servlet类的Web应用而言,是没必要注意的。
- <p></p>
- <p>要注意而且需要特别注意的时servlet-class和url-pattern,servlet-class指定servlet的类名,类名必须包含完整的包前缀,而url指定要处理的动作名,如:我在这里打算处理一个表单请求的action,</p>
- <p></p>
- <pre class="html" name="code"><form action = "login" id = "login" method = "post"></pre>要处理的action必须和url-pattern相同,否则servlet不能处理我们提交的请求,运行时会出错。<br>
- <p></p>
- <p>二、load-on-startup Servlet</p>
- <p>一般来说,容器会将绝大多数servlet类的初始化都将在页面进行请求之后,然后根据请求找到对应的servlet再初始化,那么如果我们想将一个servlet类在WEB应用启动后尽早的执行初始化,那么只有靠load-on-startup配置参数了。这个配置参数同servlet的配置参数一起配置,它的参数值是个整型值,赋给它的值越小,它就越先初始化。</p>
- <p></p>
- <pre class="html" name="code"><servlet>
- <servlet-name>myServlet</servlet-name>
- <servlet-class>com.cancique.dao.LoginServlet</servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>myServlet</servlet-name>
- <url-pattern>/login</url-pattern>
- </servlet-mapping></pre>
- <p></p>
- <p>三、访问servlet的配置参数</p>
- <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>
- <h3></h3>
- 》里面提到的application对象解析配置文件中数据库连接信息的参数很类似,不同的是application可以在任何地方进行解析,而ServletConfig对象只能在servlet中进行解析。比如:如果我们在servlet中需要得到数据库的连接信息以初始化DAO对象,那么可以在web.xml的servlet配置信息中增加一些配置参数:
- <p></p>
- <p></p>
- <pre class="html" name="code"> <servlet>
- <servlet-name>myServlet</servlet-name>
- <servlet-class>com.cancique.dao.LoginServlet</servlet-class>
- <init-param>
- <param-name>driver</param-name>
- <param-value>com.mysql.jdbc.Driver</param-value>
- </init-param>
- <init-param>
- <param-name>url</param-name>
- <param-value>jdbc:mysql://localhost:3306/test_db</param-value>
- </init-param>
- <init-param>
- <param-name>user</param-name>
- <param-value>root</param-value>
- </init-param>
- <init-param>
- <param-name>pass</param-name>
- <param-value>900622</param-value>
- </init-param>
- </servlet>
- <servlet-mapping>
- <servlet-name>myServlet</servlet-name>
- <url-pattern>/login</url-pattern>
- </servlet-mapping></pre>
- <p>在需要用到这些参数的servlet类中,我们可以通过ServletConfig对象来解析:</p>
- <p><pre class="html" name="code"> ServletConfig config = getServletConfig();
- String driver = config.getInitParameter("driver");
- String url = config.getInitParameter("url");
- String user = config.getInitParameter("user");
- String pass = config.getInitParameter("pass");
- DbDao dao = DbDao.instance(driver,url,user,pass);</pre><p></p>
- <p>四、综合应用:servlet作为MVC架构中Control层的实例——一个简单的登录验证</p>
- <p>index.jsp页面代码如下:</p>
- <p><pre class="html" name="code"><%@ page language="java" import="java.util.*" errorPage="error.jsp"%>
- <%@ page pageEncoding="gb2312"%>
- <%@page import="java.sql.SQLException"%>
- <%@page import="java.net.ConnectException"%>
- <%@page import="java.sql.DriverManager"%>
- <%@page import="java.sql.*" %>
- <html>
- <body>
- <form action = "login" id = "login" method = "post">
- user name:<input type = "text" name = "username"><hr>
- user password:<input type = "text" name = "userpassword"><hr>
- <input type = "submit" value = "submit"><br>
- </form>
- </body>
- </html>
- </pre><br>
- error.jsp页面代码如下:<p></p>
- <p><pre class="html" name="code">login failed!</pre>success.jsp页面代码如下:<p></p>
- <p><pre class="html" name="code">login successful!</pre>LoginServlet类代码如下:<p></p>
- <p><pre class="java" name="code">package com.cancique.dao;
- import java.io.IOException;
- import java.sql.*;
- import javax.servlet.RequestDispatcher;
- import javax.servlet.ServletConfig;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
- public class LoginServlet extends HttpServlet{
- public void service(HttpServletRequest request,
- HttpServletResponse response)
- {
- RequestDispatcher rd; //请求转发
- String username = request.getParameter("username");
- String userpassword = request.getParameter("userpassword");
- String errMsg = null;
- try
- {
- ServletConfig config = getServletConfig();
- String driver = config.getInitParameter("driver");
- String url = config.getInitParameter("url");
- String user = config.getInitParameter("user");
- String pass = config.getInitParameter("pass");
- DbDao dao = DbDao.instance(driver,url,user,pass);
- String sql = "select userpassword from user_information where username = '" + username + "'";
- ResultSet resultSet = dao.query(sql);
- if(resultSet.next())
- {
- if(resultSet.getString("userpassword").equals(userpassword))
- {
- HttpSession session = request.getSession(true);
- session.setAttribute("username", username);
- rd = request.getRequestDispatcher("/success.jsp");
- rd.forward(request, response);
- }
- else
- {
- errMsg +="密码错误!";
- }
- }
- else
- {
- errMsg += "用户名错误!";
- }
- }catch(Exception e)
- {
- rd = request.getRequestDispatcher("/error.jsp");
- request.setAttribute("exception", "业务异常");
- try {
- rd.forward(request, response);
- } catch (ServletException e1) {
- e1.printStackTrace();
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- }
- }
- }
- </pre>DbDao类代码如下(使用Singleton设计模式):<p></p>
- <p><pre class="java" name="code">package com.cancique.dao;
- import java.sql.*;
- public class DbDao {
- private static DbDao dao;
- private Connection conn;
- private String driver;
- private String url;
- private String username;
- private String pass;
- private DbDao()
- {}
- private DbDao(String driver,String url,
- String username,String pass)
- {
- this.driver = driver;
- this.url = url;
- this.username = username;
- this.pass = pass;
- }
- public static DbDao getDao() {
- return dao;
- }
- public static void setDao(DbDao dao) {
- DbDao.dao = dao;
- }
- public String getDriver() {
- return driver;
- }
- public void setDriver(String driver) {
- this.driver = driver;
- }
- public String getUrl() {
- return url;
- }
- public void setUrl(String url) {
- this.url = url;
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getPass() {
- return pass;
- }
- public void setPass(String pass) {
- this.pass = pass;
- }
- public void getConnection() throws ClassNotFoundException, SQLException
- {
- if(conn == null)
- {
- Class.forName(this.driver);
- conn = DriverManager.getConnection(url, username, pass);
- }
- }
- public static DbDao instance(String driver,String url,
- String username,String pass)
- {
- if(dao == null)
- {
- dao = new DbDao(driver,url,username,pass);
- }
- return dao;
- }
- public boolean insert(String sql) throws ClassNotFoundException, SQLException
- {
- getConnection();
- Statement statement = conn.createStatement();
- if(statement.executeUpdate(sql) != -1)
- {
- return false;
- }
- return true;
- }
- public ResultSet query(String sql) throws ClassNotFoundException, SQLException
- {
- getConnection();
- Statement statement = conn.createStatement();
- return statement.executeQuery(sql);
- }
- public void delete(String sql) throws ClassNotFoundException, SQLException
- {
- getConnection();
- Statement statement = conn.createStatement();
- statement.executeUpdate(sql);
- }
- public void update(String sql) throws ClassNotFoundException, SQLException
- {
- getConnection();
- Statement statement = conn.createStatement();
- statement.executeUpdate(sql);
- }
- }</pre>web.xml配置文件信息如下:<p></p>
- <p><pre class="html" name="code"><?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- <servlet>
- <servlet-name>myServlet</servlet-name>
- <servlet-class>com.cancique.dao.LoginServlet</servlet-class>
- <init-param>
- <param-name>driver</param-name>
- <param-value>com.mysql.jdbc.Driver</param-value>
- </init-param>
- <init-param>
- <param-name>url</param-name>
- <param-value>jdbc:mysql://localhost:3306/test_db</param-value>
- </init-param>
- <init-param>
- <param-name>user</param-name>
- <param-value>root</param-value>
- </init-param>
- <init-param>
- <param-name>pass</param-name>
- <param-value>900622</param-value>
- </init-param>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>myServlet</servlet-name>
- <url-pattern>/login</url-pattern>
- </servlet-mapping>
- </web-app>
- </pre><br>
- <br>
- <p></p>
- <p><br>
- </p>
- <br>