Java learning notes - Request

Principle of request object and response object
  • The request and response objects are created by the server
  • The request object is the message to get the request, and the response object is the message to set the response
  • request object inheritance architecture:
    ServletRequest -- Interface
     Inherit
     HttpServletRequest -- Interface
     Implementation
     org.apache.catalina.connector.RequestFacade -- class (tomcat)
request function:
  1. Get data:
    • Get request line message:
      • Get request method: String getMethod()
      • Get virtual directory: String getContextPath()
      • Get Servlet path: String getServletPath()
      • Get parameter of get method: String getQueryString()
      • Get the URI of the request: String getRequestURI() and String getRequestURL()
      • Get protocol and version: String getProtocol()
      • Get the IP address of the client: String getRemoteAddr()
    	// http://localhost:8087/day22_2_war_exploded/RequestDemo1?name=zhangsan
        String method = request.getMethod();
        System.out.println(method); // GET
        String contextPath = request.getContextPath();
        System.out.println(contextPath); // /day22_2_war_exploded
        String servletPath = request.getServletPath();
        System.out.println(servletPath); // /RequestDemo1
        String queryString = request.getQueryString();
        System.out.println(queryString); // name=zhangsan
        // URI: Uniform Resource Identifier
        String requestURI = request.getRequestURI();
        System.out.println(requestURI); // /day22_2_war_exploded/RequestDemo1
        // URL: Uniform Resource Locator
        StringBuffer requestURL = request.getRequestURL();
        System.out.println(requestURL); // http://localhost:8087/day22_2_war_exploded/RequestDemo1
        String protocol = request.getProtocol();
        System.out.println(protocol); // HTTP/1.1
        String remoteAddr = request.getRemoteAddr();
        System.out.println(remoteAddr); // 0:0:0:0:0:0:0:1
    1. Get request header data:
      String getHeader(String name): get the value of the request header by the name of the request header
      Enumeration < string > getheadernames(): get all request header names
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()){
                String s = headerNames.nextElement();
                String header = request.getHeader(s);
                System.out.println(header);
            }
    1. Get request body data:
      • Request body: only POST request mode can have a request body, which encapsulates the request parameters of POST request
      • Steps:
        • Get stream object
          BufferedReader getReader(): get character input stream, only character data can be operated
          ServletInputStream getInputStream(): get byte input stream and operate all data
        • Get data from stream object
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            BufferedReader reader = request.getReader();
            String line=null;
            while ((line=reader.readLine())!=null){
                System.out.println(line); // username=milesmatheson&password=123
            }
        }
        <form action="/day22_2_war_exploded/requestdemo3" method="post">
            <input type="text" placeholder="enter one user name" name="username"><br>
            <input type="text" placeholder="Please input a password" name="password"><br>
            <input type="submit" value="register">
        </form>
  2. Other functions:
    2.1 get request parameters in a general way
    2.1.1 String getParameter(String name): get parameter value according to parameter name
            String username = request.getParameter("password");
            System.out.println(username);
    2.1.2 String[] getParameterValues(String name): get the array of parameter values according to the parameter name
    String[] parameterValues = request.getParameterValues("username");
    System.out.println(Arrays.toString(parameterValues));
    2.1.3 enumeration < string > getparameternames(): get parameter names of all requests
    Enumeration<String> parameterNames = request.getParameterNames();
            while (parameterNames.hasMoreElements()){
                System.out.println(request.getParameter(parameterNames.nextElement()));
            }
    2.1.4 map < string, string [] > getparametermap(): get the map set of all parameters
            Map<String, String[]> parameterMap = request.getParameterMap();
            Set<String> strings = parameterMap.keySet();
            for (String string : strings) {
                System.out.println(string);
            }
    Chinese code scrambling
     *get mode: tomcat8 has solved the problem of getting mode scrambling
     *post mode:
    *Before getting the parameters, set the code request.setCharacterEncoding("utf-8") of request to solve the problem of scrambling
    2.2 request forwarding: a way of resource jump within the server
    2.2.1 steps:
    2.2.1.1 get request forwarder object through request object: RequestDispatcher getRequestDispatcher(String path)
    2.2.1.2 use RequestDispatcher object to forward: forward(ServletRequest request,ServletResponse response)
    RequestDispatcher requestDispatcher = request.getRequestDispatcher("/requestdemo5");
    requestDispatcher.forward(request,response);
    // demo5 triggered
    2.2.2 features:
    Browser address bar path does not change
    Can only forward to internal resources of the current server
    Forwarding is just a request
    2.3 shared data
    2.3.1 domain object: an object with scope, which can share data within the scope
    2.3.2 request domain: represents the scope of a request, which is generally used to share data among multiple resources for request forwarding
    2.3.3 method:
    setAttribute(String name,Object obj): store data
    Object getAttribute(String name): get value through key
    Removeaattribute (string name): remove key value pair through key
    // demo4 
    request.setAttribute("msg","hello");
    RequestDispatcher requestDispatcher = request.getRequestDispatcher("/requestdemo5");
    requestDispatcher.forward(request,response);
    // demo5
    Object msg = request.getAttribute("msg");
    System.out.println(msg); // hello
    2.4 get ServletContext
    ServletContext getServletContext()
