当前位置:网站首页>Servlet self study notes

Servlet self study notes

2022-06-23 05:08:00 Don't want to be a programmer

To write Servlet Mapping

Why do I need to map : What we're writing is Java Program , But access it through a browser , The browser needs to connect web The server , So we need to be able to web Register what we wrote in the server servlet,
You also need to give him a path that the browser can access ;
 Insert picture description here

Mapping problem

1、 One servlet You can specify a mapping path

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

2、 One servlet Multiple mapping paths can be specified

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

3、 One servlet You can specify a generic mapping path

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

4、 Specify some suffixes or prefixes

<!-- You can customize suffixes to implement request mapping   Be careful ,* The path of project mapping cannot be added in the front , As long as .wanaei The ending is OK  -->
  <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>*.wanaei</url-pattern>
    </servlet-mapping>

web.xml Head

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

servletContext

gitee Code
web When the container starts , It will web Programs create a corresponding ServletContext object , It represents the present web application ;

  • Shared data
    I'm here servlet Data stored in , It can be in another servlet Get in the
  • Get configuration parameters
<!-- Configure some web Application initialization parameters -->
    <context-param>
        <param-name>url</param-name>
        <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
    </context-param>
  • Request forwarding
 @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        ServletContext context = this.getServletContext();
// RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");// Forward to request path 
// requestDispatcher.forward(req,resp);
            context.getRequestDispatcher("/gp").forward(req,resp);
    }
  • Read resource file – properties class
    • stay java New under the directory properties
    • stay resources New under the directory properties
      Find out : Are packaged under the unified path :classes, We commonly call this path classpath
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
        Properties pro = new Properties();
        pro.load(is);
        String username = pro.getProperty("username");
        String password = pro.getProperty("password");
        resp.getWriter().print(username+":"+password);
    }

HttpServletResponse

web The server received... From the client http request , In response to this request , Create one for each request HttpServletRequest object , Represents a response HttpServletResponse;

  • If you want to get the parameters requested by the client : look for HttpServletResquest
  • If you want to respond to some information to the client : look for HttpServletResponse

1、 Simple classification
Responsible for sending data to the browser

  • public ServletOutputStream getOutputStream() throws IOException; public PrintWriter getWriter() throws IOException;
  • The method responsible for sending some response headers to the browser

2、 Simple application
1、 Output message to browser
2、 Download the file
- To get the downloaded file path
- What is the name of the downloaded file
- Set up a way to make the browser support downloading what we need
- Get the download file input stream
- Create buffer
- obtain OutputStream object
- take FileOutputStream Stream write to buffer buffer
- Use OutputStream Output the data in the buffer to the client

@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
// -  To get the downloaded file path 
// String realPath = this.getServletContext().getRealPath("F:\\my_project\\JavaToGiteeUp\\javaWebPro\\response\\src\\main\\resources\\1.png");
        String realPath = "F:\\my_project\\JavaToGiteeUp\\javaWebPro\\response\\src\\main\\resources\\1.png";
// -  What is the name of the downloaded file 
        String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
// -  Set up a way to make the browser support downloading what we need 
        resp.setHeader("Content-disposition","attachment;filename="+filename);// You can search web Download the header information of the file 
// -  Get the download file input stream 
        FileInputStream in = new FileInputStream(realPath);
// -  Create buffer 
        int len = 0;
        byte[] buffer = new byte[1024];
// -  obtain OutputStream object 
        ServletOutputStream out = resp.getOutputStream();
// -  take FileOutputStream Stream write to buffer buffer , Use OutputStream Output the data in the buffer to the client 
        while((len=in.read(buffer))>0){
    
            out.write(buffer,0,len);
        }
        in.close();
        out.close();
    }

3、 Verification code function
Verify how it came from ?

  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
//  How to make the browser 3 Refresh every second 
        resp.setHeader("refresh","3");
//  Create an image in memory 
        BufferedImage bufferedImage = new BufferedImage(80,20, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = (Graphics2D)bufferedImage.getGraphics();// pen 
//  Set the background color of the picture 
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0,0,80,20);
//  Write data for pictures 
        graphics.setColor(Color.BLUE);
        graphics.setFont(new Font(null,Font.BOLD,20));
        graphics.drawString(makeNum(),0,20);
//  Tell the browser , This request is opened in the form of a picture 
        resp.setContentType("image/png");
//  There is a cache on the site , Don't let the browser cache 
        resp.setDateHeader("expirse",-1);
        resp.setHeader("Cache-Control","no-cache");
        resp.setHeader("pragma","no-cache");
//  Write the picture to the browser 
        boolean write = ImageIO.write(bufferedImage, "png", resp.getOutputStream());
    }
// Generate random number 
    private String makeNum(){
    
        Random random = new Random();
        String num = random.nextInt(9999999) + "";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 7-num.length(); i++) {
    
            sb.append("0");
        }
        num = sb.toString() + num;
        return num;
    }

4、 Implement redirection
One web After the resource receives a client request , It tells the client to access another web resources , This process is called redirection

  resp.sendRedirect("/resp/draw");

Common scenes :

  • The user login

Common interview questions : Please talk about the difference between redirection and forwarding ?
The same thing :

  • All pages will jump

Difference

  • When the request is forwarded ,url There will be no change
  • When redirecting ,url The address bar will change

HttpServletRequest

HttpServletRequest Represents the request of the client , User pass Http Protocol problem access server ,HTTP All information in the request will be encapsulated in HttpServletRequest, Through this HttpServletRequest Method , Get all the information from the client ;
1、 Request forwarding
Focus on the first one 、 The fourth one .
 Insert picture description here

原网站

版权声明
本文为[Don't want to be a programmer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230136592072.html