Java教程

JavaWeb-6-Servlet

本文主要是介绍JavaWeb-6-Servlet,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

跟着狂神学JavaWeb -> 6. Servlet

6.1 Servlet简介

  • Servlet就是sun公司开发动态Web的一门技术
  • Sun在这些API中提供了一个接口叫Servlet
  • 如果想要开发一个Servlet程序,只需要完成两个步骤:
    • 编写一个类,实现Servlet接口;
    • 把开发好的Java类部署到Web服务器中。
  • 把实现了Servlet接口的Java程序,叫做Servlet

6.2 HelloServlet

  1. 构建一个普通的Maven项目,删除src目录,以后的就在这个项目里面建立Module;这个空的工程就是Maven的主工程

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

    • 父工程中会有:
    <modules>
        <module>servlet-01</module>
    </modules>
    
    • 子工程中会有:
    <parent>
        <artifactId>javaweb-02-servlet</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    
    • 父工程中的Jar包子工程可以使用
  3. Maven环境优化

    • 修改web.xml为最新的配置
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             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>
    
    • 将Maven结构搭建完整

    在这里插入图片描述

  4. 编写一个Servlet程序

    • ①编写一个普通的类
    • ②实现Servlet接口,直接继承HttpServlet
    public class HelloServlet extends HttpServlet {
        //由于get/post只是请求实现的不同方式,可以互相调用,业务逻辑都一样
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            PrintWriter writer = resp.getWriter(); /*响应流*/
            writer.print("Hello, Servlet");
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            super.doPost(req, resp);
        }
    }
    
  5. 编写Servlet的映射

    为什么需要映射?

    • 因为这里写的是Java程序,但是需要通过浏览器来访问,而浏览器需要连接web服务器,所以需要在web服务器中注册这里写的Servlet,还需要给一个浏览器能够访问的路径:
    <!--注册Servlet-->
        <servlet>
            <servlet-name>hello</servlet-name>
            <servlet-class>com.ano.servlet.HelloServlet</servlet-class>
        </servlet>
        <!--Servlet的请求路径-->
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello</url-pattern>
        </servlet-mapping>
    
  6. 配置Tomcat

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  1. 启动测试

    • 浏览器输入:localhost:8080/s1/hello

    遇到的问题:利用Tomcat 10.0.4 构建类servlet报错:类HelloServlet不是Servlet?

    • 解决办法:参考

    • 用到的两个依赖:

    <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-servlet-api -->
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-servlet-api</artifactId>
        <version>10.0.4</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jsp-api -->
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-jsp-api</artifactId>
        <version>10.0.4</version>
    </dependency>
    

6.3 Servlet原理

在这里插入图片描述

6.4 Mapping问题

  • 一个Servlet可以指定一个映射路径
  • 一个Servlet可以指定多个映射路径
  • 一个Servlet可以指定通用映射路径
  • 默认请求路径
  • 可以自定义后缀实现请求路径
  • 优先级问题

6.5 ServletContext 应用

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

6.5.1. 共享数据
/**
 * @author ano
 * 放置数据的类
 */
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        //data
        String username = "南柱赫";
        //将data保存在了ServletContext中
        context.setAttribute("username",username);


        System.out.println("hello");
    }
}
/**
 * @author ano
 * 获取数据的类
 */
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-8");
        PrintWriter writer = resp.getWriter();
        writer.println(username);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(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">
    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.ano.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.ano.servlet.GetServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>getc</servlet-name>
        <url-pattern>/getc</url-pattern>
    </servlet-mapping>

</web-app>

测试访问结果:

在这里插入图片描述

6.5.2. 获取初始化参数
  • web.xml中的配置
<!--配置一些web应用的初始化参数-->
<context-param>
    <param-name>url</param-name>
    <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>

<servlet>
    <servlet-name>getp</servlet-name>
    <servlet-class>com.ano.servlet.GetParam</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>getp</servlet-name>
    <url-pattern>/getp</url-pattern>
</servlet-mapping>
  • 获取初始化参数的类
/**
 * @author wangjiao
 */
public class GetParam extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String url = context.getInitParameter("url");
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().println(url);
    }

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

  • 测试结果

在这里插入图片描述

6.5.3. 请求转发
/**
 * @author ano
 * ServletContext-->请求转发
 */
public class ReqDispatch extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        context.getRequestDispatcher("/getp").forward(req,resp);
    }
}
  • web.xml中的配置
<servlet>
    <servlet-name>reqD</servlet-name>
    <servlet-class>com.ano.servlet.ReqDispatch</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>reqD</servlet-name>
    <url-pattern>/reqD</url-pattern>
</servlet-mapping>
  • 测试结果:

在这里插入图片描述

6.5.4 读取资源文件

在java目录下新建db.properties文件;

在resources目录下新建db.properties文件

发现:都被打包在同一个路径下:class,俗称这个路径为classpath

  • db.properties
username=root
password=123456
  • 读取资源类
/**
 * @author ano
 */
public class PropertiesServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        InputStream inputStream = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");

        Properties properties = new Properties();
        properties.load(inputStream);

        String username = properties.getProperty("username");
        String password = properties.getProperty("password");

        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");

        resp.getWriter().print(username + ":" + password);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
  • web.xml配置
