JavaEE Day14 Servlet&HTTP&Request

今日内容
1、Servlet
2、HTTP协议
3、Request
一、Servlet
1、概念
2、步骤
3、执行原理
4、生命周期
5、Servlet 3.0注解配置
6、Servlet体系结构
Servlet---接口
        |
GenericServlet---抽象类
        |
 HttpServlet---抽象类
  • GenericServlet:将Servlet接口中的其他方法做了默认空实现,只将service()方法作为抽象
    • 将来定义Servlet类时,可以继承GenericServlet,实现service()方法即可
    • 其他方法可以复写重写@Override
    • 不用这种方式
  • HttpServlet:对http协议的一种封装,可以简化操作
    • 定义类去继承HttpServlet
    • 复写doget或dopost方法
JavaEE Day14 Servlet&HTTP&Request_第1张图片
7、Servlet相关配置
  1. urlpattern
    1. 一个Servlet可以定义多个访问路径   @WebServlet({"/demo4","/dd4"})
    2. 路径的定义规则 
      1. /XXX
      2. /XXX/XXX:多层路径/目录结构
      3. *.do/其他后缀名
二、HTTP
1、概念:Hyper Text Transfer Protocol 超文本传输协议
  • 传输协议:定义了客户端和服务器端通信时发送数据的格式
JavaEE Day14 Servlet&HTTP&Request_第2张图片
  • 特点:
    • 基于TCP/IP的高级协议
    • 默认端口好:80
      • http://www.baidu.com:80
    • 基于请求响应模型的:一次请求对应于一次响应
    • 无状态的协议:每次请求之间相互独立,多次请求响应之间不能交互数据
  • 历史版本
    • 1.0:每一次请求响应都会建立新的连接
    • 1.1:复用之前的连接(css、图片等,一个页面包含多个连接),对缓存的支持比较好
2、request请求消息数据格式
  • 请求行
    • 请求方式: 请求url  请求协议/版本
    • GET /login.html  HTTP1.1 
      •  HTTP有7种请求方式,常用的有两种
        • GET
          • 请求参数在请求行中/在url后
          • 请求的url长度是有限制的
          • 不太安全
        • POST
          • 请求参数在请求体中
          • 请求的url长度是没有限制的
          • 相对安全
  • 请求头
    • 请求头名称:请求头值JavaEE Day14 Servlet&HTTP&Request_第3张图片
      JavaEE Day14 Servlet&HTTP&Request_第4张图片
    • 常见的请求头
      • host:请求的主机
      • User-Agent:浏览器告诉服务器,访问时使用的浏览器版本信息
        • 可以在服务器端获取浏览器的信息,来解决兼容性问题
          JavaEE Day14 Servlet&HTTP&Request_第5张图片
      • Accept:访问时可以相应的格式
      • Accept-Encoding:可以接收的编码或压缩格式
      • Refere:告诉服务器,我(当前请求)从哪里来
        • 作用
          • 防盗链
          • 统计工作
            JavaEE Day14 Servlet&HTTP&Request_第6张图片
      • Connection:连接是否可以复用
      • Upgrade-Insecure-request:升级
  • 请求空行
    • 空行
  • 请求体/正文
    • 封装post请求消息请求体的
  • 字符串格式:
    GET /login.html HTTP1.1
JavaEE Day14 Servlet&HTTP&Request_第7张图片
三、Request
1、request对象和response对象的原理
JavaEE Day14 Servlet&HTTP&Request_第8张图片
通过request对象获取请求消息数据,通过response对象设置响应消息数据
注意:
  1. request和response对象是由服务器创建的,我们来使用而已
  2. request对象获取请求消息,response对象设置响应消息
2、 request对象的继承体系结构
ServletRequest-----接口
            |  继承
HttpServletRequest---接口
            |  实现
