码迷,mamicode.com
首页 > 其他好文 > 详细

封装servlet

时间:2018-11-30 20:12:11      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:方法   use   jdbc   url   trace   login   row   cte   重写   

HttpServlet:

1). 是一个 Servlet, 继承自 GenericServlet. 针对于 HTTP 协议所定制.

2). 在 service() 方法中直接把 ServletReuqest 和 ServletResponse 转为 HttpServletRequest 和 HttpServletResponse.
并调用了重载的 service(HttpServletRequest, HttpServletResponse)

在 service(HttpServletRequest, HttpServletResponse) 获取了请求方式: request.getMethod(). 根据请求方式有创建了
doXxx() 方法(xxx 为具体的请求方式, 比如 doGet, doPost)

@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {

HttpServletRequest request;
HttpServletResponse response;

try {
request = (HttpServletRequest) req;
response = (HttpServletResponse) res;
} catch (ClassCastException e) {
throw new ServletException("non-HTTP request or response");
}
service(request, response);
}

public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1. 获取请求方式.
String method = request.getMethod();

//2. 根据请求方式再调用对应的处理方法
if("GET".equalsIgnoreCase(method)){
doGet(request, response);
}else if("POST".equalsIgnoreCase(method)){
doPost(request, response);
}
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
// TODO Auto-generated method stub

}

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub

}

3). 实际开发中, 直接继承 HttpServlet, 并根据请求方式复写 doXxx() 方法即可.

4). 好处: 直接由针对性的覆盖 doXxx() 方法; 直接使用 HttpServletRequest 和 HttpServletResponse, 不再需要强转.

1. GenericServlet:

1). 是一个 Serlvet. 是 Servlet 接口和 ServletConfig 接口的实现类. 但是一个抽象类. 其中的 service 方法为抽象方法

2). 如果新建的 Servlet 程序直接继承 GenericSerlvet 会使开发更简洁.

3). 具体实现:

①. 在 GenericServlet 中声明了一个 SerlvetConfig 类型的成员变量, 在 init(ServletConfig) 方法中对其进行了初始化
②. 利用 servletConfig 成员变量的方法实现了 ServletConfig 接口的方法
③. 还定义了一个 init() 方法, 在 init(SerlvetConfig) 方法中对其进行调用, 子类可以直接覆盖 init() 在其中实现对 Servlet 的初始化.
④. 不建议直接覆盖 init(ServletConfig), 因为如果忘记编写 super.init(config); 而还是用了 SerlvetConfig 接口的方法,
则会出现空指针异常.
⑤. 新建的 init(){} 并非 Serlvet 的生命周期方法. 而 init(ServletConfig) 是生命周期相关的方法.

public abstract class GenericServlet implements Servlet, ServletConfig {

/** 以下方法为 Servlet 接口的方法 **/
@Override
public void destroy() {}

@Override
public ServletConfig getServletConfig() {
return servletConfig;
}

@Override
public String getServletInfo() {
return null;
}

private ServletConfig servletConfig;

@Override
public void init(ServletConfig arg0) throws ServletException {
this.servletConfig = arg0;
init();
}

public void init() throws ServletException{}

@Override
public abstract void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException;

/** 以下方法为 ServletConfig 接口的方法 **/
@Override
public String getInitParameter(String arg0) {
return servletConfig.getInitParameter(arg0);
}

@Override
public Enumeration getInitParameterNames() {
return servletConfig.getInitParameterNames();
}

@Override
public ServletContext getServletContext() {
return servletConfig.getServletContext();
}

@Override
public String getServletName() {
return servletConfig.getServletName();
}

 

下面针对HTTP协议封装一个基类:

@Override
    public void service(ServletRequest request, ServletResponse response)
            throws ServletException, IOException {
        
        //获取请求方式是 GET 还是 POST
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;  //需要强转  不够好哦  要是封装下 
        String method = httpServletRequest.getMethod();

封装:

package com.atguigu.javaweb;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 针对于 HTTP 协议定义的一个 Servlet 基类
 */
public class MyHttpServlet extends MyGenericServlet {

    @Override
    public void service(ServletRequest arg0, ServletResponse arg1)
            throws ServletException, IOException {
        
        if(arg0 instanceof HttpServletRequest){
            HttpServletRequest request = (HttpServletRequest)arg0;
            
            if(arg1 instanceof HttpServletResponse){
                HttpServletResponse response = (HttpServletResponse)arg1;
                
                service(request, response);
            }
        }
        
    }
    
    public void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //1. 获取请求方式.
        String method = request.getMethod();
        
        //2. 根据请求方式再调用对应的处理方法
        if("GET".equalsIgnoreCase(method)){
            doGet(request, response);
        }else if("POST".equalsIgnoreCase(method)){
            doPost(request, response);
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException{
        // TODO Auto-generated method stub
        
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        
    }


}

使用起来不用强转了!:

package com.atguigu.javaweb;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet2 extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L; 

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {

        // 获取请求方式是 GET 还是 POST
        String method = request.getMethod();
        System.out.println(method);

        // 1. 获取请求参数: username, password
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 2. 获取当前 WEB 应用的初始化参数: user, password.
        // 需要使用 ServletContext 对象.
        String initUser = getServletContext().getInitParameter("user");
        String initPassword = getServletContext().getInitParameter("password");

        PrintWriter out = response.getWriter();

        // 3. 比对
        // 4. 打印响应字符串.
        if (initUser.equals(username) && initPassword.equals(password)) {
            out.print("Hello: " + username);
        } else {
            out.print("Sorry: " + username);
        }

    }

}

 


在 MySQL 数据库中创建一个 test_users 数据表, 添加 3 个字段: id, user, password. 并录入几条记录.

定义一个 login.html, 里边定义两个请求字段: user, password. 发送请求到 loginServlet
在创建一个 LoginServlet(需要继承自 HttpServlet, 并重写其 doPost 方法),
在其中获取请求的 user, password.

利用 JDBC 从 test_users 中查询有没有和页面输入的 user, password 对应的记录

SELECT count(id) FROM test_users WHERE user = ? AND password = ?

若有, 响应 Hello:xxx, 若没有, 响应 Sorry: xxx xxx 为 user.

package com.atguigu.javaweb;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet3 extends HttpServlet{
    
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        
        PrintWriter out = resp.getWriter();
        
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql:///atguigu";
            String user = "root";
            String password2 = "1230";
            connection = DriverManager.getConnection(url, user, password2);
            
            String sql = "SELECT count(id) FROM users WHERE username = ? " +
                    "AND password = ?";
            
            statement = connection.prepareStatement(sql);
            statement.setString(1, username);
            statement.setString(2, password);
            
            resultSet = statement.executeQuery();

            StringBuilder result = new StringBuilder();
            result.append("<html>")
                  .append(" <head>")
                  .append(" </head>") 
                  .append("</html>");
            
            if(resultSet.next()){
                int count = resultSet.getInt(1);
                
                if(count > 0){
                    out.print(result.toString());
                    
                }else{
                    out.print("Sorry: " + username);
                }
            }
            
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            try {
                if(resultSet != null){
                    resultSet.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

            try {
                if(statement != null){
                    statement.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            
            try {
                if(connection != null){
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            
        }
            
    }

}

 

封装servlet

标签:方法   use   jdbc   url   trace   login   row   cte   重写   

原文地址:https://www.cnblogs.com/toov5/p/10045653.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!