<servlet>
    <servlet-name>propS</servlet-name>
    <servlet-class>com.ano.servlet.PropertiesServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>propS</servlet-name>
    <url-pattern>/propS</url-pattern>
</servlet-mapping>
  • 测试结果

在这里插入图片描述

6.6 HttpServletResponse

  • web服务器接收到客户端的http请求,针对这个请求,分别会创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse对象;
  • 如果要获取客户端请求过来的参数,找HttpServletRequest;
  • 如果要给客户端响应一些信息,找HttpServletResponse.
6.6.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 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);
  • 响应状态码
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;
6.6.2 下载文件

常见应用包括:向浏览器输出消息;下载文件等。

  • 下载文件步骤:
    1. 获取下载文件的路径
    2. 下载的文件名
    3. 设置想办法让浏览器能够支持需要下载的文件
    4. 获取下载文件的输入流
    5. 创建缓冲区
    6. 获取OutputStream对象
    7. 将FileOutputStream流写入到buffer缓冲区
    8. 使用OutputStrean将缓冲区的数据输出到客户端
public class FileServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 获取下载文件的路径
        //String realPath = this.getServletContext().getRealPath("/babe.jpg");
        String realPath = "E:\\workspace\\javaweb-02-servlet\\response\\src\\main\\resources\\babe.jpg";
        System.out.println("下载文件的路径:" + realPath);
        //2. 下载的文件名
        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
        //3. 设置想办法让浏览器能够支持需要下载的文件,如果是中文文件名,用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缓冲区,使用OutputStrean将缓冲区的数据输出到客户端
        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 {
        super.doPost(req, resp);
    }
}

6.6.3 验证码功能

验证码如何实现:

  • 前端实现;
  • 后端实现:需要用到Java的图片类,生成一个图片
public class ImageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.让浏览器5s刷新一次
        resp.setHeader("refresh","3");
        //2.在内存种创建一个图片
        BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
        //3.得到图片
        //笔
        Graphics2D g = (Graphics2D)image.getGraphics();
        //设置图片的背景颜色
        g.setColor(Color.WHITE);
        g.fillRect(0,0,80,20);
        //4.给图片写数据
        g.setColor(Color.BLUE);
        g.setFont(new Font(null,Font.BOLD,20));
        g.drawString(makeNum(),0,20);

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

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

    }

    /**
     * 生成随机数
     */
    private String makeNum() {
        Random random = new Random();
        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 doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

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

在这里插入图片描述

void sendRedirect(String var1) throws IOException;
  • 常见场景:用户登录等
public class RedirectServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        /*sendRedirect()原理:*/
        //resp.setHeader("Location","/r/image");
        //resp.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
        resp.sendRedirect("/r/image");
    }
}

在这里插入图片描述

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

  • 相同点:

    • 页面都会实现跳转
  • 不同点:

    • 请求转发的时候,url不会产生变化;307
    • 重定向时,url地址栏会发生变化。302
  • 示例:

/**
 * @author wangjiao
 */
public class RequestTest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理请求
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        System.out.println(username + ":" + password);
        //重定向时注意路径问题,否则会404
        resp.sendRedirect("/r/success.jsp");
    }

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

web.xml

<servlet>
    <servlet-name>request</servlet-name>
    <servlet-class>com.ano.servlet.RequestTest</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>request</servlet-name>
    <url-pattern>/login</url-pattern>
</servlet-mapping>

index.jsp

<html>
<body>
<h2>Hello World!</h2>
<%--这里提交的路径,需要寻找到项目的路径--%>
<form action="login" method="get">
    用户名:<input type="text" name="username">
    密码:<input type="password" name="password">
    <input type="submit">
</form>
</body>
</html>

success.jsp

<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>Success</h1>
</body>
</html>

6.7 HttpServletRequest

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

在这里插入图片描述

6.7.1 获取前端传递的参数,请求转发
  • 获取前端参数的主要方法有以下4个,但常用的是前两个。
String getParameter(String var1);

String[] getParameterValues(String var1);

Enumeration<String> getParameterNames();

Map<String, String[]> getParameterMap();
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String[] hobbies = req.getParameterValues("hobbies");
        System.out.println(username);
        System.out.println(password);
        System.out.println(Arrays.toString(hobbies));

        resp.setCharacterEncoding("utf-8");
        //通过请求转发
        req.getRequestDispatcher(req.getContextPath() + "/success.jsp").forward(req,resp);
    }

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

web.xml

<servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.ano.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
</servlet-mapping>

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: wangjiao
  Date: 2021/8/5
  Time: 10:57
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
</head>
<body>
<h1>登录</h1>

<div style="text-align: left">
    <%--以post方式提交表单,提交到login请求--%>
    <form action="login" method="post">
        用户名:<input type="text" name="username"><br>
        密码:<input type="password" name="password"><br>
        爱好:
        <input type="checkbox" name="hobbies" value="女明星">女明星
        <input type="checkbox" name="hobbies" value="男明星">男明星
        <input type="checkbox" name="hobbies" value="唱歌">唱歌
        <input type="checkbox" name="hobbies" value="电影">电影
        <input type="submit">
    </form>
</div>

</body>
</html>

success.jsp

<%--
  Created by IntelliJ IDEA.
  User: wangjiao
  Date: 2021/8/5
  Time: 11:12
  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>
这篇关于JavaWeb-6-Servlet的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!