extend
  • BeanUtils tool class to simplify data encapsulation
    Used to encapsulate JavaBean s
  1. JavaBean: a standard Java class
    1.1 class must be decorated by public
    1.2 a constructor with empty parameters must be provided
    1.3 member variables must be decorated with private
    1.4 provide public setter and getter methods
  2. Concept:
    2.1 member variables:
    2.2 property: the product of intercepting setter and getter methods
  3. Method:
    setProperty()
    getProperty()
    populate(Object obj,Map map): encapsulate the key value pair information of the Map collection into the corresponding JavaBean object
Practice
  1. Login case

    Demand:
    1. Write login.html login page, password and username
     2. Use Druid database connection pool technology to operate mysql and user data table
     3. Using JdbcTemplate technology to encapsulate JDBC
     4. Log in successfully and jump to SuccessServlet display: log in successfully! User name, welcome
     5. Login failure jump to FailServlet display: login failure! Wrong user name or password
    <!-- login.html-->
    <form action="/day23_war_exploded/loginservlet" method="post">
        //User name:<input type="text" placeholder="enter one user name" name="username"><br>
        //Password:<input type="text" placeholder="Please input a password" name="password"><br>
        <input type="submit" value="Sign in">
    </form>
    // druid.properties
    driverClassName=com.mysql.jdbc.Driver
    url=jdbc:mysql:///day23
    username=root
    password=root
    initialSize=5
    maxActive=10
    maxWait=3000
    // jar package, put in the web info folder
    commons-logging-1.2.jar
    druid-1.0.9.jar
    jsoup-1.12.1.jar
    JsoupXpath-0.3.2.jar
    mchange-commons-java-0.2.12.jar
    mysql-connector-java-5.1.9.jar
    spring-beans-5.1.10.RELEASE.jar
    spring-core-5.1.10.RELEASE.jar
    spring-jdbc-5.1.10.RELEASE.jar
    spring-tx-5.1.10.RELEASE.jar
    // Create database day23 and table user
    CREATE DATABASE day23;
    USE day23
    CREATE TABLE USER(
    	id INT PRIMARY KEY AUTO_INCREMENT,
    	username VARCHAR(32) UNIQUE NOT NULL,
    	PASSWORD VARCHAR(32) NOT NULL
    )
    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 + '\'' +
                    '}';
        }
    }
    
    public class JDBCUtils {
        // JDBC tool class, using Druid's connection pool
        private static DataSource ds;
        static {
            try {
                // Load profile
                Properties properties = new Properties();
                // Use Classloader to load configuration file and get byte input stream
                InputStream resourceAsStream = JDBCUtils.class.
                        getClassLoader().getResourceAsStream("druid.properties");
                properties.load(resourceAsStream);
                // Initialize connection pool
                ds = DruidDataSourceFactory.createDataSource(properties);
            } catch (Exception e) {
                e.printStackTrace();
            }
    ds
        }
        // Get connection pool method
        public static DataSource getDataSource(){
            return ds;
        }
        // Get Connection method
        public static Connection getConnection() throws SQLException {
            return ds.getConnection();
        }
    }
    public class UserDao {
        // Declare JDBC template object sharing
        private JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
        // Class of user table in operation database
        public User login(User loginUser){
            try {
                // Writing sql
                String sql = "select * from user where username=? and password=?";
                // Call query method
                User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class),
                        loginUser.getUsername(), loginUser.getPassword());
                return user;
            }catch (Exception e){
                return null;
            }
        }
    }
    @WebServlet("/loginservlet")
    public class LoginServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doGet(request,response);
        }
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // Set encoding
            request.setCharacterEncoding("utf-8");
            /*
            // Get request parameters
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            // Encapsulating user objects
            User loginUser = new User();
            loginUser.setUsername(username);
            loginUser.setPassword(password);
             */
            // Get all request parameters
            Map<String, String[]> parameterMap = request.getParameterMap();
            // Create User object
            User loginUser = new User();
            // Using the bean utils package, you need to import the commons-bean utils-1.9.4.jar package
            try {
                BeanUtils.populate(loginUser,parameterMap);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            // Call the login method of UserDao
            UserDao dao=new UserDao();
            User user = dao.login(loginUser);
            // judge
            if(user==null){
                // Login failed
                // Forward
                request.getRequestDispatcher("/failservlet").forward(request,response);
            }else{
                // Login successfully
                request.setAttribute("user",user);
                request.getRequestDispatcher("/successservlet").forward(request,response);
            }
        }
    }
    @WebServlet("/failservlet")
    public class FailServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // Write a message to the page
            // Set encoding
            response.setContentType("text/html;charset=utf-8");
            // output
            response.getWriter().write("Login failed! Wrong user name or password");
        }
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doPost(request,response);
        }
    }
    @WebServlet("/successservlet")
    public class SuccessServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // Get the user object shared in the request domain
            User user = (User) request.getAttribute("user");
            // Write a message to the page
            // Set encoding
            response.setContentType("text/html;charset=utf-8");
            // output
            response.getWriter().write("Login succeeded!"+user.getUsername()+"Welcome");
        }
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doPost(request,response);
        }
    }
    
113 original articles published, praised 1, 865 visitors
Private letter follow

Tags: JDBC Druid Database MySQL

Posted on Mon, 10 Feb 2020 05:13:23 -0500 by gpittingale