HTTP Hypertext Transfer Protocol
Concept: Hyper Text Tranfer Protocol
- Transmission protocol: it defines that the communication between client and server is the format of sending data
- characteristic:
- Advanced protocol based on TCP/IP
- Default port number: 80
- Based on request / response model: one request corresponds to one response
- Stateless: each request is independent of each other and cannot interact with data
- Historical version:
- Each request response establishes a new connection
- Multiplex connection
Request message data format
-
Request line
-
Request mode request url request protocol / version
-
GET/login.html HTTP/1.1
-
Request method:
- There are seven request modes in HTTP protocol, and two are commonly used
- GET:
- The request parameters are in the request line, after the url
- The length of the requested url is limited
- Not very safe
- POST:
- The request parameter is in the request body
- There is no limit on the length of the requested url
- Relative safety
- GET:
- There are seven request modes in HTTP protocol, and two are commonly used
-
-
Request header: the client browser tells the server some information
- Request header name: request header value
- Common request headers:
- User agent: the browser tells the server that I can access the version information of the browser you use
- The header information can be obtained on the server side to solve the compatibility problem of the browser
- Referer: http://localhost:8080/MyApps/login.html
- Tell the server where I (current request) come from
- effect:
- Anti theft chain
- Statistics
- effect:
- Tell the server where I (current request) come from
- User agent: the browser tells the server that I can access the version information of the browser you use
-
Request blank line
- Blank line: used to split the request header and body of the POST request.
-
Request body (body)
- Encapsulates the request parameters of the POST request message
-
String format:
POST /MyApps/ser03 HTTP/1.1 Host: localhost:8080 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:95.0) Gecko/20100101 Firefox/95.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8 Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2 Accept-Encoding: gzip, deflate Content-Type: application/x-www-form-urlencoded Content-Length: 12 Origin: http://localhost:8080 Connection: keep-alive Referer: http://localhost:8080/MyApps/login.html Cookie: Idea-4311a65=5ac6d3b1-7c53-43e0-b438-60c6c2dbe879 Upgrade-Insecure-Requests: 1 Sec-Fetch-Dest: document Sec-Fetch-Mode: navigate Sec-Fetch-Site: same-origin Sec-Fetch-User: ?1 USERNAME=ads
Response message data format
Request
-
Principle of request object and response object
- The request and response objects are created by the server. Let's use them
- The request object is used to get the request message, and the response object is used to set the response message
-
request object inheritance architecture
- ServletRequest - Interface
- Succession
- HttpServletRequest - Interface
- | realization
- org.apache.catalina.connector.CoyoteInputStream class (Tomcat)
-
request:
-
Get request message data
-
Get request line data
- GET /MyApps/demo01?name=qin HTTP/1.1
- method:
- GET request method: GET
- String getMethod()
- Get virtual directory: / MyApps
- String getContextPath()
- Get Servlet path: / demo1
- String getServletPath()
- Get request parameters of get method: name=qin
- String getQueryString()
- Get requested uri: / MyApps/demo1
- String getRequestURI():/MyApps/demo1
- StringBuffer getRequestURL():http://localhost/MyApps/demo1
- URL: uniform resource locator: http://localhost/MyApps/demo1
- URI: uniform resource identifier (wider range): / MyApps/demo1
- Get protocol and version HTTP/1.1
- String getProtocol()
- Gets the IP address of the client
- String getRemoteAddr()
- GET request method: GET
-
Get request header data
- method:
- String getHeader(String name): get the value of the request header through the name of the request header
- Enumeration < string > getheadernames(): get all request header names
- method:
-
Get request body data
-
Request body: only the POST request method can have a request body. The request parameters of the POST request are encapsulated in the request body
-
Steps:
-
Get stream object
-
BufferedReader getReader(): gets the character input stream. Only character data can be manipulated
-
ServletInputStream getInputStream(): get byte input stream, which can operate on all types of data
-
regist.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>register</title> </head> <body> <form action="rd5" method="post"> <input type="text" placeholder="enter one user name" name="username"> <input type="text" placeholder="Please input a password" name="password"><br> <input type="submit" value="submit"> </form> </body> </html>
-
RequestDemo5
package com.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("/rd5") public class RequestDemo05 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Get request message body -- request parameters //1. Get character stream BufferedReader br = request.getReader(); //2. Read data String line = null; while ((line = br.readLine())!=null){ System.out.println(line); } } }
-
-
Then get the data from the stream object
-
-
-
-
Other functions
-
General method for obtaining request parameters (whether GET or POST):
-
String getParameter(String name): get the parameter value according to the parameter name username = Qin & password = 123
-
String getParameterValues(String name): get the array of parameter values according to the parameter name: Hobby = XX & Hobby = game
-
Enumeration < string > getparameternames(): get the parameter names of all requests
-
Map < string, string [] > getparametermap(): get the map set of all parameters
-
Chinese garbled code problem
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //post get request parameters // Get parameter value according to parameter name //1. Set the code of the request request.setCharacterEncoding("UTF-8"); String username = request.getParameter("username"); System.out.println(username); try { response.setCharacterEncoding("GBK"); } catch (Exception e) { e.printStackTrace(); } response.getWriter().write(username); } }
-
Get mode: Tomcat 8 has solved the problem of garbled code in get mode
-
post mode: garbled code
-
Solution: set the encoding of the request before getting the parameters
//1. Set the code of the request request.setCharacterEncoding("UTF-8");
-
-
-
-
Request forwarding: a resource jump mode within the server
- Steps:
- Get the request forwarder object through the request object: RequestDispatcher getRequestDispatcher(String path)
- Use the RequestDispatcher object for forwarding: RequestDispatcher forward(ServletRequest request,ServletResponse response)
- characteristic:
- The browser address bar path has not changed
- You can only access resources forwarded to the current server
- Forwarding is also a request
- Steps:
-
Shared data:
- Domain object: an object with scope that can share data within the scope
- Request field: represents the scope of a request. It is generally used to share data among multiple resources requesting forwarding
- method:
- setAttribute(String name,Object obj): stores data
- Getattribute (string name): get the value through the key
- void removeAttribute(String name): remove key value pairs through keys
-
Get ServletContext:
- ServletContext getServletContext()
-
-
Small case: user login
-
User login case requirements:
- Write login HTML login page
- Username & password two input boxes
- Use Druid database connection pool technology to operate the user table in mysql and day14 database
- Encapsulate JDBC using JDBC template technology
- Login succeeded, jump to the SuccessServlet display: login succeeded!
- Login failure, jump to FailServlet display: login failure, wrong user name or password
- Write login HTML login page
-
analysis
-
Development steps:
-
Create project, import html page, configuration file, jar package
-
Create database environment
create database day14; use day14; create table User( id int primary key auto_increment not null, username varchar(32), pwd varchar(32) )
-
Create package CN Domain, create User class
package cn.domain; /** * User's entity class */ public class User { private String id; private String username; private String password; public String getId() { return id; } public void setId(String 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 + '\'' + '}'; } }
-
Create package CN OP, create UserOp,
package cn.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 The utility class uses the Durid connection pool */ public class JDBCUtils { private static DataSource ds; static { try { //1. Load configuration file Properties pro = new Properties(); //Use ClassLoader to load the configuration file and obtain the bytecode input stream InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druif.properties"); pro.load(is);//Bytecode input //2. Initialize the 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 getConnectyion() throws SQLException { return ds.getConnection(); } }
-
Create package CN OP, create the class UserOp, and provide the login method
package cn.op; import cn.domain.User; import cn.util.JDBCUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; /** * Class that operates on the User table in the database */ public class UserOp { //Declare the JDBC template object for sharing private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); /** * Login method * @param loginUser Only user name and password * @return Include all user data */ public User login(User loginUser){ try { //1. Write sql String sql = "select * from user where username = ? and pwd = ?;"; //2. Call query method User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), loginUser.getUsername(), loginUser.getPwd()); return user; } catch (DataAccessException e) { e.printStackTrace();//Log } return null; } }
-
Write CN web. servlet. Loginservlet class
package cn.myweb.servlet; import cn.domain.User; import cn.op.UserOp; 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 { try { //1. Set code req.setCharacterEncoding("utf-8"); //2. Get request parameters String u = req.getParameter("username"); String p = req.getParameter("password"); //3. Encapsulate User objects User logier = new User(); logier.setUsername(u); logier.setPwd(p); //Call the login method of UserOp System.out.println(logier); System.out.println("To enter"); UserOp op = new UserOp(); System.out.println("After entering"); User user = op.login(logier); //5. Judgment if(user==null){ //Login failed req.getRequestDispatcher("/failServlet").forward(req,resp); }else{ //Login succeeded //Store data req.setAttribute("user",user); //Forward / redirect req.getRequestDispatcher("/successServlet").forward(req,resp); } } catch (ServletException | IOException e) { e.printStackTrace(); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req,resp); } }
-
login. How to write the action path of form in HTML
-
Resource path of virtual directory + Servlet
-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Sign in</title> </head> <body> <form action="/day14_2/loginServlet" method="post"> <input type="text" name="username"> <input type="password" name="pwd"> <input type="submit" value="submit"> </form> <!-- <a href="rd4">lianjie</a>--> </body> </html>
-
-
BeanUtils tool class to complete data encapsulation
-
For encapsulating JavaBean s
-
JavaBean s: standard java classes
- requirement:
- Class must be public decorated
- Constructor that must provide null arguments
- Member variables must be decorated with private
- Provide public setter and getter methods
- Function: encapsulate data
- requirement:
-
Concept:
- Member variables:
- Property: the product intercepted by setter and getter methods
- For example: getusername() -- > username -- > username
-
method:
-
setProperty()
-
getProperty()
-
populate(Object obj,Map map): encapsulates the key value pair information of the map set into the corresponding JavaBean object
package cn.myweb.servlet; import cn.domain.User; import cn.op.UserOp; import com.mchange.v2.beans.BeansUtils; import com.mchange.v2.codegen.bean.BeangenUtils; 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 { try { //1. Set code req.setCharacterEncoding("utf-8"); // //2. Get request parameters // String u = req.getParameter("username"); // String p = req.getParameter("password"); // //3. Encapsulating User objects // User logier = new User(); // logier.setUsername(u); // logier.setPwd(p); //2. Get all request parameters Map<String, String[]> map = req.getParameterMap(); //3. Create User object System.out.println("mima---"+map.get("password")[0]);; User loginer = new User(); //3.2 using BeanUtils encapsulation try { BeanUtils.populate(loginer,map);//Remember to use Apache's, otherwise an error will be reported, and the data in the map will be encapsulated in the User } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } //Call the login method of UserOp System.out.println(loginer); System.out.println("To enter"); UserOp op = new UserOp(); System.out.println("After entering"); User user = op.login(loginer); //5. Judgment if(user==null){ //Login failed req.getRequestDispatcher("/failServlet").forward(req,resp); }else{ //Login succeeded //Store data req.setAttribute("user",user); //Forward / redirect req.getRequestDispatcher("/successServlet").forward(req,resp); } } catch (ServletException | IOException e) { e.printStackTrace(); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req,resp); } }
-
-
-
-
("user",user);
//Forward / redirect
req.getRequestDispatcher("/successServlet").forward(req,resp);
}
} catch (ServletException | IOException e) {
e.printStackTrace();
}
} @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req,resp); } } ```