org.apache.catalina.connector.RequestFacade@3beac8b5(tomcat创建的类实现了上述接口)
3、Request对象的功能
  • 获取请求消息数据
    • 获取请求行数据
      • GET /day14/demo1?name=zhangsan HTTP/1.1
      • 方法
        • 获取请求方式:GET
          • String getMethod()  
          • (*)获取虚拟目录:/day14
            • String getContextPath()
            • 获取Servlet的路径:  /demo1
              • String getServlet()
              • 获取get方式的请求方式:name=zhangsan
                • String getQueryString()
                • (*)获取请求的URI:/day14/demo1
                  • String getRequestURI():/day14/demo1
                  • StringBuffer getRequestURL()  :http://localhost/day14/demo1
                  • 区别
                    • URL:统一资源定位符--http://localhost/day14/demo1,相当于中华人民共和国
                    • URI:统一资源标识符--/day14/demo1,相当于共和国,范围大
                  • 获取协议及版本 :HTTP/1.1
                    • String getProtocol()
                    • 获取客户机的IP地址
                      • String getRemoteAddr()
                      代码
                      package cm.liujinhui.web.request;
                      
                      import javax.servlet.ServletException;
                      import javax.servlet.annotation.WebServlet;
                      import javax.servlet.http.HttpServlet;
                      import javax.servlet.http.HttpServletRequest;
                      import javax.servlet.http.HttpServletResponse;
                      import java.io.IOException;
                      
                      /**
                       * 演示request对象获取请求行数据
                       *
                       * 获取请求行数据
                       GET /day14/demo1?name=zhangsan HTTP/1.1
                       方法
                       获取请求方式:GET
                       String getMethod()
                       (*)获取虚拟目录:/day14
                       String getContextPath()
                       获取Servlet的路径:  /demo1
                       String getServlet()
                       获取get方式的请求方式:name=zhangsan
                       String getQueryString()
                       (*)获取请求的URI:/day14/demo1
                       String getRequestURI():/day14/demo1
                       StringBuffer getRequestURL()  :http://localhost/day14/demo1
                       获取协议及版本 :HTTP/1.1
                       String getProtocol()
                       获取客户机的IP地址
                       String getRemoteAddr()
                       */
                      @WebServlet("/RequestDemo1")
                      public class RequestDemo1 extends HttpServlet {
                          protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                      
                          }
                          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                              //1.获取请求方式
                              System.out.println(request.getMethod());
                              //2.(*)获取虚拟目录:/day14
                              System.out.println(request.getContextPath());
                              //3.获取Servlet的路径:  /demo1
                              System.out.println(request.getServletPath());
                              //获取get方式的请求方式:name=zhangsan
                              System.out.println(request.getQueryString());
                              //(*)获取请求的URI:/day14/demo1
                              System.out.println(request.getRequestURI());
                              System.out.println(request.getRequestURL());
                              // 获取协议及版本 :HTTP/1.1
                              System.out.println(request.getProtocol());
                              //获取客户机的IP地址
                              System.out.println(request.getRemoteAddr());
                          }
                      }
                        • 获取请求头数据
                          • 方法
                            • String getHeader(String name):通过请求头的名称获取请求头的值
                            • Enumeration getHeaderNames():获取所有请求头名称
                              • 该接口的功能由Iterator接口复制。 此外, Iterator添加了可选的删除操作,并且具有较短的方法名称。 新的实现应该考虑使用Iterator ,而不是Enumeration 。 
                        JavaEE Day14 Servlet&HTTP&Request_第9张图片
                        代码演示
                        package cm.liujinhui.web.request;
                        
                        import javax.servlet.ServletException;
                        import javax.servlet.annotation.WebServlet;
                        import javax.servlet.http.HttpServlet;
                        import javax.servlet.http.HttpServletRequest;
                        import javax.servlet.http.HttpServletResponse;
                        import java.io.IOException;
                        import java.util.Enumeration;
                        
                        /**
                         * 演示获取请求头数据:user-agent
                         */
                        @WebServlet("/RequestDemo3")
                        public class RequestDemo3 extends HttpServlet {
                            protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                        
                            }
                        
                            protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                                //演示获取请求头数据:user-agent
                                String agent = request.getHeader("user-agent");
                                //判断agent的浏览器版本
                                if (agent.contains("Chrome")){
                                    //谷歌
                                    System.out.println("谷歌来了。。。");
                                    //以后可以解决兼容信息
                                }else if (agent.contains("Firefox")){
                                    //火狐浏览器
                                    System.out.println("火狐来了");
                                }
                            }
                        }
                        package cm.liujinhui.web.request;
                        import javax.servlet.ServletException;
                        import javax.servlet.annotation.WebServlet;
                        import javax.servlet.http.HttpServlet;
                        import javax.servlet.http.HttpServletRequest;
                        import javax.servlet.http.HttpServletResponse;
                        import java.io.IOException;
                        /**
                         * 演示获取请求头数据:referer
                         */
                        @WebServlet("/RequestDemo4")
                        public class RequestDemo4 extends HttpServlet {
                            protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                            }
                            protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                                //演示获取请求头数据:referer
                                String referer = request.getHeader("referer");
                                System.out.println(referer);
                                //防盗链
                                if (referer!=null){
                                    if (referer.contains("/day14")){
                                        //正常访问
                                        System.out.println("播放电影");
                                        response.setContentType("text/html;charset=utf-8");
                                        response.getWriter().write("播放电影");
                                    }else{
                                        //盗链
                                        System.out.println("想看电影吗,来优酷吧");
                                        response.setContentType("text/html;charset=utf-8");
                                        response.getWriter().write("想看电影吗,来优酷吧");
                                    }
                                }
                        
                            }
                        }
                          • 获取请求体数据
                            • 请求体:只要POST方式,才有请求体,在请求体中封装了POST请求的请求参数
                            • 步骤:
                              • 获取流对象
                                • BufferedReader getReader()  :获取字符输入流,只能操作字符数据
                                • ServletInputStream getInputStream():获取字节输入流,可以操作所有类型数据【也可以字符】
                                  • 在文件上传知识点后讲解
                              • 再从流对象中拿数据(字节流或字符流)
                          package cm.liujinhui.web.request;
                          import javax.servlet.ServletException;
                          import javax.servlet.annotation.WebServlet;
                          import javax.servlet.http.HttpServlet;
                          import javax.servlet.http.HttpServletRequest;
                          import javax.servlet.http.HttpServletResponse;
                          import java.io.BufferedReader;
                          import java.io.IOException;
                          @WebServlet("/RequestDemo5")
                          public class RequestDemo5 extends HttpServlet {
                              protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                                  //获取请求消息体--请求参数
                                  //1.获取字符流
                                  BufferedReader br = request.getReader();
                                  //2.读取数据
                                  String line = null;
                                  while((line=br.readLine())!=null){
                                      System.out.println(line);
                                  }
                              }
                          
                              protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                          
                              }
                          }
                          
                          
                          
                              
                              Title
                          
                          
                          


                          4、其他功能
                          • 获取请求参数通用方式:不论是get还是post请求方式都可以使用下列方法来获取请求参数
                            • String getParameter(String name):根据参数名称获取参数值
                              • 如:user=zs&password=123
                            • String[] getParameterValues(String name):根据参数名称获取参数值的数组 
                              • 如:hobby=xxx&hobby=111 复选框
                            • Enumeration  getParameterNames():获取所有请求的参数名称
                            • Map getParameterMap():获取参数键值对的集合
                          package cm.liujinhui.web.request;
                          import javax.servlet.ServletException;
                          import javax.servlet.annotation.WebServlet;
                          import javax.servlet.http.HttpServlet;
                          import javax.servlet.http.HttpServletRequest;
                          import javax.servlet.http.HttpServletResponse;
                          import java.io.BufferedReader;
                          import java.io.IOException;
                          import java.util.Enumeration;
                          import java.util.Map;
                          import java.util.Set;
                          
                          @WebServlet("/RequestDemo6")
                          public class RequestDemo6 extends HttpServlet {
                              protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                                 //post获取请求参数
                                  //根据参数名称获取参数值
                                  String username = request.getParameter("username");
                                  /*System.out.println("post");
                                  System.out.println(username);*/
                                  //String[] getParameterValues(String name):根据参数名称获取参数值的数组
                                  String[] hobbies = request.getParameterValues("hobby");
                                  /*for (String hobby : hobbies) {
                                      System.out.println(hobby);
                                  }*/
                                  //Enumeration  getParameterNames():获取所有请求的参数名称
                                  Enumeration parameterNames = request.getParameterNames();
                              /*    while(parameterNames.hasMoreElements()){
                                      String name = parameterNames.nextElement();
                                      System.out.println(name);
                                      String value = request.getParameter(name);
                                      System.out.println(value);
                                      System.out.println("-----------------");
                                  }*/
                                  //Map getParameterMap():获取参数键值对的集合
                                  Map parameterMap = request.getParameterMap();
                                  //遍历,keySet
                                  Set keySet = parameterMap.keySet();
                                  for (String name : keySet) {
                                      //根据键获取值
                                      String[] values = parameterMap.get(name);
                                      System.out.println(name);
                                      for (String value : values) {
                                          System.out.println(value);
                                      }
                                      System.out.println("-------------");
                                  }
                              }
                          
                              protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                                  //post获取请求参数
                                  //根据参数名称获取参数值
                                  /*String username = request.getParameter("username");
                                  System.out.println("get");
                                  System.out.println(username);*/
                                  this.doPost(request,response);
                              }
                          }
                            • 产生的中文乱码问题
                              • get方式:tomcat8已经将get方式乱码问题解决
                              • post方式:会乱码
                                • 解决:在获取参数前,设置request的编码request.setCharacterEncoding("utf-8");
                          package cm.liujinhui.web.request;
                          import javax.servlet.ServletException;
                          import javax.servlet.annotation.WebServlet;
                          import javax.servlet.http.HttpServlet;
                          import javax.servlet.http.HttpServletRequest;
                          import javax.servlet.http.HttpServletResponse;
                          import java.io.IOException;
                          import java.util.Enumeration;
                          import java.util.Map;
                          import java.util.Set;
                          
                          @WebServlet("/RequestDemo7")
                          public class RequestDemo7 extends HttpServlet {
                              protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                                  //1.设置流的字符集
                                  request.setCharacterEncoding("utf-8");
                                  //获取请求参数username
                                  String username = request.getParameter("username");
                                  System.out.println(username);
                              }
                          
                              protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                          
                                  this.doPost(request,response);
                              }
                          }
                          • 请求转发:一种在服务器内部的资源跳转方式
                          JavaEE Day14 Servlet&HTTP&Request_第10张图片
                            • 步骤
                              • 通过request对象获取请求转发器对象:RequestDispatcher getRequestDispatcher(String path)
                              • 使用RequestDispatcher对象进行转发:void forward(ServletRequest request,ServletResponse response)
                            • 特点【面试】:
                              • 浏览器地址栏路径没有发生变化
                              • 只能转发到当前服务器内部的资源中
                              • 多个转发属于同一次请求
                          package cm.liujinhui.web.request;
                          import javax.servlet.ServletException;
                          import javax.servlet.annotation.WebServlet;
                          import javax.servlet.http.HttpServlet;
                          import javax.servlet.http.HttpServletRequest;
                          import javax.servlet.http.HttpServletResponse;
                          import java.io.IOException;
                          
                          @WebServlet("/RequestDemo8")
                          public class RequestDemo8 extends HttpServlet {
                              protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                                  System.out.println("demo8888888888被访问了");
                                  //转发到demo9资源
                                  request.getRequestDispatcher("/RequestDemo9").forward(request,response);
                                  //request.getRequestDispatcher("http://www.itcast.cn").forward(request,response);
                              }
                          
                              protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                          
                                  this.doPost(request,response);
                              }
                          }
                          package cm.liujinhui.web.request;
                          import javax.servlet.ServletException;
                          import javax.servlet.annotation.WebServlet;
                          import javax.servlet.http.HttpServlet;
                          import javax.servlet.http.HttpServletRequest;
                          import javax.servlet.http.HttpServletResponse;
                          import java.io.IOException;
                          
                          @WebServlet("/RequestDemo9")
                          public class RequestDemo9 extends HttpServlet {
                              protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                                  System.out.println("demo999999999999也被访问了");
                              }
                          
                              protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                          
                                  this.doPost(request,response);
                              }
                          }
                          • 共享数据(域对象)
                            • 域对象:一个有作用范围的对象,可以在范围内共享数据
                            • request域:一次请求的范围,一般用于请求转发的多个资源中共享数据。(转发过程中共享数据)
                            • 方法
                              • void setAttribute(String name,Object obj ):存储数据
                              • Object getAttribute(String name):通过键获取值
                              • void removeAttribute(String name): 通过键移除键值对
                          • 获取ServletContext对象
                            • ServletContext getServletContext()
                          package cm.liujinhui.web.request;
                          import javax.servlet.ServletException;
                          import javax.servlet.annotation.WebServlet;
                          import javax.servlet.http.HttpServlet;
                          import javax.servlet.http.HttpServletRequest;
                          import javax.servlet.http.HttpServletResponse;
                          import java.io.IOException;
                          
                          @WebServlet("/RequestDemo8")
                          public class RequestDemo8 extends HttpServlet {
                              protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                                  System.out.println("demo8888888888被访问了");
                                  //存储数据到request中
                                  request.setAttribute("msg","hello");
                                  //转发到demo9资源
                                  request.getRequestDispatcher("/RequestDemo9").forward(request,response);
                                  //request.getRequestDispatcher("http://www.itcast.cn").forward(request,response);
                              }
                          
                              protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                          
                                  this.doPost(request,response);
                              }
                          }
                          package cm.liujinhui.web.request;
                          import javax.servlet.ServletContext;
                          import javax.servlet.ServletException;
                          import javax.servlet.annotation.WebServlet;
                          import javax.servlet.http.HttpServlet;
                          import javax.servlet.http.HttpServletRequest;
                          import javax.servlet.http.HttpServletResponse;
                          import java.io.IOException;
                          
                          @WebServlet("/RequestDemo9")
                          public class RequestDemo9 extends HttpServlet {
                              protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                                  System.out.println("demo999999999999也被访问了");
                                  //获取数据
                                  Object msg = request.getAttribute("msg");
                                  System.out.println(msg);
                                  ServletContext servletContext = request.getServletContext();
                                  System.out.println(servletContext);
                              }
                          
                              protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                          
                                  this.doPost(request,response);
                              }
                          }
                          四、登录案例
                          1、需求描述
                          用户登录案例需求:
                          •  1.编写login.html登录页面
                          •   username & password 两个输入框
                          •  2.使用Druid数据库连接池技术,操作mysql,day14数据库中user表
                          •  3.使用JdbcTemplate技术封装JDBC
                          •  4.登录成功跳转到SuccessServlet展示:登录成功!用户名,欢迎您
                          •  5.登录失败跳转到FailServlet展示:登录失败,用户名或密码错误
                          2、分析
                          JavaEE Day14 Servlet&HTTP&Request_第11张图片
                          Dao:Database Access Object
                          JavaEE Day14 Servlet&HTTP&Request_第12张图片
                          JavaEE Day14 Servlet&HTTP&Request_第13张图片
                          3、开发步骤
                          • 创建项目,导入html页面,配置文件,jar包
                          
                          
                          
                              
                              Title
                          
                          
                              
                          用户名:
                          密码:
                          • 创建数据库环境
                          CREATE DATABASE day14;
                          
                          USE day14;
                          
                          CREATE TABLE USER(
                          	id INT PRIMARY KEY AUTO_INCREMENT,
                          	username VARCHAR(32) UNIQUE NOT NULL,
                          	PASSWORD VARCHAR(32) NOT NULL
                          );
                          • 创建包:cn.itcast.domain,创建User类(包和类一次创建好)
                          package cn.liujinhui.domain;
                          
                          /**
                           * 用户的实体类JavaBean
                           */
                          public class User {
                              private int id;
                              private String username;
                              private String password;
                              public int getId() {
                                  return id;
                              }
                          
                              public void setId(int id) {
                                  this.id = id;
                              }
                          
                              public String getUsername() {
                                  return username;
                              }
                          
                              public void setUsername(String username) {
                                  this.username = username;
                              }
                          
                              public String getPassword() {
                                  return password;
                              }
                          
                              public void setPassword(String password) {
                                  this.password = password;
                              }
                          
                              @Override
                              public String toString() {
                                  return "User{" +
                                          "id=" + id +
                                          ", username='" + username + '\'' +
                                          ", password='" + password + '\'' +
                                          '}';
                              }
                          }
                          • 先写操作数据库逻辑的代码,再写对应的Servlet
                          package cn.liujinhui.util;
                          
                          import com.alibaba.druid.pool.DruidDataSourceFactory;
                          
                          import javax.sql.DataSource;
                          import java.io.IOException;
                          import java.io.InputStream;
                          import java.sql.Connection;
                          import java.sql.SQLException;
                          import java.util.Properties;
                          
                          /**
                           * JDBC的工具类 使用Durid连接池
                           */
                          public class JDBCUtils {
                              private static DataSource ds;
                              static{
                                  //1.加载配置文件
                                  Properties pro = new Properties();
                                  //使用ClassLoader加载配置文件,获取字节输入流
                                  InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
                                  try {
                                      pro.load(is);
                                  } catch (IOException e) {
                                      e.printStackTrace();
                                  }
                                  //2.初始化连接对象
                                  try {
                                      ds = DruidDataSourceFactory.createDataSource(pro);
                                  } catch (Exception e) {
                                      e.printStackTrace();
                                  }
                              }
                              /**
                               * 文档注释
                               * 获取连接池对象
                               */
                              public static DataSource getDataSource(){
                                  return ds;
                              }
                          
                          
                              /**
                               * 获取连接Connection对象
                               */
                              public static Connection  getConnection() throws SQLException {
                                  return ds.getConnection();
                              }
                          }
                          • 创建包cn.liujinhui.dao,创建类UserDao,提供login方法
                          package cn.liujinhui.dao;
                          
                          import cn.liujinhui.domain.User;
                          import cn.liujinhui.util.JDBCUtils;
                          import org.springframework.dao.DataAccessException;
                          import org.springframework.jdbc.core.BeanPropertyRowMapper;
                          import org.springframework.jdbc.core.JdbcTemplate;
                          
                          /**
                           * 操作数据库中User表的类
                           */
                          public class UserDao {
                              //声明JDBCTemplate对象公用
                              private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
                              /**
                               * 文档注释:登录方法
                               * @param loginUser 只有用户名和密码
                               * @return User 包含用户全部数据;没有查询到,返回null
                               * 需要使用druid连接池才能实现,先创建一个工具类
                               */
                              public User login(User loginUser){
                                  try {
                                      //1.编写sql
                                      String sql= "select * from user where username = ? and password = ?";
                                      //2.调用query方法
                                      User user = template.queryForObject(sql,
                                              new BeanPropertyRowMapper(User.class),
                                              loginUser.getUsername(), loginUser.getPassword());
                                      return user;
                                  } catch (DataAccessException e) {
                                      e.printStackTrace();
                                      return null;
                                  }
                              }
                          }
                          • 编写cn.liujinhui.web.servlet.LoginServlet类
                          package cn.liujinhui.web.servlet;
                          
                          import cn.liujinhui.domain.User;
                          
                          import javax.servlet.ServletException;
                          import javax.servlet.annotation.WebServlet;
                          import javax.servlet.http.HttpServlet;
                          import javax.servlet.http.HttpServletRequest;
                          import javax.servlet.http.HttpServletResponse;
                          import java.io.IOException;
                          
                          @WebServlet("/successServlet")
                          public class successServlet extends HttpServlet {
                              protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                                  //给页面写一句话
                                  //设置编码
                                  response.setContentType("text/html;charset=utf-8");
                                  //获取request中共享的user对象
                                  User user = (User) request.getAttribute("user");
                                  if (user!=null){
                                      //输出
                                      response.getWriter().write("登录成功!"+user.getUsername()+",欢迎您");
                                  }
                              }
                              protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                                  this.doPost(request,response);
                              }
                          }
                          package cn.liujinhui.web.servlet;
                          
                          import javax.servlet.ServletException;
                          import javax.servlet.annotation.WebServlet;
                          import javax.servlet.http.HttpServlet;
                          import javax.servlet.http.HttpServletRequest;
                          import javax.servlet.http.HttpServletResponse;
                          import java.io.IOException;
                          
                          @WebServlet("/failServlet")
                          public class failServlet extends HttpServlet {
                              protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                                  //给页面写一句话
                                  //设置编码
                                  response.setContentType("text/html;charset=utf-8");
                                  //输出
                                  response.getWriter().write("登录失败,用户名或密码错误");
                              }
                          
                              protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                                  this.doPost(request,response);
                              }
                          }
                          • 注意:login.html中form表单的action路径的写法
                            • 虚拟目录+Servlet的资源路径
                          package cn.liujinhui.test;
                          
                          import cn.liujinhui.dao.UserDao;
                          import cn.liujinhui.domain.User;
                          import org.junit.Test;
                          
                          public class UserDaoTest {
                              @Test
                              public void testLogin(){
                                  User loginuser = new User();
                                  loginuser.setUsername("superbaby");
                                  loginuser.setPassword("123");
                                  UserDao dao = new UserDao();
                                  User user = dao.login(loginuser);
                                  System.out.println(user);
                              }
                          }
                          driverClassName=com.mysql.jdbc.Driver
                          url=jdbc:mysql:///day14
                          username=root
                          password=root
                          initialSize=5
                          maxActive=10
                          maxWait=3000
                          4、通过BeanUtils类,简化数据封装,一次把所有数据获取出来
                          package cn.liujinhui.web.servlet;
                          
                          import cn.liujinhui.dao.UserDao;
                          import cn.liujinhui.domain.User;
                          import org.apache.commons.beanutils.BeanUtils;
                          
                          import javax.servlet.ServletException;
                          import javax.servlet.annotation.WebServlet;
                          import javax.servlet.http.HttpServlet;
                          import javax.servlet.http.HttpServletRequest;
                          import javax.servlet.http.HttpServletResponse;
                          import java.io.IOException;
                          import java.lang.reflect.InvocationTargetException;
                          import java.util.Map;
                          
                          @WebServlet("/LoginServlet")
                          public class LoginServlet extends HttpServlet {
                              @Override
                              protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                                  //1.设置编码
                                  req.setCharacterEncoding("utf-8");
                                  //2.获取请求参数
                                  /*String username = req.getParameter("username");
                                  String password = req.getParameter("password");
                                  //3.封装user对象
                                  User loginUser = new User();
                                  loginUser.setUsername(username);
                                  loginUser.setPassword(password);*/
                                  //2.获取所有请求参数
                                  Map map = req.getParameterMap();
                                  //3.创建User对象
                                  User loginUser = new User();
                                  //3.2使用BeanU体力上封装
                                  try {
                                      BeanUtils.populate(loginUser,map);
                                  } catch (IllegalAccessException e) {
                                      e.printStackTrace();
                                  } catch (InvocationTargetException e) {
                                      e.printStackTrace();
                                  }
                                  //4.调用UserDao的login方法
                                  UserDao userDao = new UserDao();
                                  try {
                                      User user = userDao.login(loginUser);
                                      //5.判断uswr
                                      if(user==null){
                                          //登录失败
                                          req.getRequestDispatcher("/failServlet").forward(req,resp);
                                      }else{
                                          //登录成功
                                          //存储数据
                                          req.setAttribute("user",user);
                                          req.getRequestDispatcher("/successServlet").forward(req,resp);
                                      }
                                  } catch (ServletException e) {
                                      e.printStackTrace();
                                  } catch (IOException e) {
                                      e.printStackTrace();
                                  }
                              }
                          
                              @Override
                              protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                                  super.doGet(req, resp);
                              }
                          }
                          5、BeanUtils介绍
                          用于封装JavaBean的
                          JavaEE Day14 Servlet&HTTP&Request_第14张图片
                          • JavaBean:标准的Java类【domain】
                            • 定义要求
                              • 类必须被public修饰
                              • 必须提供空参的构造器
                              • 成员变量必须使用private修饰
                              • 必须提供公共的getter和setter方法
                            • 功能:封装数据
                          • 概念
                            • 成员变量
                            • 属性:setter和getter方法截取后的产物
                              • 例如:getUsername()--->Username--->username
                              • 大多数情况一样,可以不一样
                          • 方法:
                            • setProperty()
                            • getProperty()
                            • populate(Object obj , Map map):将map集合的键值对信息,封装到对应的JavaBean对象中
                          package cn.liujinhui.domain;
                          
                          /**
                           * 用户的实体类JavaBean
                           */
                          public class User {
                              private int id;
                              private String username;
                              private String password;
                              private String gender;
                              public void setHehe(String gender){
                                  this.gender=gender;
                              }
                              public String getHehe(){
                                  return gender;
                              }
                              public int getId() {
                                  return id;
                              }
                          
                              public void setId(int id) {
                                  this.id = id;
                              }
                          
                              public String getUsername() {
                                  return username;
                              }
                          
                              public void setUsername(String username) {
                                  this.username = username;
                              }
                          
                              public String getPassword() {
                                  return password;
                              }
                          
                              public void setPassword(String password) {
                                  this.password = password;
                              }
                          
                              @Override
                              public String toString() {
                                  return "User{" +
                                          "id=" + id +
                                          ", username='" + username + '\'' +
                                          ", password='" + password + '\'' +
                                          ", gender='" + gender + '\'' +
                                          '}';
                              }
                          }
                          package cn.liujinhui.test;
                          
                          import cn.liujinhui.domain.User;
                          import org.apache.commons.beanutils.BeanUtils;
                          import org.junit.Test;
                          
                          import java.lang.reflect.InvocationTargetException;
                          
                          public class BeanUtilsTest {
                              @Test
                              public void test(){
                                  User user = new User();
                                  try {
                                      BeanUtils.setProperty(user,"hehe","male");
                                      System.out.println(user);
                                      String gender = BeanUtils.getProperty(user, "hehe");
                                      System.out.println(gender);
                                  } catch (IllegalAccessException e) {
                                      e.printStackTrace();
                                  } catch (InvocationTargetException e) {
                                      e.printStackTrace();
                                  } catch (NoSuchMethodException e) {
                                      e.printStackTrace();
                                  }
                              }
                          }
                          来自为知笔记(Wiz)

                          你可能感兴趣的:(servlet,http,java-ee,java,前端)