• HttpServlet


    HttpServlet(开发使用)

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

    2). 在 service() 方法中直接把 ServletReuqest 和 ServletResponse 转为 HttpServletRequest

        和 HttpServletResponse. 并调用了重载的 service(HttpServletRequest, HttpServletResponse)

         在 service(HttpServletRequest, HttpServletResponse) 获取了请求方式: request.getMethod().

         根据请求方式有创建了 doXxx() 方法(xxx 为具体的请求方式, 比如 doGet, doPost)

    package com.aff.java;
    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基类
     * @author lz
     *
     */
    public class MyHttpServlet extends MyGenericServlet {
    
        @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 {
    
        }
    
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        }
    }

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

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

    练习:定义一个 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.

    准备: 在 MySQL 数据库中创建一个 users 数据表, 添加 3 个字段:

                id, username, password. 并录入几条记录. 

    Loginservlet3

    package com.aff.java;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import com.aff.util.JDBCUtilsC3P0;
    
    public class Loginservlet3 extends HttpServlet {
        private static final long serialVersionUID = -2287053550217699690L;
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String username = req.getParameter("username");
            String password = req.getParameter("password");
    
            Connection conn = null;
            PreparedStatement ps = null;
            ResultSet rs = null;
            PrintWriter out = resp.getWriter();
            try {    
                    conn =JDBCUtilsC3P0.getConnection();
                    String sql = "SELECT count(id) FROM users WHERE username = ? and password = ?" ;
                        ps = conn.prepareStatement(sql);
                        ps.setString(1, username);
                        ps.setString(2, password);
                        rs = ps.executeQuery();
                        if (rs.next()) {
                            int count = rs.getInt(1);
                            if (count>0) {
                                out.print("hello:"+username);
                            }else{
                                out.print("sorry:"+username);
                            }
                        }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                JDBCUtilsC3P0.closeResource(conn, ps, rs);
            }
        }
    }

    login.html

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    
    <form action="loginServlet" method="post">
    user:<input type="text"  name="username"/>
    password:<input type="password" name="password"/>
    <input type="submit" value="Submit"/>
    </form>
    
    </body>
    </html>

    web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
        version="3.1">
        <!--配置当前web应用的初始化参数 全局的 -->
        <context-param>
            <param-name>user</param-name>
            <param-value>hmm</param-value>
        </context-param>
    
        <context-param>
            <param-name>password</param-name>
            <param-value>123456</param-value>
        </context-param>
    
        <servlet>
            <servlet-name>loginServlet</servlet-name>
            <servlet-class>com.aff.java.Loginservlet3</servlet-class>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>loginServlet</servlet-name>
            <url-pattern>/loginServlet</url-pattern>
        </servlet-mapping>
    
    </web-app>
    All that work will definitely pay off
  • 相关阅读:
    vuex
    JS判断浏览器类型和详细区分IE各版本浏览器
    javascript json对象操作(基本增删改查)
    react 使用antd 按需加载
    vue-cli 3.0 豆瓣api接口使用element做分页
    vue-cli 3.0 使用axios配置跨域访问豆瓣接口
    es6之扩展运算符 三个点(...)
    Vue.js——十分钟入门Vuex
    js数组的处理使用
    如何发布自己模块到NPM
  • 原文地址:https://www.cnblogs.com/afangfang/p/12717237.html
Copyright © 2020-2023  润新知