Servlet learning notes

Three configuration modes of Servlet Mode 1: precise configuration Must be in exact path, plus / SOS to access For exa...
Three configuration modes of Servlet
Servlet creation in the server is a single example
Servlet life cycle
The difference between doget, dopost and service
Summary of Servlet common exceptions
Introduction and features of HTTP servlet request
Request gets request line data and request header data according to key name
Set response line and set response header
Trouble shooting
Introduction to request forwarding
The function and characteristics of redirection
Introduction, characteristics and functions of cookies
Session
Introduction and acquisition of ServletContext object

Three configuration modes of Servlet

Mode 1: precise configuration

Must be in exact path, plus / SOS to access
For example: http://localhost:8080/ServletProject/SOS

<url-pattern>/SOS</url-pattern>

Mode 2: fuzzy configuration

As long as it ends with. do, you can access
For example: http://localhost:8080/ServletProject/a.do
For example: http://localhost:8080/ServletProject/b.do
Yes, the suffix is not. do,. P.o.k

<url-pattern>*.do</url-pattern>

Mode 3: block all requests

You can access this Servlet no matter what you enter

For example: http://localhost:8080/ServletProject (nothing later)

For example: http://localhost:8080/ServletProject/alvin is great

<url-pattern>/*</url-pattern>

A Servlet can be configured with multiple URL patterns

Different servlets are not allowed to configure the same URL pattern. If configured, an error will be reported when the server starts

When the server starts, the web.xml File load memory

Servlet creation in the server is a single example

After receiving the browser request, the server will open up a thread to process the request and call the corresponding Servlet in the thread to process it.

The server calls the Servlet to process the request, but a Servlet server only creates an instantiated object, which is shared by threads.

Servlet life cycle

@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("servlet Executed"); } //init will be called at the beginning, but it will only be called once before and after, and then only service will be run @Override public void init() throws ServletException { System.out.println("I was initialized"); } //Method executed after the server is shut down, similar to C + + destructor @Override public void destroy() { System.out.println("I was destroyed"); }

Servlet life cycle:

Conclusion:

From first call to server shutdown

verification:

init method: called when the servlet is initialized and created

service method: when processing a request

Destory method: when the servlet is destroyed, destroy the servlet when the server is shut down, and trigger the execution of destory method

Configure servlet server start to finish loading and initialization creation

<load-on-startup>1</load-on-startup>

We can web.xml Load on startup is configured in to set the servlet load time to server startup.

The lifecycle changes from server on to server off

The difference between doget, dopost and service

Create landing page

<html> <head> <title>Landing page</title> </head> <body> <form action="http://localhost:8080/ServletProject/SOS" method="get"> //Sign in:<input type="text" id="username" name="username"/><br/> //password:<input type="password" id="pwd" name="pwd"/><br/> <input type="submit" value="Sign in"/> </form> </body> </html>

When method = get, it is handled by doget

When method = post, it is handled by dopost

405 error will be reported if the request mode of method does not match with doget or dopost

When the servlet has no life service, it will be selected according to the requirements. If the service and doget or dopost exist at the same time, the service will be processed first

Summary of Servlet common exceptions

404 error: resource not found

Reason 1: the alias of the servlet in the request address is not written correctly.

Reason 2: misspelling of virtual project name

500 error: internal server error

Error 1:

​ ClassNotFoundException

Solve:

At web.xml To verify whether the full path of servlet class is misspelled.

Error 2:

Caused by code execution error of service method body

Solution:

Make error changes to the code in the service method body according to the error prompts.

405 error: request mode not supported

Reason:

Caused by a mismatch between the request method and the method in the servlet.

Solution:

Try to use the service method to handle the request, and do not call the service of the parent class in the service method.

Introduction and features of HTTP servlet request

request object

After receiving the request, the server will create a request object for the request, which holds the data related to the request

Role: store request data

Note: each request creates a new request object to store the request data

characteristic:

request object created by server

Create one request object at a time

The life cycle is within one request, and the request object will be destroyed at the end of the request

Request gets request line data and request header data according to key name

//Get request information //Get request line information //Get request method String method = req.getMethod(); System.out.println("Request method:"+method); //Get request URL information StringBuffer requestURL = req.getRequestURL(); System.out.println("request URL:"+requestURL.toString()); //Get request URI information String requestURI = req.getRequestURI(); System.out.println("request URI:"+requestURI); //Get request data in get request URL String queryString = req.getQueryString(); System.out.println("obtain get request URL Data in:"+queryString); //Get agreement String scheme = req.getScheme(); System.out.println("Get request protocol:"+scheme); //Get request header information //Get request header information according to key name String header = req.getHeader("User-Agent2"); System.out.println("Get browser version information:"+header); //Get enumeration of key names in the request header Enumeration headerNames = req.getHeaderNames(); while(headerNames.hasMoreElements()){ //Get request header key name String name=(String) headerNames.nextElement(); //Get the value corresponding to the key name of the request header String value=req.getHeader(name); System.out.println(name+":"+value); } //Get request entity data (user data) //Get data by key name String uname = req.getParameter("uname2"); String pwd=req.getParameter("pwd"); System.out.println("Request entity data:"+uname+":"+pwd); //Get entity data with the same name and different values String[] favs = req.getParameterValues("fav"); if(favs!=null){ for(String s:favs){ System.out.println("fav The value of is:"+s); } } //Get enumeration of key names in request entity Enumeration names = req.getParameterNames(); while(names.hasMoreElements()){ //Get key name String name=(String) names.nextElement(); //judge if("fav".equals(name)){ String[] favs2=req.getParameterValues(name); if(favs!=null){ for(String s:favs2){ System.out.println(name+":"+s); } } }else{ //Get value String value=req.getParameter(name); System.out.println(name+":"+value); } } //Request related network data //Get client information String remoteAddr = req.getRemoteAddr(); System.out.println("Get client's IP:"+remoteAddr); //Get the port number of the client (browser) int remotePort = req.getRemotePort(); System.out.println("Get the port number of the client:"+remotePort); //Get server host ip String localAddr = req.getLocalAddr(); System.out.println("Get server ip:"+localAddr); //Get the port number of the server int localPort=req.getLocalPort(); System.out.println("Get server port number:"+localPort); //Process request information //Response processing results }

Acquisition request data of request object learning

Request data: Request line: request method request URL protocol

getMethod(); return request method

getRequestUrl(); return request url

getRequestUri(); return request uri

getQueryString(); returns the user data in the URL in the get request note: this method is not in the post request.

getSchema(); return protocol

Request header

getHeader(String name) gets the request header information according to the key name

Note: if the obtained request header information does not exist, return null

getHeaderNames() returns an enumeration collection of request header key names stored

Requesting entity

getParameter(String name) gets data according to the key name

Note:

The key name is actually the value of the name attribute of the form label in the front-end page or the name of other key submitting data in the front-end page

If there is no corresponding request data in the request, Null is returned

getParameterValues(String name) gets different values with the same name according to the key name, and returns an array

Note: if there is no corresponding key name, null will be returned

getParameterNames() returns the enumeration of key names in entity data

Request network related data

getRemoteAddr() gets the IP address of the client

getRemotePort() get client port number

getLocalAddr() get server ip

getLocalPort() gets the port number of the server side

Set response line and set response header

protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Get request data //Processing request data //Response processing results //Set response line //Custom response 404 exception //resp.sendError(404); //Set response header //Add response header information resp.addHeader("mouse","thinkpad"); resp.addHeader("mouse","thinkpad2"); //Set response header //resp.setHeader("mouse", "two fly birds"); //resp.setHeader("mouse", "two fly birds2"); //Set response entity resp.getWriter().write("resp object"); resp.getWriter().write("resp object"); resp.getWriter().write("resp object"); resp.getWriter().write("resp object"); }

Response object processing response learning:

Set response line: protocol status code status message

​ response.sendError(int status);

Function: can respond to the browser autonomously

Set response header

addHeader(String name,String value) adds response header information. The data with the same name will not overwrite the response header information set by setHeader(String nanme,String value), but will overwrite the original information. If there is no response header, add the information.

Set response entity (processing result)

​ resp.getWriter().write("entity content");

Note:

Entity content can respond separately.

Note:

Once the resp object is used to respond to the request, it means that the request has been processed. The server will destroy the req object and resp object related to this request after responding.

Trouble shooting

The post request mode is garbled:

​ req.setCharacterEncoding("utf-8");

get request method scrambling solution:

Mode 1: each data should be transformed separately

​ String uname=req.getParameter("uname");

​ String uname2=new String(uname.getBytes("iso-8859-1"), "utf-8");

Mode 2:

​ req.setCharacterEncoding("utf-8");

At tomcat server.xml Attribute added to Connector tag in file: useBodyEncodingForURI = "true"

Response garbled problem: server response data displayed in browser garbled

​ resp.setContentType("text/html;charset=utf-8");

Servlet code writing process

protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Format request encoding req.setCharacterEncoding("utf-8"); //Format response encoding //resp.setHeader("content-type", "text/html;charset=utf-8"); resp.setContentType("text/html;charset=utf-8"); //Get request data String uname=req.getParameter("uname"); //String uname2=new String(uname.getBytes("iso-8859-1"), "utf-8"); //Processing request data System.out.println(uname); //Response processing results resp.getWriter().write("Request processed."); }

Introduction to request forwarding

Landing simulation

<html> <head> <meta charset="UTF-8"> <script src="js/jquery-3.4.1.min.js"></script> </head> <body> <script type="text/javascript" charset="UTF-8"> alert("hello"); </script> <form action="http://localhost:8080/ServletProject/SOS" method="get"> <p>Please enter the administrator account password!</p><br/> Sign in:<input type="text" id="username" name="username"/><br/> password:<input type="password" id="pwd" name="pwd"/><br/> <input type="submit" value="Sign in"/> </form> </body> </html>
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Format request encoding request.setCharacterEncoding("utf-8"); //Format response encoding response.setContentType("text/html;charset=utf-8"); //Get request information String username = request.getParameter("username"); String pwd = request.getParameter("pwd"); //Receive database information Student stu = SqlService.Login(username,pwd); //Process request information if(stu != null && stu.getClassname().equals("administrators")){ response.getWriter().write("Login succeeded!Welcome: " + stu.getRealname()); }else{ response.getWriter().write("You are not an administrator!"); } }

The function and characteristics of redirection

1. How to realize jump (client controlled jump mode)

Method 1: click hyperlink

Method 2: submit the form

Changes in the final address will be reflected in the address bar

Both are a new request to the server

2. How does the program realize jump (server-side control jump mode)

Mode 1: forward

Mode 2: redirect

Mode 3: include (can be ignored)

3. Common points of forwarding and redirection

The server-side control of the jump mode has realized the jump

4. Differences between forwarding and redirection

1) Different statements

Forward: request.getRequestDispatcher("/login/login.jsp").forward(request, response);

Redirect: response.sendRedirect("/myservlet2/login/success.jsp "";

2) The path of address bar is different after jump

Forward: address before jump

Redirect: address after jump / login/success.jsp

3) Can I get the data saved in the request

Forwarding: available

Redirect: unable to get

4) The principle is different!!! 5) Different efficiency

High forwarding efficiency

Inefficient redirection

6) Jump range is different

Forward: only the current project jump (the largest is the current server)

Redirection: can jump to any place on the Internet

The jump path is different Absolute path

Forward: not supported (jump only in the current project http://www.alvin.com)

Redirection: support

Root path/

Forward: no need to write context path / login/ login.jsp (jump only in the current project)

Redirection: need some context path / myservlet/login/success.jsp

/ represents the current server

Relative path

Only relative path 1 (the current file itself) does not have relative path 2 (the base path)

Path selection

1. Redirect to other servers, only absolute path can be used

2. Jump to other projects or current projects of the current server. It is recommended to use the root path

3. Relative path is not recommended

8) Root path has different / meaning

Forward / for current project

Redirect: / represents the current server

9) Whether refresh causes the form to be submitted repeatedly

Redirection: no

Forward: Yes

10) Whether it passes through the filter

Forward: no pass

Redirection: by

Is forwarding or redirection used? In some cases, there is no choice

You want the front and back components to share request data and use forward

Only forwarding can be used to jump to the WEB-INF directory of the same application

Only redirection can be used to jump to different applications

Using cookies to store data requires redirection

Which is the better way to jump to the same application?

Use forwarding with high efficiency, try to use forwarding as much as possible

Using forwarding needs to solve the problem of repeated submission, especially adding operations

Redirection is usually used after logout

Redirection is recommended between consecutive form pages to avoid property conflicts

Introduction, characteristics and functions of cookies

characteristic:

Data storage technology on browser side

What data needs to be stored on the server side

Line declaration:

It tells the browser to store in a responsive manner, which is not suitable for storing a large amount of data

effect:

Solve the problem of data sharing between different requests

Create Cookie data
Cookie cookie = new Cookie("b",b);
Source code of Cookie construction method
public Cookie(String name, String value) { validation.validate(name); this.name = name; this.value = value; }
Set Cookie information
//Set three-day validity period cookie.setMaxAge(3600 * 24 * 3);

Session

A

//Format request encoding request.setCharacterEncoding("utf-8"); //Format response encoding response.setContentType("text/html;charset=utf-8"); //Get request information String uname=request.getParameter("username"); //Processing request data System.out.println("ServletA.service(): "+uname); //Create Session object HttpSession session = request.getSession(); //Store data in session object session.setAttribute("uname", uname); System.out.println("ServletA.service(): "+session.getId()); //Response processing results

B

//Format request encoding request.setCharacterEncoding("utf-8"); //Format response encoding response.setContentType("text/html;charset=utf-8"); //Get request information //Get Session object HttpSession session = request.getSession(); //Get processing result data of A String uname=(String) session.getAttribute("username"); //Processing request data //Print the data of A flow System.out.println("ServletB.service():"+uname);

Question:

What should I do when I need to use the data in other requests for different requests

solve:

session Technology

use:

Create session object

​ HttpSession session = request.getSession();

Store data in session

​ session.setAttribute(String name,Object value);

Get session object

​ HttpSession session = request.getSession();

Get data in session

session,getAttribute(String uname); / / note that the returned object type needs to be cast

Delete data in session

​ session.removeAttribute(String name); note: if there is data, delete it; if there is no data, do nothing.

technological process:

Browser initiates request to Servlet1, which is used in Servlet1 request.getSession() get the session object. If there is no SessionID in this request, create a new session object. If there is a SessionID, return its corresponding session object (provided that the session object is not destroyed before the expiration of the object, even if there is a SessionID, a session will be recreated)

Verify whether the session fails, store the data in the session object, obtain the data in the session or delete the data in the session: session solves the data sharing problem of different requests of the same user.

characteristic:

session solves the problem of data sharing for different requests of the same user.

Optimize login cases

login

//Format request encoding req.setCharacterEncoding("utf-8"); //Format response encoding resp.setContentType("text/html;charset=utf-8"); //Get data in Session HttpSession session = req.getSession(); String str=(session.getAttribute("flag")==null?"":"Wrong user name or password"); //Destroy session session.invalidate(); //Get request information //Process request information //Response processing results //Direct response resp.getWriter().write("<html>"); resp.getWriter().write("<head>"); resp.getWriter().write("</head>"); resp.getWriter().write("<body>"); resp.getWriter().write("<form action='user' method='get'>"); resp.getWriter().write("<font color='red'>"+str+"</font>"); resp.getWriter().write(" user name:<input type='text' name='uname' value=''/><br />"); resp.getWriter().write(" password:<input type='password' name='pwd' value=''/><br />"); resp.getWriter().write("<input type='submit' value='Sign in'/><br />"); resp.getWriter().write("</form>"); resp.getWriter().write("</body>"); resp.getWriter().write("</html>");

user

//Format request encoding req.setCharacterEncoding("utf-8"); //Format response encoding resp.setContentType("text/html;charset=utf-8"); //Get request information String uname=req.getParameter("uname"); String pwd=req.getParameter("pwd"); //Process request information //Verify user information if("Zhang San".equals(uname) && "123".equals(pwd)){ //Login successful //Response processing results }else{ //Login failed //Create Session and add login failure flag HttpSession session = req.getSession(); session.setAttribute("flag","loginFalse"); //Response processing results (redirect to login page) resp.sendRedirect("login"); }

Introduction and acquisition of ServletContext object

Question:

Request solves the problem of data sharing in one request, and session solves the problem of data sharing in different users' requests. What should be done for data sharing in different users?

solve:

Using the ServletContext object

effect:

Solve the data sharing problem of different users

Principle:

The ServletContext object is created by the server, and there is only one object in a project. No matter where the project is acquired, the same object will be obtained by the request initiated by different users, which is jointly owned by users.

characteristic:

Server to create

User sharing

Only one project

Life cycle:

Server startup to server shutdown

Scope:

Within the project

use:

Get ServletContext object

Use scope to share data flow

Get web.xml Global configuration in

Get project resource flow object under webroot

Get the absolute path of resources under webroot

Getting ServletContext object

//Format request encoding req.setCharacterEncoding("utf-8"); //Format response encoding resp.setContentType("text/html;charset=utf-8"); //Get request information //Process request information String str = "I'm a user sharing data"; //Get ServletContext object ServletContext servletContext = this.getServletContext(); ServletContext servletContex2 = this.getServletConfig().getServletContext(); ServletContext servletContex3 = req.getSession().getServletContext(); System.out.println(servletContext == servletContex2); //true System.out.println(servletContext == servletContex3); //true

ServletContext object stores and obtains shared data

servletA

//Format request encoding req.setCharacterEncoding("utf-8"); //Format response encoding resp.setContentType("text/html;charset=utf-8"); //Get request information //Process request information String str = "I'm a user sharing data"; //Get ServletContext object ServletContext servletContext = this.getServletContext(); ServletContext servletContex2 = this.getServletConfig().getServletContext(); ServletContext servletContex3 = req.getSession().getServletContext(); System.out.println(servletContext == servletContex2); //true System.out.println(servletContext == servletContex3); //true //Store shared users to ServletContext servletContext.setAttribute("str",str); //Direct response resp.getWriter().write("Data already in ServletContext Storage complete!");

servletB

//Format request encoding req.setCharacterEncoding("utf-8"); //Format response encoding resp.setContentType("text/html;charset=utf-8"); //Get request information //Get ServletContext object ServletContext sc = this.getServletContext(); //Get shared data String s=(String) sc.getAttribute("str"); //Process request information System.out.println("TestServletContextB.service()"+s);

Get web profile global properties

//Format request encoding req.setCharacterEncoding("utf-8"); //Format response encoding resp.setContentType("text/html;charset=utf-8"); //Get request information //Process request information String str="I'm a user sharing data"; //Get ServletContext object ServletContext sc1 = this.getServletContext(); ServletContext sc2 =this.getServletConfig().getServletContext(); ServletContext sc3=req.getSession().getServletContext(); System.out.println(sc1==sc2); System.out.println(sc2==sc3); //Store user shared data to ServletContext sc1.setAttribute("str", str); //obtain web.xml Global configuration properties in String f=sc1.getInitParameter("flag"); if("false".equals(f)){ System.out.println("TestServlectContextA.service(close***resources)"); }else{ System.out.println("TestServlectContextA.service(open***resources)"); } //Get the flow object of resource under webRoot //File f2=new File("D:\\apache-tomcat-7.0.56\\webapps\\sc\\image"); InputStream resourceAsStream = sc1.getResourceAsStream("image/s.png"); //Get the absolute path of resources under WebRoot String path=sc1.getRealPath("image/s.png"); System.out.println(path); //Response processing results //Direct response resp.getWriter().write("Data already in ServletContext Finished storing in");

web configuration

<?xml version="1.0" encoding="UTF-8"?> -<web-app version="2.5" id="WebApp_ID" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <!-- Configure global configuration properties --> -<context-param> <param-name>flag</param-name> <param-value>true</param-value> </context-param> <display-name>ServletContext</display-name> -<servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>TestServlectContextA</servlet-name> <servlet-class>com.alvin.servlet.TestServlectContextA</servlet-class> </servlet> -<servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>TestServletContextB</servlet-name> <servlet-class>com.alvin.servlet.TestServletContextB</servlet-class> </servlet> -<servlet-mapping> <servlet-name>TestServlectContextA</servlet-name> <url-pattern>/sa</url-pattern> </servlet-mapping> -<servlet-mapping> <servlet-name>TestServletContextB</servlet-name> <url-pattern>/sb</url-pattern> </servlet-mapping> -<welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>

ServletContext object implements page access count times

UserServlet

//Format request encoding req.setCharacterEncoding("utf-8"); //Format response encoding resp.setContentType("text/html;charset=utf-8"); //Get request information String uname=req.getParameter("uname"); String pwd=req.getParameter("pwd"); //Process request information //Verify user information if("Zhang San".equals(uname) && "123".equals(pwd)){ //Login successful //Get ServletContext object ServletContext sc=this.getServletContext(); //Get counter Object obj=sc.getAttribute("nums"); //judge if(obj!=null){ //Counter data auto increment int nums=(int) obj; nums=nums+1; //Store counter data to ServletContext object sc.setAttribute("nums", nums); }else{ sc.setAttribute("nums",1); } //Create Session object HttpSession hs=req.getSession(); //Store data hs.setAttribute("uname",uname); //Response processing results (redirected to the login successful Servlet) resp.sendRedirect("main"); }else{ //Login failed //Create Session and add login failure flag HttpSession session = req.getSession(); session.setAttribute("flag","loginFalse"); //Response processing results (redirect to login page) resp.sendRedirect("login"); } }

LoginServlet

//Format request encoding req.setCharacterEncoding("utf-8"); //Format response encoding resp.setContentType("text/html;charset=utf-8"); //Get data in Session HttpSession session = req.getSession(); String str=(session.getAttribute("flag")==null?"":"Wrong user name or password"); //Destroy session session.invalidate(); //Get request information //Process request information //Response processing results //Direct response resp.getWriter().write("<html>"); resp.getWriter().write("<head>"); resp.getWriter().write("</head>"); resp.getWriter().write("<body>"); resp.getWriter().write("<form action='user' method='get'>"); resp.getWriter().write("<font color='red'>"+str+"</font>"); resp.getWriter().write(" user name:<input type='text' name='uname' value=''/><br />"); resp.getWriter().write(" password:<input type='password' name='pwd' value=''/><br />"); resp.getWriter().write("<input type='submit' value='Sign in'/><br />"); resp.getWriter().write("</form>"); resp.getWriter().write("</body>"); resp.getWriter().write("</html>"); }

24 June 2020, 22:34 | Views: 4951

Add new comment

For adding a comment, please log in
or create account

0 comments