Servlet

6.Servlet

6.1Servlet简介

Servlet是开发动态网页的一门技术,是一个接口

开发一个Servlet程序,只需要两步:

​ 1>编写一个类,实现Servlet接口

​ 2>把开发好的Java类部署到Web服务器中

6.2 HellowServlet

Servlet接口有两个默认的实现类:HttpServlet , GenericServlet

1.主工程

构建一个普通的maven项目(javaweb-04-maven),删除src目录,以后的学习就在这里面建立model,这个空的就是主工程

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

父项目中有(javaweb-04-maven)

<modules>    
    <module>servlet-01</module>
</modules>

子项目会有(servlet-01)

<parent>
    <artifactId>javaweb-04-maven</artifactId>
    <groupId>com.scl</groupId>
    <version>1.0-SNAPSHOT</version>
</parent>

父项目中的Java子项目可以直接使用

3.maven环境优化

​ 1>.修改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">
</web-app>

​ 2>.将maven的结构搭建完整

​ 添加java目录(标记目录为源根),resources目录(标记为资源根)

4.编写一个servlet程序

​ 1>.编写一个普通类

​ 2>.实现一个HttpServlet接口

public class HellowServlet extends HttpServlet {
    
    //由于get或者post只是请求实现的不同方式,可以相互调用,业务逻辑都一样
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
        
        PrintWriter writer =resp.getWriter();//响应流
        writer.println("Hellow Servlet");
    }

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

5.编写Servlet的映射

为什么需要映射:我们写的是Java程序,需要通过浏览器访问,而浏览器需要连接web服务器,所以需要在web服务器注册我们写的Servlet,还需要给一个访问路径(在web.xml文件里添加)

<servlet>
    <servlet-name>servler-01</servlet-name>
    <servlet-class>com.scl.servlet.HellowServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>servler-01</servlet-name>
    <url-pattern>/servlet_01_war</url-pattern>
</servlet-mapping>

6.配置Tomcat

在这里插入图片描述

7.启动测试

6.3Servlet原理

Servlet是由web服务器调用,web服务器在收到请求后会执行下面的过程

在这里插入图片描述

6.4Mapping问题

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

<servlet-mapping>
    <servlet-name>servlet-01</servlet-name>
    <url-pattern>/servlet_01_war</url-pattern>
</servlet-mapping>

2.一个Servlet请求可以指定多个映射路径

<servlet-mapping>
    <servlet-name>servlet-01</servlet-name>
    <url-pattern>/servlet_01_war</url-pattern>
</servlet-mapping>
 <servlet-mapping>
     <servlet-name>servlet-01</servlet-name>
     <url-pattern>/servlet_01_war2</url-pattern>
 </servlet-mapping>   

3.一个Servlet请求可以指定一个通用映射路径(可以利用默认映射路径自己编辑404界面)

