Servlet&HTTP&Request of Java learning notes

1, The architecture of Servlet

1.Servlet: Interface
2.GenericServlet: abstract class
The other methods in the Servlet interface are implemented by default, and only the servlet() method is abstracted.
When defining Servlet classes in the future, you can inherit GenericServlet and implement servlet() method.
3.HttpServlet: abstract class
It is a kind of encapsulation of http protocol to simplify the operation.
(1) Definition class inherits HTTPServlet;
(2) Copy the doGet/doPost method.
4.Servlet related configuration
urlpartten: Servlet access path
(1) A Servlet can define multiple access paths: @ webServlet({"/d4","/dd4","/ddd4"})
(2) Rules for definition of route:

  • /xxx: path matching
  • /xxx/xxx: multi level path, directory structure
  • *. do: extension match

2, HTTP concept

1. Concept: Hypertext Transfer Protocol
2. Transmission protocol: defined the format of sending data when client and server communicate.
3. characteristics:
(1) Advanced protocol based on TCP/IP;
(2) Default port number: 80;
(3) Based on the request / response model: one request corresponds to one response;
(4) Stateless: each request is independent of each other and cannot interact with data.

3, HTTP request message data format

1. request line
Request mode request url request protocol / version
GET /login.html HTTP/1.1

  • There are 7 request modes in HTTP protocol, and there are two common ones:
    (1)GET:
    The request parameter is in the request line, after the url;
    The requested url length is limited;
    Not very safe.
    (2)POST:
    The request parameter is in the request body;
    The requested url length is unlimited;
    Relatively safe.

2. Request header: the client browser tells the server some messages
Request header name: request header value
Common request headers:
(1) User agent: the browser tells the server that I access the browser version information you are using.
The information of the header can be obtained on the server side to solve the compatibility problem of the browser.
(2)Referer: http://localhost/login.html
Tell the server: where do I come from
Effect:
Anti-theft chain;
Statistical work.

3. Request blank line
A blank line is used to split the request header and the request body of a POST request.
4. Request body (body):
That encapsulates the request parameters of the POST request message.

4, The principle of request object and response object


1. The request and response objects are created by the server. Let's use them. 2. The request object is to get the request message, and the response object is to set the response message.

5, request object inheritance architecture

ServletRequest - Interface
Inherit
HttpServletRequest - Interface
Implementation
org.apache.catalina.connector.RequestFacade class (tomcat)

6, request function

1. Request line message data:
GET /day14/demo1?name=zhangsan HTTP/1.1
Method:
(1) GET request method: GET
String getMethod()
(2) Get virtual directory / day14
String getContextpath()
(3) Get Servlet path: / demo1
String getServletpath()
(4) Get get method request parameter: name = Zhang San
String getQueryString()
(5) Get request URI: / day14/demo1
String getRequestURI()
StringBuffer getRequestURL()
URI: Uniform Resource Locator
URL: Uniform Resource Identifier
(6) Get protocol version
String getRemoteAddr()
(7) Get the IP address of the client
String getRemoteAddr()
2. Get request header data
Method:
String getHeader(String name): get the value of the request header through the name of the request header;
Enumeration getHeader Names(): gets all request header names.
3. Get request body data:
Request body: only POST request mode can have a request body, which encapsulates the request parameters of POST request.
Steps:
(1) Get stream object
BufferdReader getReader(): get character input stream, only character data can be operated;
ServletInputStream getInputStream(): get byte input stream and operate all types of data;
(2) Then take the data from the flow object
4. Other functions:
General way to get the request parameters: the following methods can be used to get the request parameters no matter get or post request.
(1) String getParameter(String name): get the parameter value according to the parameter name;
(2) String[] getParameterValues(String name): get the array of parameter values according to the parameter name;
(3) Enumeration getParameterNames(): get the parameter names of all requests;
(4) Map < string, string [] > getparametermap(): get the map set of all parameters.

  • Chinese code scrambling:
    Get mode: tomcat 8 has solved the problem of get mode scrambling;
    post mode: before obtaining the parameters, set the encoding request.setCharacterEncoding("utf-8") of the request.

Request forwarding: a way of resource jump within the server

  • Steps:
    (1) Obtain the request forwarder object through the request object: RequestDispatcher;
    getRequestDispatcher(String path)
    (2) Use the RequestDispatcher object to forward: forward(ServletRequest request,ServletResponse response)
  • Characteristic:
    (1) Browser address bar path does not change;
    (2) It can only be forwarded to the internal resources of the current server;
    (3) Forwarding is a request.

Shared data:

  • Domain object: an object with scope, which can share data within the scope;
  • Request domain: represents the scope of a request, which is generally used to share data among multiple resources for request forwarding;
  • Method:
    (1) void setAttribute(String name,Object obj): store data;
    (2) Object getAttribute(String name): get the value through the key;
    (3) Void removeaattribute (string name): remove the key value pair through the key.

Get ServletContext:

  • ServletContext getServletContext()

7, How to write action path of form form in login.html

  • Resource path of virtual directory + Servlet

