Request
Get request data
I Request inheritance system
RequestFacade ------> HttpServletRequest ------> ServletRequest
ServletRequest: the root interface of the request object provided by Java
HttpServletRequest: the request object interface encapsulated by HTTP protocol provided by Java
RequestFacade: implementation class defined by Tomcat
-
Tomcat needs to parse the request data, encapsulate it as a request object, and create a request object to pass to the service method
-
Use the request object to consult the HttpServletRequest interface of the Java EE API document
II Request get request data
1. Get request data
01. Request line
GET /request-demo/req1?username=zhangsan HTTP/1.1
Method name | function | result |
---|---|---|
String getMethod() | Get request method | GET |
String getContextPath() | Get virtual directory (access path) | /request-demo |
StringBuffer getRequestURL() | Get URL (uniform resource locator) | http://localhost:8080/request-demo/req1 |
String getRequestURI() | Get URI (Uniform Resource Identifier) | /request-demo/req1 |
String getQueryString() | GET request parameters (GET method) | username=zhangsan&password= |
Case:
localhost:8080/web-demo01/req1?username=zhangsan&password=123
/** * Method: String getMethod() * Result: method = GET */ String method = req.getMethod(); System.out.println("method = " + method); /** * Method: String getContextPath() * Result: contextPath = /web-demo01 */ String contextPath = req.getContextPath(); System.out.println("contextPath = " + contextPath); /** * Method: StringBuffer getRequestURL() * Result: requesturl= http://localhost:8080/web -demo01/req1 */ StringBuffer requestURL = req.getRequestURL(); System.out.println("requestURL = " + requestURL); /** * Method: String getRequestURI() * Result: requestURI = /web-demo01/req1 */ String requestURI = req.getRequestURI(); System.out.println("requestURI = " + requestURI); /** * Method: String getQueryString() * Result: querystring = username = Zhangsan & password = 123 */ String queryString = req.getQueryString(); System.out.println("queryString = " + queryString);
02. Request header
User-Agent: Mozilla/5.0 Chrome/91.0.4472.106
method | function |
---|---|
String getHeader(String name) | Get the value according to the request header name |
/** * Get request header * user-agent: Browser version information * Result: header = Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36 Edg/101.0.1210.47 */ String header = req.getHeader("user-agent"); System.out.println("header = " + header);
03. Requestor
Only POST mode is available
username=superbaby&password=123
method | function |
---|---|
ServletInputStream getInputStream() | Get byte input stream |
BufferedReader getReader() | Get character input stream |
/** * Get post request body * Result: line = username = Zhangsan & password = 123 */ //1. Get character input stream BufferedReader br = req.getReader(); //2. Read data String line = br.readLine(); System.out.println("line = " + line);
2. Obtain request parameters in a general way
method | function |
---|---|
Map<String, String[ ]> getParameterMap() | Get all parameter Map collections |
String[ ] getParameterValues(String name) | Get parameter value (array) by name |
String getParameter(String name) | Get parameter value by name (single value) |
Just write one, regardless of whether it uses the GET or POST method
<form action="/web-demo01/req2" method="post"> <input type="text" name="username"><br> <input type="password" name="password"><br> <input type="checkbox" name="hobby" value="1">Swimming <input type="checkbox" name="hobby" value="2">Mountain climbing<br> <input type="submit"> </form>
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1. Get the map set of all parameters Map<String, String[]> map = req.getParameterMap(); for (String key : map.keySet()) { System.out.print(key+":"); String[] values = map.get(key); for (String value : values) { System.out.print(value+" "); } System.out.println(); } System.out.println("--------------------"); //2. Get the parameter value according to the key and the array String[] hobbies = req.getParameterValues("hobby"); for (String hobby : hobbies) { System.out.println(hobby); } //3. Obtain a single parameter value according to the key String username = req.getParameter("username"); String password = req.getParameter("password"); System.out.println("username = " + username); System.out.println("password = " + password); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); }
Console:
username:admin
password:123456
hobby:1 2
1
2
username = admin
password = 123456
3. Chinese garbled code of request parameters
01.POST mode
//Set POST mode garbled code request.setCharacterEncoding("UTF-8");
02.GET method
String username = request.getParameter("username"); String username1 = new String(username.getBytes("ISO-8859-1"),"UTF-8"); System.out.println("username1 = " + username1);
3, Request forwarding
A resource jump mode inside the server
Sender:
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("demo5"); request.setAttribute("msg","hello"); //Request forwarding request.getRequestDispatcher("/req6").forward(request,response); }
Receiving end:
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("demo6"); Object msg = request.getAttribute("msg"); System.out.println("msg = " + msg); }
**Implementation method: * * req Getrequestdispatcher ("resource B path") forward(request,response);
method | effect |
---|---|
void setAttribute(String name, Object o) | Store data in the request field |
Object getAttribute(String name) | Get the value according to the key |
void removeAttribute(String name) | l delete the key value pair according to the key |
Request forwarding features:
-
The browser address bar path does not change
-
It can only be forwarded to the internal resources of the current server
-
For one request, you can use request to share data among the forwarded resources
Response
Use the response object to set the response data
1, Response architecture
ResponseFacade ------> HttpServletResponse ------> ServletResponse
ServletResponse: the root interface of the request object provided by Java
HttpServletResponse: the request object encapsulated by the Http protocol provided by Java
ResponseFacade: implementation class defined by Tomcat
2, Response set response data function
The response data is divided into three parts
1. Response line:
HTTP/1.1 200 OK
method | function |
---|---|
void setStatus(int sc) | Set response status code |
2. Response head
Content-Type: text/html
method | function |
---|---|
void setHeader(String name, String value) | Set response header key value pair |
3. Responder
<html><head>head><body></body></html>
method | function |
---|---|
PrintWriter getWriter() | Get character output stream |
ServletOutputStream getOutputStream() | Get byte output stream |
3, Response complete redirection
A resource jump mode
Resource A said to the browser that I can't handle this. Find someone else (status code) to handle it. The person's location is XXX (response header location:xxx)
Implementation method:
resp.setStatus(302);
resp. Path of setheader ("set location");
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //redirect //1. Set the response status code 302 response.setStatus(302); //2. Set the response header Location response.setHeader("Location","/web-demo01//resp2"); }
Simplified implementation:
resp.sendRedirect("path of resource B");
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Simplify redirection response.sendRedirect("/web-demo01//resp2"); }
Redirection features:
-
The browser address bar path does not change
-
It can only be forwarded to the internal resources of the current server
-
For one request, you can use request to share data among the forwarded resources
Path resource problem
-
Specify who uses the path?
- Browser usage: need to add virtual directory
- Server use: no need to add virtual directory
-
Dynamic path:
String contextPath = request.getContextPath(); response.sendRedirect(contextPath + "/resp2");
4, Response response character data
- use
1. Get the character output stream through the Response object
PrintWriter writer = resp.getWriter();
2. Write data
writer.write("aaa");
-
details
1. The flow does not need to be closed. With the end of the response, the response object is destroyed and closed by the server
2. Chinese data garbled: Reason: the default code of the character output stream obtained through the Response is ISO-8859-1
resp.setContentType("text/html;charset=utf-8");
//It simplifies html parsing and character formatting response.setContentType("text/html;charset=utf-8"); //1. Get character output stream PrintWriter writer = response.getWriter(); //Content type setting html parsing //response.setHeader("content-type","text/html"); writer.write("<h1>Hello</h1>");
After opening, the web page is a h1 label with the word "hello"
5, Response response byte data
-
use
1. Get byte output stream through Response object
ServletOutputStream outputStream = resp.getOutputStream();
2. Write data
outputStream. Write (byte data);
- troublesome!!!
//1. Read the file FileInputStream fis = new FileInputStream("C:\\Users\\Liu Hao\\Desktop\\07.jpg"); //2. Get the response byte output stream ServletOutputStream os = response.getOutputStream(); //3. Complete the copy of the stream byte[] buff = new byte[1024]; int len = 0; while ((len = fis.read(buff)) != -1){ os.write(buff,0,len); } fis.close();
- IOUtils tool class
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency>
- After simplification
//1. Read the file FileInputStream fis = new FileInputStream("C:\\Users\\Liu Hao\\Desktop\\07.jpg"); //2. Get the response byte output stream ServletOutputStream os = response.getOutputStream(); //3. Complete the copy of the stream IOUtils.copy(fis,os); fis.close();
6, User login and registration function cases
UserMapper
public interface UserMapper { /** * Query user objects by user name and password * @param username * @param password * @return */ @Select("select * from tb_user where username = #{username} and password = #{password}") User select(@Param("username") String username, @Param("password") String password); /** * Query user object by user name * @param username * @return */ @Select("select * from tb_user where username = #{username}") User selectByUsername(@Param("username") String username); @Insert("insert into tb_user values(null,#{username},#{password})") void add(User user); }
RegisterServlet
@WebServlet("/registerServlet") public class RegisterServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. Accept user data String username = request.getParameter("username"); String password = request.getParameter("password"); //Encapsulate user objects User user = new User(); user.setUsername(username); user.setPassword(password); //2. Call mybatis to complete the query //2.1 get sqlSessionFactory object // String resource = "mybatis-config.xml"; // InputStream inputStream = Resources.getResourceAsStream(resource); // SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSessionFactory sqlSessionFactory = sqlSessionFactoryUtils.getSqlSessionFactory(); //2.2 get sqlSession object SqlSession sqlSession = sqlSessionFactory.openSession(); //2.3 get Mapper UserMapper userMapper = sqlSession.getMapper(UserMapper.class); //2.4 calling method User u = userMapper.selectByUsername(username); //3. Judge whether the user exists if (u == null){ //user name does not exist userMapper.add(user); //Commit transaction sqlSession.commit(); //Release resources sqlSession.close(); }else { //User name exists response.setContentType("text/html;charset=utf-8"); response.getWriter().write("User name already exists"); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
LoginServlet
@WebServlet("/loginServlet") public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. Accept user name and password String username = request.getParameter("username"); String password = request.getParameter("password"); //2. Call mybatis to complete the query //2.1 get sqlSessionFactory object // String resource = "mybatis-config.xml"; // InputStream inputStream = Resources.getResourceAsStream(resource); // SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSessionFactory sqlSessionFactory = sqlSessionFactoryUtils.getSqlSessionFactory(); //2.2 get sqlSession object SqlSession sqlSession = sqlSessionFactory.openSession(); //2.3 get Mapper UserMapper userMapper = sqlSession.getMapper(UserMapper.class); //2.4 calling method User user = userMapper.select(username, password); //2.5 releasing resources sqlSession.close(); //Get the character output stream and set the content type response.setContentType("text/html;charset=utf-8"); PrintWriter writer = response.getWriter(); //3. Judge whether user is null if (user != null){ writer.write("Login successful"); }else { writer.write("Login failed"); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
Interface
<form action="/web-demo01/loginServlet" id="form" method="post"> <h1 id="loginMsg">LOGIN IN</h1> <p>Username:<input id="username" name="username" type="text"></p> <p>Password:<input id="password" name="password" type="password"></p> <div id="subDiv"> <input type="submit" class="button" value="login up"> <input type="reset" class="button" value="reset"> <a href="register.html">No account? Click Register</a> </div> </form>
<body> <div class="form-div"> <div class="reg-content"> <h1>Welcome to register</h1> <span>Existing account?</span> <a href="login.html">Sign in</a> </div> <form id="reg-form" action="/web-demo01/registerServlet" method="post"> <table> <tr> <td>user name</td> <td class="inputs"> <input name="username" type="text" id="username"> <br> <span id="username_err" class="err_msg" style="display: none">User names are not very popular</span> </td> </tr> <tr> <td>password</td> <td class="inputs"> <input name="password" type="password" id="password"> <br> <span id="password_err" class="err_msg" style="display: none">Incorrect password format</span> </td> </tr> </table> <div class="buttons"> <input value="Register" type="submit" id="reg_btn"> </div> <br class="clear"> </form> </div> </body>
sqlSessionFactoryUtils optimization
public class sqlSessionFactoryUtils { private static SqlSessionFactory sqlSessionFactory; //Static code blocks are loaded only once static { try { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public static SqlSessionFactory getSqlSessionFactory(){ return sqlSessionFactory; } }
Call direct later
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryUtils.getSqlSessionFactory();