编程语言
首页 > 编程语言> > 20210121 JavaWeb之Servlet 详解第二部分

20210121 JavaWeb之Servlet 详解第二部分

作者:互联网

6 、Servlet

6.1 Servlet简介

把实现了Servlet接口的Java程序叫做,Servlet

6.2 HelloServlet

Servlet接口Sun公司有两个默认的实现类:HttpServlet GenericServlet

  1. 构建一个普通的Maven项目,删掉里面的src目录,以后我们的学习就在这个项目里建立Moudle;这个空的工程就是Maven主工程

  2. 关于Maven父子工程的理解

    • 父项目中会有

      <modules>
              <module>servlet01</module>
      </modules>
      
    • 子项目中会有

      <parent>
              <artifactId>javaweb-01-servlet</artifactId>
              <groupId>com.gdh</groupId>
              <version>1.0-SNAPSHOT</version>
      </parent>
      

父项目中的java子项目可以直接使用 son extends father

  1. Maven环境优化

    • 修改web.xml为最新的
    • 将maven的结构搭建完整
  2. 编写一个Servlet程序

    • 编写一个普通类
    • 实现servlet接口,直接继承HttpServlet
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
       // ServletOutputStream outputStream = resp.getOutputStream();
        PrintWriter writer = resp.getWriter();//响应流
        writer.print("Hellr world");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
  1. 编写Serverlet的映射

    为什么需要映射:我们写的JAVA程序,但是要通过浏览器访问,而浏览器需要连接web服务器,所以我们需要在web服务器中注册我们写的Servlet,还需要给他一个浏览器能够访问的路径;

     <!--注册servlet-->
        <servlet>
            <servlet-name>helloServlet</servlet-name>
            <servlet-class>com.dyt.servlet.HelloServlet</servlet-class>
        </servlet>
        <!--一个servlet对应一个mapping映射-->
        <servlet-mapping>
            <servlet-name>helloServlet</servlet-name>
            <!--请求路径-->
            <url-pattern>/hello</url-pattern>
        </servlet-mapping>
    
  2. 配置tomcat

  3. 启动项目测试

6.3 Servlet原理

Servlet是由Web服务器调用,web服务器在收到浏览器请求之后,会
在这里插入图片描述

