Servlet

Servlet

1. Introduction to Servlet

The Java program that implements the servlet interface is called servlet

2. HelloServlet

The servlet interface has two default implementation classes in Sun company: httpservlet and genericservlet

be careful! Don't forget to add the URL/

<!--Servlet的请求路径-->
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

3. Servlet principle

The servlet is called by the web server. After receiving the browser request, the web server will:

4. Mapping problem

5. ServletContext

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

1. Shared data

The data I saved in this servlet can be obtained in another servlet

Put in - > take out - > configure mapping

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req,IOException {

        //this.getInitParameter();      初始化参数
        //this.getServletConfig();      Servlet配置
        //this.getServletContext();     Servlet上下文

        ServletContext context = this.getServletContext();

        String username = "王诗凯";    //数据
        context.setAttribute("username",username); //将一个数据保存在ServletContext中,名字为username,值username

        System.out.println("Hello");
    }

}
public class GetServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req,IOException {
        ServletContext context = this.getServletContext();   //拿到的是同一个ServletContext,因为全局唯一

        String username = (String)context.getAttribute("username");

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

    @Override
    protected void doPost(HttpServletRequest req,IOException {
        super.doGet(req,resp);
    }
}
  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>com.wang.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.wang.servlet.GetServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>getc</servlet-name>
    <url-pattern>/getc</url-pattern>
  </servlet-mapping>

Test access results

2. Get initialization parameters

