Learn a little bit of Servlet every day

1. Web resources

1. The concept of web resources

Deploy the web application to tomcat, all the content in the web application is the resource in the server

2. Classification of web resources

Classification of web resources: dynamic resources written in src in web applications, static resources written in web in web applications

Static resources: The content will not change every time you visit, such as html, css, js, pictures, audio, video. . .

Dynamic resources: Every time you visit, the conditions and situations are different, and the visit results are different, such as: Servlet, jsp, Thymeleaf. . .

Two, Servlet

1. The concept of Servlet

Servlet is a small Java program running on the server (tomcat), which is provided by sun company to define dynamic resource specifications

From the code level, a Servlet is an interface, and all implementation classes that implement the Servlet interface are a Servlet

2. The role of Servlet

The role of Servlet: processing requests and responses

3. Introductory case of Servlet

a>Create a class, implement the Servlet interface, and rewrite all the abstract methods in it

public class FirstServlet implements Servlet {
    
    
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
    
    
		//初始化
    }

    @Override
    public ServletConfig getServletConfig() {
    
    
        //返回一个Servlet的配置对象
        return null;
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
    
    
        System.out.println("hello,Servlet");
        servletResponse.getWriter().println("success");
    }

    @Override
    public String getServletInfo() {
    
    
        //返回一个Servlet的信息
        return null;
    }

    @Override
    public void destroy() {
    
    
		//销毁
    }
}

b> Register Servlet in web.xml

<servlet>
    <servlet-name>FirstServlet</servlet-name>
    <servlet-class>com.xy.servlet.FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>FirstServlet</servlet-name>
    <url-pattern>/firstServlet</url-pattern>
</servlet-mapping>

Notice:

1. When registering a Servlet, the value of the servlet-name in the servlet tag and the servlet-mapping tag should be consistent. It is recommended to use the class name

2. url-pattern sets the virtual path of the Servlet, which must start with /, / means localhost:8080/context path

3. url-pattern sets the rules of the virtual path of the Servlet:

url-pattern can set multiple

url-pattern can set paths in various formats: /test/abc, /test.html, *.do

c> Access Servlet

Access the Servlet through the virtual path of the Servlet in the page, and the corresponding method in the Servlet will be called at this time

D> Deployment path of resources in src

When the web application is deployed to tomcat, the resources under src will be stored in the classes folder under WEB-INF

Three, Servlet life cycle

Tomcat is a Servlet container that can manage the life cycle of Servlets. That is, Servlet re-instantiation, initialization, service, and destruction are all managed by tomcat. What is the process of the Servlet life cycle?

1. Initialization. After the server is started, the first access to the Servlet will execute init(), and it will only be executed once during the entire process of the server running.

Note: You can add the subtag load-on-startup to the servlet tag when registering the Servlet. At this time, the initialization time of the Servlet can be advanced to the time when the server starts, and the smaller the value, the higher the priority

<servlet>
    <servlet-name>SecondServlet</servlet-name>
    <servlet-class>com.xy.servlet.SecondServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

2. Service, every time you access the Servlet, service() will be executed, and it will be executed multiple times during the entire process of the server running

3. Destroy, execute destroy() when the server is closed, and execute it only once during the entire process of server operation

Four, ServletConfig and ServletContext

4.1、ServletConfig

ServletConfig represents the configuration object of the Servlet, so the configuration information of the Servlet can be obtained through this object

/**
 * ServletConfig表示Servlet的配置对象,因此可以通过该对象获取Servlet的配置信息
 * 1、获取Servlet的友好名称,即注册时servlet-name标签的值
 * 2、获取Servlet的初始化参数
 * 3、获取ServletContext
 */
//获取Servlet的友好名称,即注册时servlet-name标签的值
String servletName = servletConfig.getServletName();
System.out.println("Servlet的友好名称:"+servletName);
//获取Servlet的初始化参数
String testInitParam = servletConfig.getInitParameter("testInitParam");
System.out.println("Servlet的初始化参数:" + testInitParam);
//获取ServletContext
ServletContext servletContext = servletConfig.getServletContext();

4.2、ServletContext

ServletContext represents the entire web application, so the relevant content of the web application can be obtained through this object

ServletContext is created when the server is started and destroyed when the server is shut down. It will only be created once during the entire process of running the server, that is, the obtained ServletContext is the same during the entire process of running the current server.