6.4 Mapping问题

  1. 一个Servlet可以指定一个映射路径

    <servlet-mapping>
        <servlet-name>helloServlet</servlet-name>
        <!--请求路径-->
        <url-pattern>/hello</url-pattern>
      </servlet-mapping>
    
  2. 一个Servlet可以指定多个映射路径

    <servlet-mapping>
        <servlet-name>helloServlet</servlet-name>
        <!--请求路径-->
        <url-pattern>/hello</url-pattern>
      </servlet-mapping>
    <servlet-mapping>
        <servlet-name>helloServlet</servlet-name>
        <!--请求路径-->
        <url-pattern>/hello1</url-pattern>
      </servlet-mapping>
    
  3. 一个Servlet可以指定通用映射路径

    <servlet-mapping>
        <servlet-name>helloServlet</servlet-name>
        <!--请求路径-->
        <url-pattern>/hello/*</url-pattern>
      </servlet-mapping>
    
  4. 指定一些后缀或者前缀

      <!--可以自定义后缀实现请求映射  *前边不能加项目映射的路径  ssss.gdh-->
      <servlet-mapping>
        <servlet-name>helloServlet</servlet-name>
        <!--请求路径-->
        <url-pattern>*.gdh</url-pattern>
      </servlet-mapping>
    
  5. 默认请求路径

    <servlet-mapping>
        <servlet-name>helloServlet</servlet-name>
        <!--请求路径-->
        <url-pattern>/*</url-pattern>
      </servlet-mapping>
    
  6. 优先级问题

    指定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求;

    <!--404处理-->
    <servlet>
        <servlet-name>error</servlet-name>
        <servlet-class>com.gdh.servlet.ErrorServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>error</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
    

6.5 ServletContext

web容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用。可以保存一下数据

6.6 HttpServletResponse

web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse;

1.简单分类

负责向浏览器发送数据的方法

public ServletOutputStream getOutputStream() throws IOException;  //用于文件流
public PrintWriter getWriter() throws IOException;   //用于写中文

负责向浏览器发送响应头的方法

public void setCharacterEncoding(String charset);  //设置响应编码
public void setContentLength(int len);             //设置字符串响应的长度
public void setContentLengthLong(long len);        //设置长度 
public void setContentType(String type);           //设置类型
public void setDateHeader(String name, long date);
public void addDateHeader(String name, long date);
public void setHeader(String name, String value);
public void addHeader(String name, String value);
public void setIntHeader(String name, int value);
public void addIntHeader(String name, int value);

响应状态码

public static final int SC_CONTINUE = 100;

    /**
     * Status code (101) indicating the server is switching protocols
     * according to Upgrade header.
     */
    public static final int SC_SWITCHING_PROTOCOLS = 101;

    /**
     * Status code (200) indicating the request succeeded normally.
     */
    public static final int SC_OK = 200;

    /**
     * Status code (201) indicating the request succeeded and created
     * a new resource on the server.
     */
    public static final int SC_CREATED = 201;

    /**
     * Status code (202) indicating that a request was accepted for
     * processing, but was not completed.
     */
    public static final int SC_ACCEPTED = 202;

    /**
     * Status code (203) indicating that the meta information presented
     * by the client did not originate from the server.
     */
    public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203;

    /**
     * Status code (204) indicating that the request succeeded but that
     * there was no new information to return.
     */
    public static final int SC_NO_CONTENT = 204;

    /**
     * Status code (205) indicating that the agent <em>SHOULD</em> reset
     * the document view which caused the request to be sent.
     */
    public static final int SC_RESET_CONTENT = 205;

    /**
     * Status code (206) indicating that the server has fulfilled
     * the partial GET request for the resource.
     */
    public static final int SC_PARTIAL_CONTENT = 206;

    /**
     * Status code (300) indicating that the requested resource
     * corresponds to any one of a set of representations, each with
     * its own specific location.
     */
    public static final int SC_MULTIPLE_CHOICES = 300;

    /**
     * Status code (301) indicating that the resource has permanently
     * moved to a new location, and that future references should use a
     * new URI with their requests.
     */
    public static final int SC_MOVED_PERMANENTLY = 301;

    /**
     * Status code (302) indicating that the resource has temporarily
     * moved to another location, but that future references should
     * still use the original URI to access the resource.
     *
     * This definition is being retained for backwards compatibility.
     * SC_FOUND is now the preferred definition.
     */
    public static final int SC_MOVED_TEMPORARILY = 302;

    /**
    * Status code (302) indicating that the resource reside
    * temporarily under a different URI. Since the redirection might
    * be altered on occasion, the client should continue to use the
    * Request-URI for future requests.(HTTP/1.1) To represent the
    * status code (302), it is recommended to use this variable.
    */
    public static final int SC_FOUND = 302;

    /**
     * Status code (303) indicating that the response to the request
     * can be found under a different URI.
     */
    public static final int SC_SEE_OTHER = 303;

    /**
     * Status code (304) indicating that a conditional GET operation
     * found that the resource was available and not modified.
     */
    public static final int SC_NOT_MODIFIED = 304;

    /**
     * Status code (305) indicating that the requested resource
     * <em>MUST</em> be accessed through the proxy given by the
     * <code><em>Location</em></code> field.
     */
    public static final int SC_USE_PROXY = 305;

     /**
     * Status code (307) indicating that the requested resource 
     * resides temporarily under a different URI. The temporary URI
     * <em>SHOULD</em> be given by the <code><em>Location</em></code> 
     * field in the response.
     */
    public static final int SC_TEMPORARY_REDIRECT = 307;

    /**
     * Status code (400) indicating the request sent by the client was
     * syntactically incorrect.
     */
    public static final int SC_BAD_REQUEST = 400;

    /**
     * Status code (401) indicating that the request requires HTTP
     * authentication.
     */
    public static final int SC_UNAUTHORIZED = 401;

    /**
     * Status code (402) reserved for future use.
     */
    public static final int SC_PAYMENT_REQUIRED = 402;

    /**
     * Status code (403) indicating the server understood the request
     * but refused to fulfill it.
     */
    public static final int SC_FORBIDDEN = 403;

    /**
     * Status code (404) indicating that the requested resource is not
     * available.
     */
    public static final int SC_NOT_FOUND = 404;

    /**
     * Status code (405) indicating that the method specified in the
     * <code><em>Request-Line</em></code> is not allowed for the resource
     * identified by the <code><em>Request-URI</em></code>.
     */
    public static final int SC_METHOD_NOT_ALLOWED = 405;

    /**
     * Status code (406) indicating that the resource identified by the
     * request is only capable of generating response entities which have
     * content characteristics not acceptable according to the accept
     * headers sent in the request.
     */
    public static final int SC_NOT_ACCEPTABLE = 406;

    /**
     * Status code (407) indicating that the client <em>MUST</em> first
     * authenticate itself with the proxy.
     */
    public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407;

    /**
     * Status code (408) indicating that the client did not produce a
     * request within the time that the server was prepared to wait.
     */
    public static final int SC_REQUEST_TIMEOUT = 408;

    /**
     * Status code (409) indicating that the request could not be
     * completed due to a conflict with the current state of the
     * resource.
     */
    public static final int SC_CONFLICT = 409;

    /**
     * Status code (410) indicating that the resource is no longer
     * available at the server and no forwarding address is known.
     * This condition <em>SHOULD</em> be considered permanent.
     */
    public static final int SC_GONE = 410;

    /**
     * Status code (411) indicating that the request cannot be handled
     * without a defined <code><em>Content-Length</em></code>.
     */
    public static final int SC_LENGTH_REQUIRED = 411;

    /**
     * Status code (412) indicating that the precondition given in one
     * or more of the request-header fields evaluated to false when it
     * was tested on the server.
     */
    public static final int SC_PRECONDITION_FAILED = 412;

    /**
     * Status code (413) indicating that the server is refusing to process
     * the request because the request entity is larger than the server is
     * willing or able to process.
     */
    public static final int SC_REQUEST_ENTITY_TOO_LARGE = 413;

    /**
     * Status code (414) indicating that the server is refusing to service
     * the request because the <code><em>Request-URI</em></code> is longer
     * than the server is willing to interpret.
     */
    public static final int SC_REQUEST_URI_TOO_LONG = 414;

    /**
     * Status code (415) indicating that the server is refusing to service
     * the request because the entity of the request is in a format not
     * supported by the requested resource for the requested method.
     */
    public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415;

    /**
     * Status code (416) indicating that the server cannot serve the
     * requested byte range.
     */
    public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;

    /**
     * Status code (417) indicating that the server could not meet the
     * expectation given in the Expect request header.
     */
    public static final int SC_EXPECTATION_FAILED = 417;

    /**
     * Status code (500) indicating an error inside the HTTP server
     * which prevented it from fulfilling the request.
     */
    public static final int SC_INTERNAL_SERVER_ERROR = 500;

    /**
     * Status code (501) indicating the HTTP server does not support
     * the functionality needed to fulfill the request.
     */
    public static final int SC_NOT_IMPLEMENTED = 501;

    /**
     * Status code (502) indicating that the HTTP server received an
     * invalid response from a server it consulted when acting as a
     * proxy or gateway.
     */
    public static final int SC_BAD_GATEWAY = 502;

    /**
     * Status code (503) indicating that the HTTP server is
     * temporarily overloaded, and unable to handle the request.
     */
    public static final int SC_SERVICE_UNAVAILABLE = 503;

    /**
     * Status code (504) indicating that the server did not receive
     * a timely response from the upstream server while acting as
     * a gateway or proxy.
     */
    public static final int SC_GATEWAY_TIMEOUT = 504;

    /**
     * Status code (505) indicating that the server does not support
     * or refuses to support the HTTP protocol version that was used
     * in the request message.
     */
    public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505;