  <!--配置一些web应用初始化参数-->
  <context-param>
    <param-name>url</param-name>
    <param-value>jdbc:MysqL://localhost:3306/mybatis</param-value>
  </context-param>
@Override
    protected void doGet(HttpServletRequest req,IOException {
        ServletContext context = this.getServletContext();   //拿到的是同一个ServletContext,因为全局唯一

        String url = context.getInitParameter("url");
        resp.getWriter().print(url);
    }

3. Request forwarding

@Override
    protected void doGet(HttpServletRequest req,IOException {
        ServletContext context = this.getServletContext();   //拿到的是同一个ServletContext,因为全局唯一
        System.out.println("进入了ServletDemo04");
        /*
        RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");  //转发请求路径
        requestDispatcher.forward(req,resp);   //调用forward实现请求转发
         */

        context.getRequestDispatcher("/gp").forward(req,resp);
    }

4. Read resource file

Properties

Discovery: they are all packaged in the same path: classes, which we commonly call classpath

Idea: you need a file stream

@Override
    protected void doGet(HttpServletRequest req,IOException {
        InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");

        Properties prop = new Properties();
        prop.load(is);
        String user = prop.getProperty("username");
        String pwd = prop.getProperty("password");

        resp.getWriter().print(user + ":" + pwd);
    }

Just access the test

6. HttpServletResponse

The web server receives the HTTP request from the client. For this request, create an HttpServletRequest object representing the request and an httpservletresponse representing the response;

1. Simple classification

Method responsible for sending data to browser

servletOutputStream getOutputStream() throws IOException;
PrintWriter getWriter() throws IOException;

Method responsible for sending response header to browser

    void setDateHeader(String var1,long var2);

    void addDateHeader(String var1,long var2);

    void setHeader(String var1,String var2);

    void addHeader(String var1,String var2);

    void setIntHeader(String var1,int var2);

    void addIntHeader(String var1,int var2);

    void setCharacterEncoding(String var1);

    void setContentLength(int var1);

    void setContentLengthLong(long var1);

    void setContentType(String var1);

Response status code

    int SC_CONTINUE = 100;
    int SC_SWITCHING_PROTOCOLS = 101;
    int SC_OK = 200;
    int SC_CREATED = 201;
    int SC_ACCEPTED = 202;
    int SC_NON_AUTHORITATIVE_INFORMATION = 203;
    int SC_NO_CONTENT = 204;
    int SC_RESET_CONTENT = 205;
    int SC_PARTIAL_CONTENT = 206;
    int SC_MULTIPLE_CHOICES = 300;
    int SC_MOVED_PERMANENTLY = 301;
    int SC_MOVED_TEMPORARILY = 302;
    int SC_FOUND = 302;
    int SC_SEE_OTHER = 303;
    int SC_NOT_MODIFIED = 304;
    int SC_USE_PROXY = 305;
    int SC_TEMPORARY_REDIRECT = 307;
    int SC_BAD_REQUEST = 400;
    int SC_UNAUTHORIZED = 401;
    int SC_PAYMENT_required = 402;
    int SC_FORBIDDEN = 403;
    int SC_NOT_FOUND = 404;
    int SC_METHOD_NOT_ALLOWED = 405;
    int SC_NOT_ACCEPTABLE = 406;
    int SC_PROXY_AUTHENTICATION_required = 407;
    int SC_REQUEST_TIMEOUT = 408;
    int SC_CONFLICT = 409;
    int SC_GONE = 410;
    int SC_LENGTH_required = 411;
    int SC_PRECONDITION_Failed = 412;
    int SC_REQUEST_ENTITY_TOO_LARGE = 413;
    int SC_REQUEST_URI_TOO_LONG = 414;
    int SC_UNSUPPORTED_MEDIA_TYPE = 415;
    int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    int SC_EXPECTATION_Failed = 417;
    int SC_INTERNAL_SERVER_ERROR = 500;
    int SC_NOT_IMPLEMENTED = 501;
    int SC_BAD_GATEWAY = 502;
    int SC_SERVICE_UNAVAILABLE = 503;
    int SC_GATEWAY_TIMEOUT = 504;
    int SC_HTTP_VERSION_NOT_SUPPORTED = 505;

2. Common applications

@Override
    protected void doGet(HttpServletRequest req,IOException {
        //1. 要获取下载文件的路径
        //D:\JavaWeb\HelloServlet\response\target\classes\TIM截图20200728172813.png
        //String realPath = this.getServletContext().getRealPath("/TIM截图20200728172813.png");
        String realPath = "D:\\JavaWeb\\HelloServlet\\response\\target\\classes\\TIM截图20200728172813.png";
        System.out.println("下载文件的路径:" + realPath);
        //2. 下载的文件名是啥?
        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
        //3. 设置想办法让浏览器能够支持(Content-Disposition)下载我们需要的东西,中文文件名用URLEncoder.encode编码,否则可能乱码
        resp.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName,"utf-8"));
        //4. 获取下载文件的输出流
        FileInputStream in = new FileInputStream(realPath);
        //5. 创建缓冲流
        int len = 0;
        byte[] buffer = new byte[1024];
        //6. 获取OutputStream对象
        ServletOutputStream out = resp.getOutputStream();
        //7. 将FileOutputStream流写入到Buffer缓冲区
        //8. 使用OutputStream将缓冲区的数据输出到客户端
        while ((len = in.read(buffer)) > 0){
            out.write(buffer,len);
        }

        in.close();
        out.close();
    }
	@Override
    protected void doGet(HttpServletRequest req,IOException {
        //如何让浏览器3s刷新一次
        resp.setHeader("refresh","3");

        //在内存中创建一个图片
        BufferedImage image = new BufferedImage(100,20,BufferedImage.TYPE_INT_RGB);
        //得到图片
        Graphics2D g = (Graphics2D) image.getGraphics();    //笔
        //设置图片的背景颜色
        g.setColor(Color.white);
        g.fillRect(0,100,20);
        //给图片写数据
        g.setColor(Color.blue);
        g.setFont(new Font(null,Font.BOLD,20));
        g.drawString(makeNum(),20);

        //告诉浏览器,这个请求用图片的方式打开
        resp.setContentType("image/jpeg");
        //网站存在缓存,不让浏览器请求
        resp.setDateHeader("expires",-1);
        resp.setHeader("Cache-Control","no-cache");
        resp.setHeader("Pragma","no-cache");

        //把图片写给浏览器
        ImageIO.write(image,"jpg",resp.getOutputStream());


    }

    //生成随机数
    private String makeNum(){
        Random random = new Random();
        String num = random.nextInt(99999999) + "";
        StringBuffer sb = new StringBuffer();
        //防止数字不满8位,空位用0填充
        for (int i = 0; i < 7 - num.length(); i++) {        //快捷键 fori
            sb.append("0");
        }
        String s = sb.toString() + num;
        return num;
    }

After a web resource is requested by the client, it will notify the client to access another web resource. This process is called redirection

Common scenarios:

    void sendRedirect(String var1) throws IOException;

test

    @Override
    protected void doGet(HttpServletRequest req,IOException {
        /*重定向的原理
        resp.setHeader("Location","/response/img");
        resp.setStatus(302)
         */
        resp.sendRedirect("/response/img");     //重定向
    }

Interview question: please talk about the difference between redirection and forwarding

Same point

difference

Request redirection

@Override
protected void doGet(HttpServletRequest req,IOException {
    //处理请求
    String username = req.getParameter("username");
    String password = req.getParameter("password");

    System.out.println(username + ":" + password);

    //重定向时候一定要注意,路径问题,否则404
    resp.sendRedirect("/response/success.jsp");
}

index. jsp

<html>
<body>
<h2>Hello World!</h2>

<%--这里提交的路径,需要寻找到项目的路径--%>
<%--${pageContext.request.contextPath}代表当前的的项目--%>
<form action="${pageContext.request.contextPath}/login" method="get">
    用户名:<input type = "text" name="username">
    密码:<input type="password" name="password">
    <input type="submit">
</form>


</body>
</html>

success. jsp

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

7. HttpServletRequset

HttpServletRequest represents the request of the client. The user accesses the server through the HTTP protocol. All the information in the HTTP request will be encapsulated in the HttpServletRequest. Through this HttpServletRequest method, all the information of the client can be obtained

Get parameters and request forwarding

@Override
protected void doGet(HttpServletRequest req,IOException {
    //后台接受中文乱码问题
    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("===================================");

    //通过请求转发
    System.out.println(req.getContextPath());
    //说明:转发是内部资源,写相对路径;重定向是外部资源,写绝对路径
    req.getRequestDispatcher("success.jsp").forward(req,resp);
}

index. jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
</head>
<body>

<h1>登录</h1>

<div style="text-align: center">
    <%--这里表单表示的意思:以post方式提交表单,提交到我们的login请求--%>
    <form action="${pageContext.request.contextPath}/login" method="post">
        用户名:<input type="text" name="username"> <br>
        密码:<input type="password" name = "password"> <br>
        爱好:
        <input type="check@R_109_2419@" name = "hobbies" value="女孩">女孩
        <input type="check@R_109_2419@" name = "hobbies" value="代码">代码
        <input type="check@R_109_2419@" name = "hobbies" value="唱歌">唱歌
        <input type="check@R_109_2419@" name = "hobbies" value="电影">电影

        <br>
        <input type="submit">
    </form>
</div>
</body>
</html>

success. jsp

<%--
  Created by IntelliJ IDEA.
  User: a000248
  Date: 2020/7/30
  Time: 11:14
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h1>登录成功!</h1>

</body>
</html>
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>