/**
 * ServletContext表示的是整个web应用,因此可以通过该对象获取web应用的相关内容
 * 1、获取当前web应用的上下文路径
 * 2、获取当前web应用的部署路径(真实路径)
 * 3、获取当前web应用的上下文参数
 * 4、作为一个域对象,在整个web应用中共享数据
 */
//获取当前web应用的上下文路径
String contextPath = servletContext.getContextPath();
System.out.println("当前web应用的上下文路径:"+contextPath);
/**
 * 获取当前web应用的部署路径(真实路径)
 * servletContext.getRealPath(""):获取服务器上web应用的路径
 * D:\IDEA\workspace\java_web\out\artifacts\Servlet_war_exploded\
 * servletContext.getRealPath("test"):获取服务器上web应用中某个文件的路径,不会判断该文件是否存在,只是一个拼接的效果
 * D:\IDEA\workspace\java_web\out\artifacts\Servlet_war_exploded\test
 */
String realPath = servletContext.getRealPath("test");
System.out.println("当前web应用的部署路径(真实路径):"+realPath);
//获取当前工程的上下文参数
String testContextParam = servletContext.getInitParameter("testContextParam");
System.out.println("当前web应用的上下文参数:"+testContextParam);
/**
 * ServletContext是一个域对象,可以在整个web应用中共享数据
 * 域对象即区域对象、范围对象,指定的范围中,所使用的对象都是同一个
 * 域对象:请求域(HttpServletRequest),会话域(HttpSession),应用域(ServletContext)
 * 因为在指定的范围值,所获取的域对象都是同一个,因此可以在这个范围内,使用域对象共享数据
 * 操作共享数据的方法:
 * void setAttribute(String name, Object value):设置共享的数据
 * Object getAttribute(String name):获取共享的数据
 * void removeAttribute(String name):删除共享的数据
 */
servletContext.setAttribute("testServletContext", "hello,ServletContext");

Five, the extended implementation class of the Servlet interface

insert image description here

5.1、GenericServlet

GenericServlet implements the Servlet interface, rewrites infrequently used methods, such as init(), destroy(), and sets the method service() that really needs to be rewritten as an abstract method

Therefore, you can inherit GenericServlet when creating a Servlet, and you only need to rewrite service() at this time

5.2、HttpServlet

HttpServlet inherits GenericServlet and rewrites the service() method. Inside the method, converts ServletRequest to HttpServletRequest, converts ServletResponse to HttpServletResponse, and calls service() with HttpServletRequest and HttpServletResponse as parameters, and in this method, Depending on the request method, different methods are called, GET–>doGet(), POST–>doPost()

Therefore, you can inherit HttpServlet when creating a Servlet. At this time, you only need to rewrite doGet() and doPost()

5.3, use idea to create Servlet directly

  1. Add Tomcat or servlet dependencies for the current module or project
    insert image description here
  2. Create a Servlet under the corresponding package
    insert image description here
  3. Create Servlets
    insert image description here

Six, HttpServletRequest

HttpServletRequest encapsulates the request message, so information related to the request message can be obtained through this object, such as the request method, request parameters, request header information, request forwarding, etc.

1. Obtain request-related information

//获取当前请求的请求方式
String method = request.getMethod();
System.out.println("当前请求的请求方式:" + method);
//获取当前请求的上下文路径
String contextPath = request.getContextPath();//重要
System.out.println("当前请求的上下文路径:"+contextPath);
//获取当前所请求的服务器的ip、端口号、协议
String serverName = request.getServerName();
int serverPort = request.getServerPort();
String scheme = request.getScheme();
System.out.println("ip:"+serverName+",端口号:"+serverPort+",协议:"+scheme);
//获取当前请求的url和uri
StringBuffer requestURL = request.getRequestURL();
System.out.println("requestURL = " + requestURL);
String requestURI = request.getRequestURI();
System.out.println("requestURI = " + requestURI);

The uri is written as/项目部署名/资源路径
insert image description here

2. Obtain request header information

//获取请求头信息
String referer = request.getHeader("referer");
System.out.println("referer = " + referer);

3. Get request parameters

//获取单个的请求参数
String username = request.getParameter("username");
String password = request.getParameter("password");
//获取多个同名的请求参数
String[] hobbies = request.getParameterValues("hobby");
System.out.println("username:"+username+",password:"+password+",hobby:"+ Arrays.toString(hobbies));

Notice:

