java servlet

#### 1、Java Web Servlet

src 目录 对应于tomcat 相应应用app下的WEB-INF/classes目录

web目录下的文件对应tomcat 相应应用app下目录文件

httpRequest 请求:

GET /login.html HTTP/1.1请求行 

host:www.baidu.com        请求头

​                                              请求空行 

 username=howhy&age=12      请求体

httpResponse 响应:

HTTP/1.1 200 OK               响应行 

Content-Type: text/html;charset=utf-8  响应头

​                                              响应空行 

 html json                                             响应体

```java
//interface Servlet 
public interface Servlet {
    void init(ServletConfig var1) throws ServletException;//只执行一次 load-on-startup 默认使用时创建若设置为1随tomcat启动而创建

    ServletConfig getServletConfig();

    void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;//业务处理

    String getServletInfo();

    void destroy();//只执行一次随tomcat关闭而销毁
}

public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {
    private static final long serialVersionUID = 1L;
    private transient ServletConfig config;

    public GenericServlet() {
    }

    public void destroy() {
    }

    public String getInitParameter(String name) {
        return this.getServletConfig().getInitParameter(name);
    }

    public Enumeration<String> getInitParameterNames() {
        return this.getServletConfig().getInitParameterNames();
    }

    public ServletConfig getServletConfig() {
        return this.config;
    }

    public ServletContext getServletContext() {
        return this.getServletConfig().getServletContext();
    }

    public String getServletInfo() {
        return "";
    }

    public void init(ServletConfig config) throws ServletException {
        this.config = config;
        this.init();
    }

    public void init() throws ServletException {
    }

    public void log(String msg) {
        this.getServletContext().log(this.getServletName() + ": " + msg);
    }

    public void log(String message, Throwable t) {
        this.getServletContext().log(this.getServletName() + ": " + message, t);
    }

    public abstract void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;

    public String getServletName() {
        return this.config.getServletName();
    }
}

public abstract class HttpServlet extends GenericServlet {
    private static final long serialVersionUID = 1L;
    private static final String METHOD_DELETE = "DELETE";
    private static final String METHOD_HEAD = "HEAD";
    private static final String METHOD_GET = "GET";
    private static final String METHOD_OPTIONS = "OPTIONS";
    private static final String METHOD_POST = "POST";
    private static final String METHOD_PUT = "PUT";
    private static final String METHOD_TRACE = "TRACE";
    private static final String HEADER_IFMODSINCE = "If-Modified-Since";
    private static final String HEADER_LASTMOD = "Last-Modified";
    private static final String LSTRING_FILE = "javax.servlet.http.LocalStrings";
    private static ResourceBundle lStrings = ResourceBundle.getBundle("javax.servlet.http.LocalStrings");

    public HttpServlet() {
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String protocol = req.getProtocol();
        String msg = lStrings.getString("http.method_get_not_supported");
        if (protocol.endsWith("1.1")) {
            resp.sendError(405, msg);
        } else {
            resp.sendError(400, msg);
        }

    }

    protected long getLastModified(HttpServletRequest req) {
        return -1L;
    }

    protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (DispatcherType.INCLUDE.equals(req.getDispatcherType())) {
            this.doGet(req, resp);
        } else {
            NoBodyResponse response = new NoBodyResponse(resp);
            this.doGet(req, response);
            response.setContentLength();
        }

    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String protocol = req.getProtocol();
        String msg = lStrings.getString("http.method_post_not_supported");
        if (protocol.endsWith("1.1")) {
            resp.sendError(405, msg);
        } else {
            resp.sendError(400, msg);
        }

    }

    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String protocol = req.getProtocol();
        String msg = lStrings.getString("http.method_put_not_supported");
        if (protocol.endsWith("1.1")) {
            resp.sendError(405, msg);
        } else {
            resp.sendError(400, msg);
        }

    }

    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String protocol = req.getProtocol();
        String msg = lStrings.getString("http.method_delete_not_supported");
        if (protocol.endsWith("1.1")) {
            resp.sendError(405, msg);
        } else {
            resp.sendError(400, msg);
        }

    }

    private static Method[] getAllDeclaredMethods(Class<?> c) {
        if (c.equals(HttpServlet.class)) {
            return null;
        } else {
            Method[] parentMethods = getAllDeclaredMethods(c.getSuperclass());
            Method[] thisMethods = c.getDeclaredMethods();
            if (parentMethods != null && parentMethods.length > 0) {
                Method[] allMethods = new Method[parentMethods.length + thisMethods.length];
                System.arraycopy(parentMethods, 0, allMethods, 0, parentMethods.length);
                System.arraycopy(thisMethods, 0, allMethods, parentMethods.length, thisMethods.length);
                thisMethods = allMethods;
            }

            return thisMethods;
        }
    }

    protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Method[] methods = getAllDeclaredMethods(this.getClass());
        boolean ALLOW_GET = false;
        boolean ALLOW_HEAD = false;
        boolean ALLOW_POST = false;
        boolean ALLOW_PUT = false;
        boolean ALLOW_DELETE = false;
        boolean ALLOW_TRACE = true;
        boolean ALLOW_OPTIONS = true;

        for(int i = 0; i < methods.length; ++i) {
            Method m = methods[i];
            if (m.getName().equals("doGet")) {
                ALLOW_GET = true;
                ALLOW_HEAD = true;
            }

            if (m.getName().equals("doPost")) {
                ALLOW_POST = true;
            }

            if (m.getName().equals("doPut")) {
                ALLOW_PUT = true;
            }

            if (m.getName().equals("doDelete")) {
                ALLOW_DELETE = true;
            }
        }

        String allow = null;
        if (ALLOW_GET) {
            allow = "GET";
        }

        if (ALLOW_HEAD) {
            if (allow == null) {
                allow = "HEAD";
            } else {
                allow = allow + ", HEAD";
            }
        }

        if (ALLOW_POST) {
            if (allow == null) {
                allow = "POST";
            } else {
                allow = allow + ", POST";
            }
        }

        if (ALLOW_PUT) {
            if (allow == null) {
                allow = "PUT";
            } else {
                allow = allow + ", PUT";
            }
        }

        if (ALLOW_DELETE) {
            if (allow == null) {
                allow = "DELETE";
            } else {
                allow = allow + ", DELETE";
            }
        }

        if (ALLOW_TRACE) {
            if (allow == null) {
                allow = "TRACE";
            } else {
                allow = allow + ", TRACE";
            }
        }

        if (ALLOW_OPTIONS) {
            if (allow == null) {
                allow = "OPTIONS";
            } else {
                allow = allow + ", OPTIONS";
            }
        }

        resp.setHeader("Allow", allow);
    }

    protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String CRLF = "\r\n";
        StringBuilder buffer = (new StringBuilder("TRACE ")).append(req.getRequestURI()).append(" ").append(req.getProtocol());
        Enumeration reqHeaderEnum = req.getHeaderNames();

        while(reqHeaderEnum.hasMoreElements()) {
            String headerName = (String)reqHeaderEnum.nextElement();
            buffer.append(CRLF).append(headerName).append(": ").append(req.getHeader(headerName));
        }

        buffer.append(CRLF);
        int responseLength = buffer.length();
        resp.setContentType("message/http");
        resp.setContentLength(responseLength);
        ServletOutputStream out = resp.getOutputStream();
        out.print(buffer.toString());
        out.close();
    }

    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getMethod();
        long lastModified;
        if (method.equals("GET")) {
            lastModified = this.getLastModified(req);
            if (lastModified == -1L) {
                this.doGet(req, resp);
            } else {
                long ifModifiedSince;
                try {
                    ifModifiedSince = req.getDateHeader("If-Modified-Since");
                } catch (IllegalArgumentException var9) {
                    ifModifiedSince = -1L;
                }

                if (ifModifiedSince < lastModified / 1000L * 1000L) {
                    this.maybeSetLastModified(resp, lastModified);
                    this.doGet(req, resp);
                } else {
                    resp.setStatus(304);
                }
            }
        } else if (method.equals("HEAD")) {
            lastModified = this.getLastModified(req);
            this.maybeSetLastModified(resp, lastModified);
            this.doHead(req, resp);
        } else if (method.equals("POST")) {
            this.doPost(req, resp);
        } else if (method.equals("PUT")) {
            this.doPut(req, resp);
        } else if (method.equals("DELETE")) {
            this.doDelete(req, resp);
        } else if (method.equals("OPTIONS")) {
            this.doOptions(req, resp);
        } else if (method.equals("TRACE")) {
            this.doTrace(req, resp);
        } else {
            String errMsg = lStrings.getString("http.method_not_implemented");
            Object[] errArgs = new Object[]{method};
            errMsg = MessageFormat.format(errMsg, errArgs);
            resp.sendError(501, errMsg);
        }

    }

    private void maybeSetLastModified(HttpServletResponse resp, long lastModified) {
        if (!resp.containsHeader("Last-Modified")) {
            if (lastModified >= 0L) {
                resp.setDateHeader("Last-Modified", lastModified);
            }

        }
    }

    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        HttpServletRequest request;
        HttpServletResponse response;
        try {
            request = (HttpServletRequest)req;
            response = (HttpServletResponse)res;
        } catch (ClassCastException var6) {
            throw new ServletException("non-HTTP request or response");
        }

        this.service(request, response);
    }
}

```

