Configuring and using servlets in IDEA

Configuring and using servlets in IDEA

Crazy God says Java

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 two 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

Servlet interface sun company has two default implementation classes: HttpServlet,

1. Build an ordinary Maven project, delete the src directory, and create the Module in this project.

This empty project is Maven's main project; pom. Servlets and jsp dependencies can be added to XML

2. Understanding of Maven father son project:

The parent project will have:

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

The subproject will include:

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

3. Write a Servlet program

​ 1. Write a common class

​ 2. To implement the Servlet class, we directly inherit the HttpServlet class

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("get into doGet method");
        PrintWriter writer = resp.getWriter();//Response flow
        writer.print("Hello,Servlet!");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

5. Write Servlet mapping

Why we need to write a mapping: we write a Java program, but we need to access it through the browser, and the browser needs to connect to the web server, so we need to register the Servlet we write in the web service and give it a path that the browser can access

<!--register Servlet-->
<servlet>
  <servlet-name>hello</servlet-name>
  <servlet-class>com.xpccccc.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 that the path of project publishing can be configured (Tomcat 10 may not access 500, so Tomcat 9 can be used)

7. Start up test

Success occurs if

3. 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>/hello1</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>
    
  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

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

    You can customize the suffix to implement the request path

    Note: * the path of project mapping cannot be added in front of it (/ hello/hsdbgcjhsd.xupeng error)

  6. Priority issues

    The inherent mapping path is specified with the highest priority. If it cannot be found, the default processing request will be taken

    <!--404-->
    <servlet>
      <servlet-name>error</servlet-name>
      <servlet-class>com.xpccccc.servlet.ErrorServlet</servlet-class>
    </servlet>
    <servlet-mapping>
      <servlet-name>error</servlet-name>
      <!--Take the default path-->
      <url-pattern>/*</url-pattern>
    </servlet-mapping>
    
    

4,ServletContext

When the web container starts, it will create a corresponding ServletContext object for each web program, which represents the current web application;

4.1. Shared data

The data we save in this Servlet can be obtained in another Servlet

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("Hello");
        //this. Getservletcontext() servlet context
        ServletContext context = this.getServletContext();
        String username="Xu Peng";

        context.setAttribute("username",username);//(similar to key value pair)
    }
}

public class GetServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();
        String username = (String)servletContext.getAttribute("username");

        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().print("name"+username);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

<servlet>
  <servlet-name>hello</servlet-name>
  <servlet-class>com.xpccccc.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>hello</servlet-name>
  <url-pattern>/hello</url-pattern>
</servlet-mapping>

<servlet>
  <servlet-name>getc</servlet-name>
  <servlet-class>com.xpccccc.servlet.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>getc</servlet-name>
  <url-pattern>/getc</url-pattern>
</servlet-mapping>

4.2. Get initialization parameters

@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);
    }
  <context-param>
    <param-name>url</param-name>
    <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
  </context-param>
</servlet>
<servlet-mapping>
  <servlet-name>gp</servlet-name>
  <url-pattern>/gp</url-pattern>
</servlet-mapping>

4.3. Request forwarding

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletContext context = this.getServletContext();
    System.out.println("Entered ServletDemo04");
    context.getRequestDispatcher("/gp").forward(req,resp);//Request forwarding
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req, resp);
}
<servlet>
  <servlet-name>sd4</servlet-name>
  <servlet-class>com.xpccccc.servlet.ServletDemo04</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>sd4</servlet-name>
  <url-pattern>/sd4</url-pattern>
</servlet-mapping>

4.4. Read resource files

Properties

  • Create new properties in java directory
  • Create new properties in the resource directory

Discovery: they are all packaged in the same path: classes. We commonly call this path classpath

Idea: need a file stream

username=root
password=123445
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/xpccccc/servlet/aa.properties");
        Properties prop = new Properties();
        prop.load(is);
        String usr = prop.getProperty("username");
        String psd = prop.getProperty("password");
        resp.getWriter().print(usr+":"+psd);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

5,HttpServletResponse

5.1. Download files

<servlet>
  <servlet-name>down</servlet-name>
  <servlet-class>com.xpccccc.servlet.FileServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>down</servlet-name>
  <url-pattern>/down</url-pattern>
</servlet-mapping>
public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. Get the path of the downloaded file
        System.out.println("get into FileServlet");
        String realPath = "/Users/xupeng/Documents/JavaWeb/javaweb-02-servlet/response/src/main/resources/Screenshot 2022-03-01 10 am.25.07.png" ;
        System.out.println("The download path is:"+realPath);
        //2. What is the name of the downloaded file
        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
        //3. Set up a way to make the browser support downloading what we need
        resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));
        //4. Get the input stream of the downloaded file
        FileInputStream in = new FileInputStream(fileName);

        System.out.println("haha");
        //5. Create buffer period
        int len=0;
        byte[] buffer = new byte[1024];
        //6. Get OutputStream object
        ServletOutputStream out = resp.getOutputStream();
        //7. Write FileInputStream to buffer
        while((len=in.read(buffer))>0){
        //8. Use OutputStream to write buffer data to the client
            out.write(buffer,0,len);
        }
        in.close();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

5.2 implementation of Response verification code

<servlet>
  <servlet-name>image</servlet-name>
  <servlet-class>com.xpccccc.servlet.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>image</servlet-name>
  <url-pattern>/image</url-pattern>
</servlet-mapping>
public class ImageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //How to refresh the browser every 2 seconds
        resp.setHeader("refresh","2");
        //Create a picture in memory
        BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
        //Get pictures
        Graphics g = image.getGraphics();
        //Set picture background color
        g.setColor(Color.white);
        g.fillRect(0,0,80,20);
        //Write data to pictures
        g.setColor(Color.blue);
        g.setFont(new Font(null,Font.BOLD,20));
        g.drawString(makeNum(),0,20);

        //Tell the browser that the request is opened in the form of a picture
        resp.setContentType("image/jpeg");

        //There is a cache on the website. Do not let the browser cache
        resp.setHeader("Cache-Control","no-cache");

        //Write the picture to the browser
        ImageIO.write(image,"jpg",resp.getOutputStream());
    }

    //Production random number
    public String makeNum(){
        Random r = new Random();
        String num=r.nextInt(9999999)+"";//Generate 7-digit verification code
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 7-num.length(); i++) {
            sb.append("0");
        }
        num=sb.toString()+num;
        return num;
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

5.3. Realize redirection

After a web resource receives a request from the client, it will notify the client to access another web resource. This process is called redirection

Common scenarios:

  • User login

    @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            /*
            resp.setHeader("Location","/r1/image");
            resp.setStatus(302);
            * */
            resp.sendRedirect("/r1/image");//redirect
        }
    

