Servlet
concept step Principle of execution life cycle Servlet 3.0 annotation configuration The architecture of Servlet- GenericServlet: the default null implementation of other methods in the Servlet interface, only the service() method as an abstraction
- When defining a Servlet class in the future, you can inherit GenericServlet and implement the service() method
- HttpServlet: an encapsulation of http protocol to simplify operation
- Definition class inherits HttpServlet
- Copy doGet/doPost method (judge request method)
- GET on browser direct request
- urlpartten: Servlet access path
- A Servlet can define multiple access paths: @ webservlet ({'/ D4', '/ DD4', '/ ddd4'})
- Path definition rules
- /xxx: path matching
- /xxx/xxx: multi layer path, directory structure
- *. do: extension match
@WebServlet("/servletDemo") public class ServletDemo extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
HTTP
- Concept: Hyper Text Transfer Protocol
- Transmission protocol: the format of sending data when client and server communicate
characteristic
- Advanced protocol based on TCP/IP
- Default port number: 80
- Based on the request / response model: one request corresponds to one response
- Stateless: each request is independent of each other and cannot interact with data
Historical version
- 1.0: new connection will be established for each request response
- 1.1: multiplexing connection
Request message data format (request)
POST /login.html HTTP/1.1 Host: localhost User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;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 Referer: http://localhost/login.html Connection: keep-alive Upgrade-Insecure-Requests: 1 username=zhangsanRequest line
- Request mode request url request protocol / version
- GET /login.html HTTP/1.1
- Request mode (there are 7 request modes in HTTP protocol and 2 in common use)
- GET:
- The request parameter is in the request line, after the url.
- The requested url length is limited
- Not very safe
- POST:
- Request parameter in request body
- The requested url length is unlimited
- Relative safety
- GET:
-
Request header name: request header value
-
The client browser tells the server some information
-
Common request headers
- 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
- Referer: http://localhost/login.html
- Tell the server where the current request comes from
- Function: anti theft chain, statistical work
- User agent: the browser tells the server that I access the browser version information you are using
- A blank line is used to split the request header and body of a POST request
- That encapsulates the request parameters of the POST request message
Request
The principle of request object and response object
- The request object is to get the request message
- The response object is to set the response message
-
The tomcat server will create the corresponding ServletDemo object according to the resource path in the request url
-
The request and response objects are created by the server (the request message data is encapsulated in the request object). Let's use them
-
tomcat passes two objects, request and response, to the service method, and calls the service method
-
We can get the request message data through the request object and set the response message data through the response object
-
Before the server responds to the browser, it will take out the response message data we set from the response object
request object inheritance architecture
ServletRequest / interfaceHttpServletRequest / interfacerequest function
Get request message data Get request line data (method)- GET /day14/demo1?name=zhangsan HTTP/1.1
- GET: String getMethod()
- Get virtual directory (/ day): String getContextPath()
- Get Servlet path (/ demo1): String getServletPath()
- Get get method request parameter (name=zhangsan): String getQueryString()
- Get request URI
- String getRequestURI(): /day14/demo1
- StringBuffer getRequestURL(): http://localhost/day14/demo1
- URI (Uniform Resource Identifier): / day14/demo1
- URL (uniform resource locator): http://localhost/day14/demo1
- Get protocol and Version (HTTP/1.1): String getProtocol()
- Get the IP address of the client: String getRemoteAddr()
- Get the value of the request header by the name of the request header: String getHeader(String name)
- Get all request header names: enumeration < string > getheadernames()
// Get request header data @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get all request header names Enumeration<String> headerNames = request.getHeaderNames(); // ergodic While(headerNames.hasMoreElements()){ // Get the value of the request header by name String value = request.getHeader(name); System.out.println(name+":"+value); } // Get request header data: user agent String agent = request.getHeader("user-agent"); // Judge browser version of agent if(agent.contains("Chrome")){ // Google browser }else{ // Other browsers } }Get request body data (method)
- Request body: only POST request mode has a request body, which encapsulates the request parameters of POST request
- step
- Get stream object
- Get character input stream (only character data can be manipulated): BufferedReader getReader()
- Get byte input stream (all types of data can be manipulated): ServletInputStream getInputStream()
- Then take the data from the flow object
- Get stream object
<!--html in form Form's action Path writing: virtual directory+Servlet Resource path for--> <form action="demo/requestDemo" 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>
@WebServlet("/requestDemo") public class ServletDemo extends HttpServlet { // Get request message body (request parameter) @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get character stream BufferedReader br = request.getReader(); // Read data String line = null; while((line = br.readerLine())!=null){ System.out.println(line); // Output a line of user name and password information } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }Other functions General way to get request parameters
-
The following methods can be used to GET the request parameters in both GET and POST request modes
-
Get parameter value according to parameter name: String getParameter(String name)
String name1 = request.getParameter("username"); // Get the value of name1 for username according to the value of the tag name attribute
- username=zs&password=123
-
Get the array of parameter values according to the parameter name: String[] getParameterValues(String name)
String[] hobbies = request.getParameterValues("hobby"); for(String hobby : hobbies){ System.out.println(hobby); }
- hobby=football&hobby=game
-
Get parameter names of all requests: enumeration < string > getparameternames()
Enumeration<String> parameterNames = request.getParameterNames(); while(parameterNames.hasMoreElements()){ String name = parameterNames.nextElement(); System.out.println(name); // Parameter name requested String value = request.getParameter(name); System.out.println(value); // Get parameter value according to parameter name }
-
Get the map set of all parameters: Map < string, string [] > getparametermap()
Map<String,String[]> parameterMap = request.getParameterMap(); Set<String> keySet = parameterMap.keySet(); // Get key for(String name : keySet){ String[] values = parameterMap.get(name); // Get value from key System.out.println(name); for(String value : values){ System.out.println(value); } }
-
Chinese code scrambling:
- GET mode: tomcat 8 has solved the problem of getting mode scrambling
- POST mode: random code
- Solution: before obtaining parameters, set the code of request request.setCharacterEncoding("utf-8");
-
A way of resource jump inside the server
-
step
- Get the request forwarder object through the request object: RequestDispatcher getRequestDispatcher(String path)
- Use the RequestDispatcher object to forward: forward(ServletRequest request, ServletResponse response)
request.getRequestDispatcher("/requestDemo").forward(request, response);
-
matters needing attention
- Browser address bar path does not change
- Can only forward to internal resources of the current server
- Forwarding is a request
- Domain object: a scoped object that 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
- Store data: void setAttribute(String name,Object obj)
- Get value through key: object getattribute (string name)
- Remove key value pair by key: void removeaattribute (string name)
- ServletContext getServletContext()
BeanUtils tool class to simplify data encapsulation
For encapsulating JavaBean s
JavaBean: a standard Java class
requirement- Class must be public decorated
- Constructor of null parameter must be provided
- Member variables must be decorated with private
- Provide public setter and getter methods
concept
Member variable- Property: the result of intercepting setter and getter methods
- For example: getusername() -- > username – > username
method
- Setting: setProperty()
- Get: getProperty()
- Encapsulate the key value pair information of the map collection into the corresponding JavaBean object: populate (object obj, map map map)
User user = new User(); try{ BeanUtils.setProperty(user,"username","zhangsan"); // Save zhangsan's string into user's username Strign username = BeanUtils.getProperty(user,"username"); //Take the value of username }catch(IllegalAccessException e){ e.printStackTrace(); }catch(InvocationTargetException e){ e.printStackTrace(); }
HTTP protocol
Request message: data sent by client to server
-
data format
- Request line
- Request header
- Request blank line
- Requestor
Response message: data sent by the server to the client
data format Response line- Composition: Protocol / version response status code status code description
- Response status code (all status codes are three digits): the server tells the client
- 1xx: the server received the client message but did not accept the completion. After waiting for a period of time, 1xx status code will be sent
- 2xx: success. Two hundred
- 3xx: redirect.
- 302: redirection
- 304: access cache
- 4xx: client error
- 404: request path has no corresponding resource
- 405: there is no corresponding doXxx method for request mode
- 5xx: server side error. 500 (exception in the server)
- Format: header name: value
- Common response headers
- The server tells the client the data format and encoding format of the response body: content type
- The server tells the client in what format to open the response body data: content disposition
- In line: default value, open in the current page
- attachment;filename=xxx: open the response body as an attachment, and download the file
-
Response string format
HTTP/1.1 200 OK Content-Type: text/html;charset=UTF-8 Content-Length: 101 Date: Wed, 06 Jun 2018 07:08:42 GMT <html> <head> <title>$Title$</title> </head> <body> hello , response </body> </html>
Response object
Function: set response message
Set response line- Format: HTTP/1.1 200 ok
- Set status code: setStatus(int sc)
- setHeader(String name,String value)
- Get output stream
- Character output stream: PrintWriter getWriter()
- Byte output stream: ServletOutputStream getOutputStream()
- Output data to client browser using output stream
Redirection (how resources jump)
- a resource cannot be completed, b resource can be completed
- Tell browser to redirect: status code 302
- Tell browser b resource path: response header location: b resource path
// Accessing / responseDemo0 will automatically jump to / responseDemo //1. Set status code to 302 response.setStatus(302); //2. Set response header location response.setHeader("location","/day/responseDemo"); //A simple redefinition method response.sendRedirect("/day/responseDemo");Characteristics of redirection: redirect
- Address bar changed
- Redirect resources that can access other sites (servers)
- Redirection is two requests. Cannot use request object to share data
- Forwarding address bar path unchanged
- Forwarding can only access resources under the current server
- Forwarding is a request that can be shared using a request object
-
Relative path: a unique resource cannot be determined by relative path
- For example:/ index.html
- Path does not start with /
- Rule: find the relative position relationship between the current resource and the target resource
- . /: current directory
- .. /: back one level catalog
-
Absolute path: unique resources can be determined by absolute path
- For example: http://localhost/day/responseDemo
- day/responseDemo
- Path starting with /
- Rule: judge who uses the defined path? ->Determine where the request will come from in the future
- For client browser: need to add virtual directory (access path of project)
- It is recommended to obtain the virtual directory dynamically: request.getContextPath()
- <a>, < form > redirect
- For servers: no need to add virtual directory
- Forwarding path
- For client browser: need to add virtual directory (access path of project)
Server output character data to browser
step- Get character output stream
- output data
// Before getting the stream object, set the default encoding of the stream to utf-8 response.setCharacterEncoding("utf-8"); // Tell the browser the encoding of the message body data sent by the server. It is recommended that the browser use this encoding to decode // response.setHeader("content-type","text/html;charset=utf-8"); // Simplify to the following code response.setContentType("text/html;charset=utf-8"); // Get character output stream PrintWriter pw = response.getWriter(); // Automatically destroyed after a response // Output data to page pw.write("<h1>hello response</h1>");Pay attention to the confusion
- PrintWriter pw = response.getWriter();: the default encoding of the obtained stream is ISO-8859-1
- Set the default encoding for the stream
- Tell the browser the encoding used by the response body
- Simple form (set the encoding before getting the stream): response.setContentType("text/html;charset=utf-8");
Server output byte data to browser
step- Get character output stream
- output data
// Get byte output stream ServletOutputStream sos = response.getOutputStream(); // output data sos.write("hello".getBytes());
ServletContext object
concept
- It represents the whole web application and can communicate with the container (server) of the program
obtain
-
Get from the request object: request.getServletContext();
-
Get from HttpServlet: this.getServletContext();
ServletContext context1 = request.getServletContext(); ServletContext context2 = this.getServletContext(); // context1 == context2
function
-
Get MIME type
- MIME type: a file data type defined in the process of Internet communication
- Format: large type / small type text / HTML image / jpeg
- Get: String getMimeType(String file)
-
Domain objects: sharing data
- setAttribute(String name,Object value)
- getAttribute(String name)
- removeAttribute(String name)
- ServletContext object scope: all users all requested data
@WebServlet("/servletContextDemo1") public class ServletContextDemo1 extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get through HttpServlet ServletContext context = this.getServletContext(); // Set data context.setAttribute("msg","hello"); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } } @WebServlet("/servletContextDemo2") public class ServletContextDemo2 extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get through HttpServlet ServletContext context = this.getServletContext(); // get data Object msg = context.getAttribute("msg"); System.out.println(msg); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
- Method to get the real (server) path of the file: String getRealPath(String path)
@WebServlet("/servletContextDemo3") public class ServletContextDemo3 extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get through HttpServlet ServletContext context = this.getServletContext(); // Get the server path of the file String realPath = context.getRealPath("/b.txt");// Resource access under web Directory String realPath2 = context.getRealPath("/WEB-INF/c.txt");// Resource access under WEB-INF directory String realPath3 = context.getRealPath("/WEB-INF/classes/a.txt");//Resource access in src directory } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }