javawebServlet

javaweb

http响应

服务器 -- 响应 -- 客户端

Accept:告诉浏览器它所支持的数据类型
Accept-Encoding:支持那种 编码格式  GBK  UTF-8  GB2312  ISO8859-1
Content-Type:text/html   类型
Content-Type: image/png
Connection:keep-Alive   连接
Cache-Control: private  缓存控制
Content-Encoding:gzip   编码
Host:主机……/.
Refresh :告诉客户端多久刷新一次
Location:让网页重新定位

servlet

web.xml

<?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>hello</servlet-name>
    <servlet-class>day1.ServletDemo</servlet-class>
</servlet>
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>
package day1;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class ServletDemo extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //ServletInputStream inputStream = req.getInputStream();
        PrintWriter writer = resp.getWriter();
        writer.println("hello world!");
    }

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

<?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>
    <servlet-name>hello</servlet-name>
    <servlet-class>day1.ServletDemo</servlet-class>
</servlet>
<!--    可以有多个servlet映射-->
    <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>
</web-app>



<?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>
    <servlet-name>hello</servlet-name>
    <servlet-class>day1.ServletDemo</servlet-class>
</servlet>
<!--    可以有多个servlet映射-->
    <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>
    
    <servlet>
        <servlet-name>error</servlet-name>
        <servlet-class>day1.ErrorServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>error</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

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

servlet使用

<?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>test</servlet-name>
  <servlet-class>test.ContextTest</servlet-class>
</servlet>
  <servlet-mapping>
    <servlet-name>test</servlet-name>
    <url-pattern>/test</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>test1</servlet-name>
  <servlet-class>test.Test</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>test1</servlet-name>
    <url-pattern>/test1</url-pattern>
  </servlet-mapping>
</web-app>
package test;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

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

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        this.getServletConfig()//获取servlet配置
        //this.getInitParameter()//获得servlet初始化参数
        ServletContext servletContext = this.getServletContext();
        servletContext.setAttribute("username","王涛");
    }
}
package test;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

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

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf8");
        PrintWriter writer = resp.getWriter();
        ServletContext servletContext = this.getServletContext();
        Object username = servletContext.getAttribute("username");
        writer.println(username.toString());
        writer.close();
    }
}

文件过滤问题

<resources>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
      </resource>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
      </resource>
    </resources>

HttpServletRequest

获取前端传递参数
package com.test;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String[] hobbys = req.getParameterValues("hobbys");
        for (String hobby : hobbys) {
            System.out.println(hobby);
        }
req.getRequestDispatcher("/success.jsp").forward(req,resp);
    }

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

<h2>Hello World!</h2>
<div style="text-align: center;">
    <form method="post" action="${pageContext.request.contextPath}/login">
        username: <input type="text" name="username">
        password: <input type="password" name="password">
        hobby:
        <input type="checkbox" name="hobbys" value="girl"> girl
        <input name="hobbys" type="checkbox" value="encoding"> encoding
        <input name="hobbys" type="checkbox" value="song"> song
        <input type="checkbox" name="hobbys" value="playboy"> playboy
<br>
        <input type="submit">
    </form>
</div>

307

HttpServletResponse

响应

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

请求来的信息找HttpServletRequest,响应回去的信息找HttpServletResponse

简单分类

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

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 setBufferSize(int size);
public int getBufferSize();
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 void setStatus(int sc);

public static final int SC_CONTINUE = 100;
    public static final int SC_SWITCHING_PROTOCOLS = 101;

    public static final int SC_OK = 200;

    public static final int SC_CREATED = 201;

    public static final int SC_ACCEPTED = 202;

    public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203;

    public static final int SC_NO_CONTENT = 204;

    public static final int SC_RESET_CONTENT = 205;

    public static final int SC_PARTIAL_CONTENT = 206;

    public static final int SC_MULTIPLE_CHOICES = 300;

    public static final int SC_MOVED_PERMANENTLY = 301;

    public static final int SC_MOVED_TEMPORARILY = 302;

    public static final int SC_FOUND = 302;

    public static final int SC_SEE_OTHER = 303;

    public static final int SC_NOT_MODIFIED = 304;

    public static final int SC_USE_PROXY = 305;

    public static final int SC_TEMPORARY_REDIRECT = 307;

    public static final int SC_BAD_REQUEST = 400;
    public static final int SC_UNAUTHORIZED = 401;

    public static final int SC_PAYMENT_REQUIRED = 402;
    public static final int SC_FORBIDDEN = 403;
    public static final int SC_NOT_FOUND = 404;
    public static final int SC_METHOD_NOT_ALLOWED = 405;
    public static final int SC_NOT_ACCEPTABLE = 406;
    public static final int SC_REQUEST_TIMEOUT = 408;

    public static final int SC_CONFLICT = 409;

    public static final int SC_GONE = 410;

    public static final int SC_LENGTH_REQUIRED = 411;

    public static final int SC_PRECONDITION_FAILED = 412;

    public static final int SC_REQUEST_ENTITY_TOO_LARGE = 413;

    public static final int SC_REQUEST_URI_TOO_LONG = 414;

    public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415;

    public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;

    public static final int SC_EXPECTATION_FAILED = 417;

    public static final int SC_INTERNAL_SERVER_ERROR = 500;

    public static final int SC_NOT_IMPLEMENTED = 501;

    public static final int SC_BAD_GATEWAY = 502;

    public static final int SC_SERVICE_UNAVAILABLE = 503;

    public static final int SC_GATEWAY_TIMEOUT = 504;

    public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505;