```Java
@WebServlet("/demo3")//http://localhost:8081/ServeletDemo2/demo3?name=howhy&age=12
public class ServletDemo3 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(req);//org.apache.catalina.connector.RequestFacade@68663bec tomcat extends HttpServlet 
        System.out.println(req.getMethod());//get
        System.out.println(req.getContextPath());// /ServeletDemo2
        System.out.println(req.getServletPath());// /demo3
        System.out.println(req.getPathInfo());
        System.out.println(req.getQueryString());// name=howhy&age=12
        System.out.println(req.getRequestURI());// /ServeletDemo2/demo3
        System.out.println(req.getRequestURL());// http://localhost:8081/ServeletDemo2/demo3
        Enumeration<String> headerNames = req.getHeaderNames();
        while(headerNames.hasMoreElements()){
            System.out.println(headerNames.nextElement());
        }
        System.out.println(req.getHeader("user-agent"));
        resp.getWriter().write("ssssssss");
    }

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

##### 1.1转发和重定向

转发:一次请求  只能转发内部路径  可以reqeust域

重定向:两次请求 可以跳转到外部路径 不可以用request域

```
</head>
<body>
<div style="width:300px; height:300px;margin:100px auto">
    <img src="/ServeletDemo3/demo2" id="img"/>
    <a href="#" id="imga">看不清换一张</a>