The difference between redirection and forwarding

Same point: the page will jump

difference:

  • When the request is forwarded, the url does not change
  • When redirecting, the url changes
<servlet>
  <servlet-name>request</servlet-name>
  <servlet-class>com.xpccccc.servlet.RequestServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>request</servlet-name>
  <url-pattern>/login</url-pattern>
</servlet-mapping>
<html>
<body>
<h2>Hello World!</h2>

<%--The path submitted here needs to find the path to the project--%>
<%--${pageContext.request.contextPath}This represents the current project--%>
<form action="${pageContext.request.contextPath}/login" method="get">
    user name:<input type="text" name="username"> <br>
    password:<input type="password" name="password">  <br>
    <input type="submit">
</form>
</body>
</html>

Note here that web2 3 does not support ${pageContext.request.contextPath}, so it is on the web Update XML to a later version 4.0

<?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">

</web-app>
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("Enter this request");
    String username = req.getParameter("username");
    String password = req.getParameter("password");
    System.out.println(username+":"+password);

    //When redirecting, you must pay attention to the path problem, otherwise 404
    resp.sendRedirect("/r1/success.jsp");

}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>Success</h1>
</body>
</html>

6,HttpServletRequest

HttpServletRequest represents the request of the client. Through the Http protocol server, all the information in the Http request will be encapsulated into HttpServletRequest. Through this HttpServletRequest method, all the information of the client can be obtained

Get front-end parameters and request forwarding

<?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">

    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.xpccccc.servlet.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
    
</web-app>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Sign in</title>
</head>
<body>

<h1>Sign in</h1>

<div>
    <%--Here the form means, in post Submit the form and submit it to our login request--%>
    <form action="${pageContext.request.contextPath}/login" method="post">
        user name:<input type="text" name="username"> <br>
        password:<input type="password" name="password"> <br>
        Hobbies:
            <input type="checkbox" name="hobbies" value="girl">girl
            <input type="checkbox" name="hobbies" value="code">code
            <input type="checkbox" name="hobbies" value="film">film
            <input type="checkbox" name="hobbies" value="sing">sing
        <br>
        <input type="submit">
    </form>
</div>

</body>
</html>

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  	//Set encoding format
    req.setCharacterEncoding("utf-8");
    resp.setCharacterEncoding("utf-8");
    String username = req.getParameter("username");
    String password = req.getParameter("password");
    String[] hobbies = req.getParameterValues("hobbies");
    System.out.println("======================");
    System.out.println(username);
    System.out.println(password);
    System.out.println(Arrays.toString(hobbies));
    System.out.println("======================");

    //Forward by request
    /// here represents the current web application
    req.getRequestDispatcher("/success.jsp").forward(req,resp);

}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req, resp);
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>
    Login successful
</h1>
</body>
</html>

Keywords: Java Maven intellij-idea

Added by buluk21 on Tue, 01 Mar 2022 10:27:52 +0200