2.常见应用

public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取文件的相对路径
        String path = this.getServletContext().getRealPath("/WEB-INF/classes/image-20201225111804440.png");
        System.out.println("下载文件的地址:"+ path);
        //下载的文件名是啥
        String filename = path.substring(path.lastIndexOf("\\")+1);//获取文件名称,在转化为子串
        //response.setHeader告诉浏览器以什么方式打开
        //假如文件名称是中文则要使用 URLEncoder.encode()编码
        //否则直接使用response.setHeader("content-disposition", "attachment;filename=" + filename);即可
        resp.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
        InputStream in = null ;
        OutputStream out = null ;
        try {
            in = new FileInputStream(path); //获取文件的流
            int len = 0;
            byte buf[] = new byte[1024];//缓存作用
            out = resp.getOutputStream();//输出流
            while( (len = in.read(buf)) > 0 ){ //切忌这后面不能加 分号 ”;“
                out.write(buf, 0, len);//向客户端输出,实际是把数据存放在response中,然后web服务器再去response中读取
            }
        }finally {
            if(in!=null) {
                try{
                    in.close();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
            if(out!=null) {
                try{
                    out.close();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

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

3.验证码功能

验证怎么来的?

public class ImageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //如何让浏览器3秒自动刷新一次
        resp.setHeader("refresh","3");
        //在内存占用创建一个图片
        BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
        //得到图片
        Graphics2D g = (Graphics2D) image.getGraphics();//笔
        //设置背景颜色
        g.setColor(Color.white);
        g.fillRect(0,0,80,20);
        //给图片写数据
        g.setColor(Color.red);
        g.setFont(new Font(null,Font.BOLD,20));
        g.drawString(makeNum(),0,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 = String.valueOf(random.nextInt(9999999));
        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;
    }

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

4.实现重定向

B一个web资源收到客户端A请求后,B他会通知A客户端去访问另外一个web资源C,这个过程叫重定向。

常见场景:用户登录

public void sendRedirect(String location) throws IOException;

测试:

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setHeader("Location","/r/img");
    resp.setStatus(302);
    resp.sendRedirect("/r/img"); //重定向
}

面试题:请你聊聊重定向和转发的区别?

相同点 页面都是实现跳转

不同点 请求转发的时候,url不会产生变化307 重定向时候,url地址栏会发生变化302

简单请求响应

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("进入这个请求");
    //处理请求
    String username = req.getParameter("username");
    String password = req.getParameter("password");
    System.out.println(username +":"+ password);
    //重定向
    resp.sendRedirect("/r/success.jsp");
}
<%--这里提交的路径,需要寻找到项目的路径--%>
<%--${pageContext.request.contextPath} 项目路径--%>
<form action="${pageContext.request.contextPath}/login" method="get">
    用户名:<input type="text" name="username"><br>
    密码: <input type="password" name="password"><br>
    <input type="submit">
</form>

6.6 HttpServletRequest

  1. 获取前端传递过来的参数
req.getParameter("username");  //String
req.getParameterValues()       //String[]
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("进入这个请求");
    //编码问题
    req.setCharacterEncoding("utf-8");
    resp.setCharacterEncoding("utf-8");
    //处理请求
    String username = req.getParameter("username");
    String password = req.getParameter("password");
    System.out.println(username +":"+ password);
    //重定向
    //resp.sendRedirect("/r/success.jsp");
    //转发
    req.getRequestDispatcher("success.jsp").forward(req,resp);

}

标签:code,JavaWeb,int,resp,static,20210121,SC,Servlet,public
来源: https://blog.csdn.net/qq_41096598/article/details/112968482