8, BeanUtils tool class to simplify data encapsulation

  • For encapsulating JavaBean s
    1.JavaBean: a standard Java class
    Requirement:
    (1) Class must be public decorated;
    (2) The constructor of empty parameter must be provided;
    (3) Member variables must be decorated with private;
    (4) Provide public setter and getter methods.
    Function: encapsulate data.
    2. concept:
    Member variable:
    Property: the intercepted product of setter and getter methods.
    For example: getusername() -- > username -- > username
    3. method:
    (1)setProperty();
    (2)getProperty();
    (3) populate(Object obj, Map map): encapsulate the key value pair information of the map collection into the corresponding JavaBean object.

9, Login case

Case requirements:
1. Write login.html login page
Two input fields: username & password;
2. Use Druid database connection pool technology to operate mysql and user table in day14 database;
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 jumps to FailServlet display: login failure, user name or password error;
Development steps:

1. Create project, import html page, configuration file, jar package
2. Create database environment

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
);

3. Create package cn.itcast.domain and create User class

package cn.itcast.domain;
		/**
		 * User's entity class
		 */
		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 + '\'' +
		                '}';
		    }
		}

4. Create package cn.itcast.util and write tool class JDBC utils

package cn.itcast.util;

		import com.alibaba.druid.pool.DruidDataSourceFactory;
		
		import javax.sql.DataSource;
		import javax.xml.crypto.Data;
		import java.io.IOException;
		import java.io.InputStream;
		import java.sql.Connection;
		import java.sql.SQLException;
		import java.util.Properties;
		
		/**
		 * JDBC Tool class uses Durid connection pool
		 */
		public class JDBCUtils {
		
		    private static DataSource ds ;
		
		    static {
		
		        try {
		            //1. Load configuration file
		            Properties pro = new Properties();
		            //Use ClassLoader to load configuration file and get byte input stream
		            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
		            pro.load(is);
		
		            //2. Initialize connection pool object
		            ds = DruidDataSourceFactory.createDataSource(pro);
		
		        } catch (IOException e) {
		            e.printStackTrace();
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
		    }
		
		    /**
		     * Get connection pool object
		     */
		    public static DataSource getDataSource(){
		        return ds;
		    }
		     /**
		     * Get Connection object
		     */
		    public static Connection getConnection() throws SQLException {
		        return  ds.getConnection();
		    }
		}

5. Create package cn.itcast.dao, create class UserDao, and provide login method

package cn.itcast.dao;

		import cn.itcast.domain.User;
		import cn.itcast.util.JDBCUtils;
		import org.springframework.dao.DataAccessException;
		import org.springframework.jdbc.core.BeanPropertyRowMapper;
		import org.springframework.jdbc.core.JdbcTemplate;
		
		/**
		 * Class of User table in operation database
		 */
		public class UserDao {
		
		    //Declare JDBC template object sharing
		    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
		
		    /**
		     * Login method
		     * @param loginUser Only user name and password
		     * @return user Contains all user data, no query found, return null
		     */
		    public User login(User loginUser){
		        try {
		            //1. writing sql
		            String sql = "select * from user where username = ? and password = ?";
		            //2. Call query method
		            User user = template.queryForObject(sql,
		                    new BeanPropertyRowMapper<User>(User.class),
		                    loginUser.getUsername(), loginUser.getPassword());
		      		            return user;
		        } catch (DataAccessException e) {
		            e.printStackTrace();//Log
		            return null;
		        }
		    }
		}
	              

6. Write cn.itcast.web.servlet.LoginServlet class

package cn.itcast.web.servlet;

		import cn.itcast.dao.UserDao;
		import cn.itcast.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("/loginServlet")
		public class LoginServlet extends HttpServlet {
		@Override
		    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		        //1. Set code
		        req.setCharacterEncoding("utf-8");
		        //2. Get request parameters
		        String username = req.getParameter("username");
		        String password = req.getParameter("password");
		        //3. Encapsulate user object
		        User loginUser = new User();
		        loginUser.setUsername(username);
		        loginUser.setPassword(password);
		
		        //4. Call the login method of UserDao
		        UserDao dao = new UserDao();
		        User user = dao.login(loginUser);
		
		        //5. judge user
		        if(user == null){
		            //Login failed
		            req.getRequestDispatcher("/failServlet").forward(req,resp);
		        }else{
		            //Login successfully
		            //Store data
		            req.setAttribute("user",user);
		            //Forward
		            req.getRequestDispatcher("/successServlet").forward(req,resp);
		        }
		
		    }
		
		    @Override
		    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		        this.doGet(req,resp);
		    }
		}

7. Write FailServlet and SuccessServlet classes

@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");
		
		        if(user != null){
		            //Write a sentence to the page
		
		            //Set encoding
		            response.setContentType("text/html;charset=utf-8");
		            //output
		            response.getWriter().write("Login succeeded!"+user.getUsername()+",Welcome");
		        }
		         }		
		         @WebServlet("/failServlet")
		public class FailServlet extends HttpServlet {
		    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		        //Write a sentence 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);
		    }
		}
19 original articles published, 10 praised, 1710 visited
Private letter follow

Tags: Java JDBC SQL Database

Posted on Sat, 15 Feb 2020 01:15:07 -0800 by lawnninja