JavaWeb -- Servlet, Mapping problem, ServletContext

1. Introduction to Servlet Servlet is a tec...
1. Introduction to Servlet
  • Servlet is a technology for sun company to develop dynamic web

  • Sun provides an interface called Servlet in these API s. If you want to develop a Servlet program, you only need to complete two small steps:

    • Write a class to implement the Servlet interface
    • Deploy the developed Java classes to the web server

The Java program that implements the servlet interface is called Servlet

2. HelloServlet

Sun company has two default implementation classes: HttpServlet and GenericServlet
(1) Build a common Maven project, delete the src directory, and then we will build Moudel in this project; this empty project is the main project of Maven;
For example, create a common Maven project named javaweb-02-servlet, delete the src directory, add dependencies, and finally create a Moudel named servlet-01 in this project

Building Moudel





(2) Understanding of Maven father son project
There will be

<modules> <module>servlet-01</module> </modules>

Subprojects will have

<parent> <artifactId>javaweb-02-servlet</artifactId> <groupId>com.kuang</groupId> <version>1.0-SNAPSHOT</version> </parent>

java subprojects in the parent project can be used directly

son extends father

(3) Maven environment optimization

  • Modify web.xml to the latest
  • Complete the structure of maven
    Create java and resources packages in the main directory and mark them

    (4) Write a Servlet program

    ① Write a common class
    ② Implement the Servlet interface, here we directly inherit HttpServlet
package com.zz.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; public class HelloServlet extends HttpServlet { //Because get or post are just different ways of request implementation, they can call each other, and the business logic is the same; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //ServletOutputStream outputStream = resp.getOutputStream(); PrintWriter writer = resp.getWriter(); //Response flow writer.print("Hello,Serlvet"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }

(5) Write Servlet mapping
Why mapping is needed: we write JAVA programs, but to access through a browser, and the browser needs to connect to the web server, so we need to register our Servlet in the web service, and also need to give it a path that the browser can access;

<!--register Servlet--> <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.zz.servlet.HelloServlet</servlet-class> </servlet> <!--Servlet Request path for--> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping>

(6) Configure Tomcat
Note: configure the path of project publishing


(7) Start the test, OK!
Click the start button on the top right, and a folder named target will be generated after successful operation


3. Servlet principle

The Servlet is called by the web server. After the web server receives the browser request, it will:

4. Mapping problem

(1) A Servlet can specify a mapping path

<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping>


(2) A Servlet can specify multiple mapping paths

<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello2</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello3</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello4</url-pattern> </servlet-mapping>


(3) A Servlet can specify a common mapping path

<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello/*</url-pattern> </servlet-mapping>


(4) Default request path

<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping>


(5) Specify some suffixes or prefixes, etc

<! -- you can customize the suffix to implement the request mapping Note * cannot be preceded by project mapping path hello/sajdlkajda.zz can also --> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>*.zz</url-pattern> </servlet-mapping>


Note: the path of project mapping cannot be added in front of point * i.e. the / symbol in front of point * is removed
(6) Priority issues
It specifies that the inherent mapping path has the highest priority. If it cannot be found, it will go to the default processing request;

<!--register Servlet--> <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.zz.servlet.HelloServlet</servlet-class> </servlet> <!--Servlet Request path for--> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <!--register Servlet--> <servlet> <servlet-name>error</servlet-name> <servlet-class>com.zz.servlet.ErrorServlet</servlet-class> </servlet> <!--Servlet Request path for--> <servlet-mapping> <servlet-name>error</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping>


It can be seen from the above figure that hello also belongs to / *, but enter hello and enter HelloServlet

5. ServletContext

When the web container is started, it will create a corresponding ServletContext object for each web program. It represents the current web application, specifically the following applications
(1) Share data
The data I save in this servlet can be obtained in another servlet;

Code in HelloServlet:

package com.zz.servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //this.getInitParameter() initialization parameter //This. Getservletconfig() servlet configuration //This. Getservletcontext() servlet context ServletContext context = this.getServletContext(); String username = "mogul"; //data context.setAttribute("username", username); //A data is saved in the ServletContext named: username. Value username } }

Code in GetServlet:

package com.zz.servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class GetServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); String username = (String) context.getAttribute("username"); resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); resp.getWriter().print("The name is"+username); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }

Code in web.xml:

<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0" metadata-complete="true"> <!--register Servlet--> <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.zz.servlet.HelloServlet</servlet-class> </servlet> <!--Servlet Request path for--> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet> <servlet-name>getc</servlet-name> <servlet-class>com.zz.servlet.GetServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>getc</servlet-name> <url-pattern>/getc</url-pattern> </servlet-mapping> </web-app>

Test access results:

  • Enter getc directly
  • Enter hello first, then getc

(2) Get initialization parameters
Create ServletDemo03

package com.zz.servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class ServletDemo03 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); String url = context.getInitParameter("url"); resp.getWriter().print(url); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }

Add the following configuration in web.xml:

<!--Some configuration web Application initialization parameters--> <context-param> <param-name>url</param-name> <param-value>jdbc:mysql://localhost:3306/mybatis</param-value> </context-param>
<servlet> <servlet-name>gp</servlet-name> <servlet-class>com.zz.servlet.ServletDemo03</servlet-class> </servlet> <servlet-mapping> <servlet-name>gp</servlet-name> <url-pattern>/gp</url-pattern> </servlet-mapping>

Test access results:

(3) Request forwarding
Create ServletDemo04

package com.zz.servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class ServletDemo04 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); System.out.println("Entered ServletDemo04"); //RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp"); / / the path of the forwarded request //requestDispatcher.forward(req,resp); / / call forward to forward the request; context.getRequestDispatcher("/gp").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }

Add the following configuration in web.xml:

<servlet> <servlet-name>sd4</servlet-name> <servlet-class>com.zz.servlet.ServletDemo04</servlet-class> </servlet> <servlet-mapping> <servlet-name>sd4</servlet-name> <url-pattern>/sd4</url-pattern> </servlet-mapping>

Test access results:

It can be seen that the access is to the gp interface, but the access address does not change

(4) Read resource file
Properties

  • Create a new aa.properties in the java directory
    username=root123
    password=hahaha123
  • Create a new db.properties in the resources directory
    username=root
    password=123456

After clicking Tomcat to run, it is found that db.properties is in the directory, but aa.properties is not

Solution: configure resources in the build of the current pom.xml file to prevent the failure of resource export

<build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build>

After clicking Tomcat again, we found that: they are all packed in the same path: classes, which we commonly call classpath:

  • Create ServletDemo05 and read the resource file aa.properties
    Idea: need a file stream
package com.zz.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class ServletDemo05 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/com/zz/servlet/aa.properties"); Properties prop = new Properties(); prop.load(is); String user = prop.getProperty("username"); String pwd = prop.getProperty("password"); resp.getWriter().print(user+":"+pwd); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
  • Add the following configuration in web.xml:
<servlet> <servlet-name>sd5</servlet-name> <servlet-class>com.zz.servlet.ServletDemo05</servlet-class> </servlet> <servlet-mapping> <servlet-name>sd5</servlet-name> <url-pattern>/sd5</url-pattern> </servlet-mapping>

Test access results:

Read the resource file db.properties the same as above.

Easonnzz Published 38 original articles, won praise 1, visited 1278 Private letter follow

8 February 2020, 06:48 | Views: 1700

Add new comment

For adding a comment, please log in
or create account

0 comments