Both get request and post request in tomcat7 have garbled characters when obtaining request parameters

Solution to the garbled problem of get request in tomcat7:

In the configuration file server.xml, add the attribute URIEncoding="UTF-8" to the label that sets the port number

In tomcat8, only post requests have garbled characters when obtaining request parameters

Solution to the problem of garbled characters in post requests in tomcat7 and tomcat8:

Set the encoding before getting the request parameters: request.setCharacterEncoding("UTF-8");

Note: You must not get any request parameters before setting the encoding code, otherwise it will be invalid

4. Request forwarding

Request forwarding is to send the current request to the next resource for further processing, generally forwarding to a certain page, and then this page can be responded to the browser

Since request forwarding is a jump that occurs inside the server, the address in the browser's address bar will not change

//请求转发
request.getRequestDispatcher("/success.html").forward(request, response);

Seven, HttpServletResponse

HttpServletResponse represents the response message, so the information of the response message can be set through this object

1. Response to browser data

//解决响应的数据在页面中显示乱码的问题
response.setContentType("text/html;charset=UTF-8");
//response.setHeader("content-type", "text/html;charset=UTF-8");
//响应浏览器数据
PrintWriter writer = response.getWriter();
//writer.write("helloworld");
writer.print("<h1>你好</h1>");

2. Redirection

Redirection will notify the browser to send the request again to access the redirected address, so the address in the browser's address bar will change

response.sendRedirect("success.html");

3. How the server responds to the browser

a> request forwarding

b> response browser data

c>redirect

4. The difference between forwarding and redirection

insert image description here

a>Request forwarding occurs inside the server. For the browser, only one request is sent, so the address in the browser's address bar will not change

Redirection is the server notifying the browser to send the request again, requesting the redirected address. For the browser, two requests are sent, so the address in the browser's address bar will change

b> Forwarding can obtain data in the requested domain, but redirection cannot

c> Redirection can be accessed across domains, but forwarding is not, because forwarding is a jump that occurs inside the server, so the resources that can be accessed must also be resources inside the server

d>The resources under WEB-INF cannot be directly accessed through the browser, but can only be accessed through the server

Therefore, request forwarding can access resources under WEB-INF, but redirection cannot.

Summary: If the business logic processing is successful, use redirection, and if the business logic processing fails, use forwarding. For example, if the login is successful, use redirection to jump to the success page, and if the login fails, use forwarding to jump to the login page.

8. The path problem of web application

1. The path is divided into relative path and absolute path

Relative path: The target resource is equivalent to the path of the current location

Absolute path:

Static web: The absolute path indicates the path of the resource on the disk, starting with a drive letter

Web application: the absolute path indicates the path of the resource on the server, starting with /

2. Relative path

The relative path path is unreliable, and the absolute path will be mainly used in the future

1. The relative path is related to the location of the target resource and the current location. The current location is different, and the relative path to access the target resource is different, that is, there is no unified relative path for the same resource

2. The relative path is related to the location of the target resource and the current location. When jumping to a page through forwarding, the address in the address bar does not match the content of the page, which will cause the relative path in the page to fail

3. Absolute path

Static web: The absolute path indicates the path of the resource on the disk, starting with a drive letter

Web application: the absolute path indicates the path of the resource on the server, starting with /

Absolute paths in web applications are further divided into absolute paths parsed by browsers and absolute paths parsed by servers

The absolute path parsed by the browser, / is parsed as localhost:8080, such as the absolute path set in the tag in the html page, the absolute path redirected to

The absolute path resolved by the server, / is resolved to localhost:8080/context path, such as the path in web.xml, the path of the resource forwarded to

4. The use of absolute paths in the project

1. In the html page, the absolute path set in the label

a> Manually add the context path when setting the absolute path in the page tag

<a href="/Servlet/success.html">测试/</a>

b> use the base tag

In the head tag, set the base tag, set the page with the base tag, use the path in the tag will be based on the path of the base tag, that is, the real path of the tag base+ the path of the tag

Note: The base tag cannot be applied to paths starting with /, .../, ./

<base href="/Servlet/">

<!--此时超链接真正的路径为/Servlet/testRequestServlet-->
<a href="testRequestServlet">TestRequestServlet</a><br>

2. Absolute path to redirect to

response.sendRedirect(request.getContextPath() + "/success.html");

Guess you like

Origin blog.csdn.net/qq_52370789/article/details/129800999