</div>
<script>
    (function(){
        var img=document.getElementById("img");
        var imga=document.getElementById("imga");
        img.onclick=function(){
            img.src="/ServeletDemo3/demo2?t="+new Date().getMilliseconds();
        }
        imga.onclick=function(){
            img.src="/ServeletDemo3/demo2?t="+new Date().getMilliseconds();
        }
    })()

</script>
</body>
</html>
```

```
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;


@WebServlet("/demo2")
public class ServeletDemo2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int h=50;
        int w=100;
        BufferedImage bufferedImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = bufferedImage.getGraphics();
        graphics.setColor(Color.pink);
        graphics.fillRect(0,0,w,h);
//        graphics.setColor(Color.blue);
//        graphics.fillRect(0,0,w-1,h-1);
        String azStr="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            int index=random.nextInt(azStr.length());
            char code=azStr.charAt(index);
            System.out.println(code);
            graphics.setColor(Color.blue);
            graphics.drawString(code+"",(i+1)*20,25);
        }
        graphics.setColor(Color.green);
        for (int i = 0; i <10 ; i++) {
            int x1=random.nextInt(w);
            int x2=random.nextInt(w);
            int y1=random.nextInt(w);
            int y2=random.nextInt(w);
            graphics.drawLine(x1,y1,x2,y2);
        }
        ImageIO.write(bufferedImage,"jpg",resp.getOutputStream());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("demo2");
        this.doGet(req,resp);
    }
}