<servlet-mapping>
    <servlet-name>servlet-01</servlet-name>
    <url-pattern>/servlet_01_war/*</url-pattern>
</servlet-mapping>

4.优先级

​ 指定的映射路径优先级最高,找不到映射路径就会走到默认路径

6.5 ServletContext(servlet-02)

web容器在启动时,会为每个web程序都创建一个对应的ServletContext对象,代表了当前的web应用

1>共享数据

​ 在这个Servlet保存的数据可以在另一个Servlet中使用

Servlet HellowServlet 将姓名保存在ServletContext中( .getServletContext())

public class HellowServlet extends HttpServlet {

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

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

        ServletContext context= this.getServletContext();

        String username ="邵成龙";
        context.setAttribute("username",username);//将一个数据保存在ServletContext中,名字(属性)为:username,值为:username
    }
}

在这里插入图片描述

Servlet GetServlet从ServletContext中获取姓名,并且输出

public class GetServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context= this.getServletContext();
        String username=(String)context.getAttribute("username");


        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-16");
        resp.getWriter().println("姓名: "+username);
    }

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

在这里插入图片描述

2>获取初始化参数

在web.xml文件里添加初始化参数( .getInitParameter)

<!--配置web应用的初始化参数-->
    <context-param>
        <param-name>url</param-name>
        <param-value>jdbc:mysql://loacalhost:3306/mybatis</param-value>
    </context-param>

添加一个servlet

public class ServletDemo03 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context= this.getServletContext();
        String url= context.getInitParameter("url");

        resp.getWriter().println(url);
    }

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

在这里插入图片描述

3>请求转发()

.getRequestDispatcher

public class ServletDemo04 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context= this.getServletContext();

        System.out.println("进入了ServletDemo04");

//        RequestDispatcher requestDispatcher= context.getRequestDispatcher("/getp");//转发的请求路径
//        requestDispatcher.forward(req,resp);//调用forward实现请求转发
        context.getRequestDispatcher("/getp").forward(req,resp);

    }

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

4>读取资源文件

Properties

在java目录下新建properties

在resources下新建properties

发现都被打包到同一个路径下:classes,我们俗称为classpath

思路:需要一个文件流

6.6HttpServletResponse

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

如果要获取客户端请求过来的参数,找HttpServletRequest

如果要给客户端响应一些信息,找HttpServletResponce

1.简单分类

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

ServletOutputStream getOutputStream() throws IOException;//写普通的流
PrintWriter getWriter() throws IOException;//写中文

负责向浏览器发送响应头

    void setCharacterEncoding(String var1);

    void setContentLength(int var1);

    void setContentLengthLong(long var1);

    void setContentType(String var1);

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

响应状态码:

2xx : 请求响应成功 200

3xx : 请求重定向

4xx : 找不到资源 404

5xx : 服务器代码错误 500 网关错误: 502

 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.常见应用

1.向浏览器输出消息
2.下载文件

1.要获取下载文件的路径

2.下载文件的文件名

3.设置想办法让浏览器支持下载需要的东西

4.获取下载文件的输入流

5.创建缓冲区

6.获取OutputStream对像

7.将FileOutputStream流写入buffer缓冲区

8.使用OUtputStream将缓冲区的数据输出到客户端

public class FileServlet extends HttpServlet {

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

//        1.要获取下载文件的路径
        String realPath="D:\\JAVA\\Java Web\\javaweb-04-maven\\response\\src\\main\\resources\\图片.jpg";
//        2.下载文件的文件名
        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);//最后一个斜杠后面的就是文件名
//        3.设置想办法让浏览器支持(Content-Disposition)下载需要的东西 ,文件名是中文时,用URLEncoder.encode(fileName,"UTF-8")  代替fileName;
        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,0,len);
        }
        in.close();
        out.close();

//
    }

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

3.验证码功能

验证码怎么来的:

前端实现

后端实现,需要用到java的图片类,生成一个图片

让浏览器自动刷新

resp.setHeader("refresh","3");
public class ImageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //让浏览器3s刷新一次
        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.BLUE);
        g.setFont(new Font(null,Font.BOLD,20));
        g.drawString(makeNum(),0,20);

        //告诉浏览器,这个请求用图片的方式打开
        resp.setContentType("image/jpeg");

        //网站存在缓存,不让浏览器缓存
        resp.setDateHeader("expires",-1);
        resp.setHeader("Cache-comtral","no-cache");
        resp.setHeader("Pragma","no-cache");

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

    //生成随机数
    public String makeNum(){
        Random random=new Random();
        String num = random.nextInt(9999999) + "";//将int型转为String
        StringBuffer sb = new StringBuffer();
        for (int i=0;i<7-num.length();i++){
            sb.append("0");//随机生成的数字不足4位用0填充
        }
        num= sb.toString()+num;
        return num;
    }


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

4.实现重定向

一个web资源(B)收到客户端(A)请求后,会通知客户端(A)去访问另一个web资源©,这个过程叫做重定向

在这里插入图片描述

常见场景:

用户登录

void sendRedirect(String var1) throws IOException;

测试

java文件
public class RedirectServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*
        resp.setHeader("Location","/response/img");
        resp.setStatus(302);
         */
        //上面两步等于下面一行
        resp.sendRedirect("/response/img");//重定向
    }

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

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>filedown</servlet-name>
    <servlet-class>com.scl.servlet.FileServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>filedown</servlet-name>
    <url-pattern>/down</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>ImageServlet</servlet-name>
    <servlet-class>com.scl.servlet.ImageServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ImageServlet</servlet-name>
    <url-pattern>/img</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>RedirectServlet</servlet-name>
    <servlet-class>com.scl.servlet.RedirectServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>RedirectServlet</servlet-name>
    <url-pattern>/red</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>RequestTest</servlet-name>
    <servlet-class>com.scl.servlet.RequestTest</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>RequestTest</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>
  
</web-app>

index.jsp文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>

<%--这里提交的路径需要寻找到项目的路径--%>
<%--${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>

</body>
</html>

success.jsp文件

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

面试题: 重定向与转发的区别

相同点:都会实现页面跳转

不同点:

请求转发时,url 不会发生变化 307

重定向时,url地址栏会变化 302

在这里插入图片描述

浏览器中文显示乱码问题:

1.修改浏览器编码为utf-8

2.在默认的index.jsp文件最上面添加

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

6.7 HttpServletRequest

HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,Http请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息

应用场景:

1.获取前端传递的参数,请求转发

方法

在这里插入图片描述

java文件
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //后台接收中文乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String[] hobbys = req.getParameterValues("hobbys");

        System.out.println("===================================");
        System.out.println(username);
        System.out.println(password);
        System.out.println(Arrays.toString(hobbys));
        System.out.println("===================================");

        //通过请求转发
        //后端"/success.jsp"里的"/"代表当前项目,不需要"/request/success.jsp"
        req.getRequestDispatcher("/success.jsp").forward(req,resp);

    }

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

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>LoginServlet</servlet-name>
    <servlet-class>com.scl.servlet.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>

</web-app>

index.jsp文件
<?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>LoginServlet</servlet-name>
    <servlet-class>com.scl.servlet.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>

</web-app>

success.jsp文件
<%--
  Created by IntelliJ IDEA.
  User: sll
  Date: 2020/11/5
  Time: 11:58
  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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值