文件下载

package test;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

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

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取下载的文件路径
        String realPath = "D:\\ideaProject\\MavenProject\\ServeltTest\\ContextTest\\src\\main\\resources\\1.png";
        //D:\apache-tomcat-8.5.84\webapps\ContextTest_war\1.png,可以写死,直接写绝对路径
        System.out.println(realPath);
        //2.下载的文件名是什么?
        String substring = realPath.substring(realPath.indexOf("\\") + 1);
        //3.设置想办法让浏览器能够支持下载我们需要的资源
        resp.setHeader("Content-Disposition","attachment;filename"+ URLEncoder.encode(substring,"utf-8"));
        //4.获取下载文件的输入流
        FileInputStream fileInputStream = new FileInputStream(realPath);
        //5.创建缓冲区
        byte[] bytes = new byte[1024];
        int len;
        //6.获取输出流对象
        ServletOutputStream outputStream = resp.getOutputStream();
        //7.文件输出流写入到缓冲区
        while ((len = fileInputStream.read(bytes))!=-1){
            outputStream.write(bytes);
        }
        //8.使用输出流讲缓冲区中的数据输入到客户端
        outputStream.close();
        fileInputStream.close();
    }
}

验证码实现

package test;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
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;
public class imageServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //告诉浏览器每五秒刷新一次
        resp.setHeader("refresh","5");
        //在内存中创建图片
        BufferedImage bufferedImage = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = bufferedImage.getGraphics();//生成画笔工具
        graphics.setColor(Color.white);//设置画笔颜色白色
        graphics.fillRect(0,0,80,20);//画出一个矩形图片宽80高20再0,0位置

        //生成随机数
        graphics.setColor(Color.BLUE);//设置画笔颜色蓝色
        graphics.setFont(new Font(null,Font.BOLD,20));//设置字体
        graphics.drawString(makeInt(),0,20);//画出String

        resp.setContentType("image/jpeg");//告诉浏览器响应类型
        resp.setDateHeader("expires",-1);//告诉浏览器数据不缓存
        resp.setHeader("Cache-Control","no-cache");//缓存控制,不缓存
        resp.setHeader("Pragma","no-cache");
//使用ImageIO写出image对象
        ImageIO.write(bufferedImage,"jpeg",resp.getOutputStream());
    }
    public String makeInt(){
        Random random = new Random();
        int i = random.nextInt(9999999);
        String s = "" + i;
        StringBuffer buffer = new StringBuffer();
        for (int j = 0;j < 7-s.length();j++){
            int nextInt = random.nextInt(10);
            String s1 = nextInt + "";
            buffer.append(s1);
        }
        s = buffer.toString() + s;
        return s;
    }
}

实现重定向

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect("/ContextTest_war/image");
}//重定向,实现请求转发

等价于

resp.setHeader("Location","/ContextTest_war/image");
        resp.setStatus(302);
<html>
<body>
<h2>Hello World!</h2>
<form action="${pageContext.request.contextPath}/login" method="get">
    <input type="text" name="username"> username
    <input type="password" name="password"> password
<input type="submit">
</form>
</body>
</html>
package test;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

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

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("login");
        resp.setHeader("Location","/ContextTest_war/image");
        resp.setStatus(302);
        System.out.println(req.getParameter("username"));
        System.out.println(req.getParameter("password"));
    }
}

posted @ 2023-01-30 20:04  小国哥哥  阅读(21)  评论(0编辑  收藏  举报