```

```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <a href="/ServeletDemo3/download?filename=20201201.png">下载1</a>
</body>
</html>
```

```
package com.howhy.controller;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("33333333333333333333");
        String filename=req.getParameter("filename");
        ServletContext servletContext = this.getServletContext();
        String mimeType = servletContext.getMimeType(filename);
        resp.setContentType(mimeType);
        resp.setHeader("content-disposition","attachment;filename="+filename);

        String path=servletContext.getRealPath("/img/"+filename);
        System.out.println(path);
        FileInputStream fileInputStream = new FileInputStream(path);
        byte[] buff=new byte[1024];
        int len=0;
        while((len=fileInputStream.read(buff))!=-1){
            resp.getOutputStream().write(buff,0,len);
        }
        fileInputStream.close();
    }

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

```

#### 二 jsp

jsp其实就是一个servlet

jsp脚本 <% i=5 %> 这样的代码相当于是在servlet类中的service方法定义 int i=5

<%! i=3 %> 这样的代码相当于是在servlet类中定义的成员变量 

<%=i%>  这样的代码相当于是在servlet类中的service输出i的值 为5

jsp内置对象

​    request response out

```
<%@ page import="com.howhy.controller.User" %>
<%@ page import="java.util.Date" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.HashMap" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
  <head>
    <title>el</title>
  </head>
  <body>
  <h4>${4+2}</h4>
  <h4>${4-2}</h4>
  <h4>${4*2}</h4>
  <h4>${4/2}</h4>
  <h4>${4%2}</h4>
  <h4>${4==2}</h4>
  <h4>${4==2 || 1==1}</h4>
  <%
      request.setAttribute("name","howhy");
      session.setAttribute("age",23);
      User user = new User();
      user.setName("aa");
      user.setAge(22);
      user.setBirth(new Date());
      request.setAttribute("user",user);
      ArrayList<Integer> listarr=new ArrayList<Integer>();
      listarr.add(2);
      listarr.add(21);
      listarr.add(22);
      request.setAttribute("list",listarr);
    HashMap<String, Integer> mp = new HashMap<String, Integer>();
    mp.put("zs",12);
    mp.put("ls",22);
    mp.put("ww",23);
    request.setAttribute("users",mp);
    request.setAttribute("flag",true);
    request.setAttribute("number",3);
  %>
  <h5>${requestScope.name1}</h5><!--此处取域属性值 也可以直接写${name}会依次从域pageContext request session applicationContext中从小到大查找  找到就不往下找了-->
  <h5>${sessionScope.age}</h5>
  ${user.name}<br/><!--此处取类的属性值类中必须有相应属性的getName方法-->
  ${user.birth}<br/>
  ${user.birthStr}<br/>
  ${requestScope.list}<br/>
  ${list[0]}<br/>
  <c:forEach var="a" items="${list}">
    <h4>${a}</h4>
  </c:forEach>
  ${requestScope.users.zs}<br/>
  ${requestScope.users["ls"]}<br/>
  ${empty list}<!--emtpy not empty判断字符串 数组 集合 是否为null并且长度为0-->
<c:if test="${flag}">
  <h5>this is display</h5>
</c:if><br/>
  <c:choose >
    <c:when test="${number==1}">星期一</c:when>
    <c:when test="${number==2}">星期二</c:when>
    <c:when test="${number==3}">星期三</c:when>
    <c:when test="${number==4}">星期四</c:when>
    <c:when test="${number==5}">星期五</c:when>
    <c:when test="${number==6}">星期六</c:when>
    <c:when test="${number==7}">星期七</c:when>
    <c:otherwise>无效的星期数字</c:otherwise>
  </c:choose>
  </body>
</html>

```

####  三 filter

filte url-pattern  特定的url /index.jsp 路径目录/user/* 路径后缀通配符*.jsp  所有 /*

 

posted @ 2020-12-10 16:40  howhy  阅读(67)  评论(0)    收藏  举报