【狂神说Java】JavaWeb入门到实战--Servlet详解

狂神视频地址

https://www.bilibili.com/video/BV12J411M7Sj?p=2


1.Servlet 简介

  Servlet 就是sun公司开发动态web的一门技术
 sun 在这些API 中提供了一个接口:Servlet,如果你想开发一个Servlet 程序,只需要完成两个步骤

  • 编写一个类,实现Servlet 接口
  • 把开发号好的Java类部署到服务器中

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


2.HelloServlet

Servlet 接口有两个默认的实现类:HttpServletGenericServlet

关于mavne 父子工程的理解
  父项目中会有

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

  子项目中会有

 <parent>
  <artifactId>servlet</artifactId>
  <groupId>cn.bloghut</groupId>
  <version>1.0-SNAPSHOT</version>
</parent>

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

子项目中的jar包 父项目不能使用

Zi extends Fu

编写一个普通类,实现Servlet接口,这里我们直接继承httpServlet

public class HelloServlet extends HttpServlet {
    
    
    
}

在这里插入图片描述

public class HelloServlet extends HttpServlet {
    
    

    //由于get或者post只是请求实现的不同的方法,可以相互调用,业务逻辑都一样

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

//        ServletOutputStream sos = resp.getOutputStream();
        PrintWriter writer = resp.getWriter();//响应流
        writer.println("hello,Servlet");

    }

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

3.编写Servlet的映射

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

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>cn.bloghut.servlet.HelloServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>
  
  
</web-app>

配置tomcat

测试
在这里插入图片描述

4.Servlet 原理

  Servlet 是由web服务器调用,web服务器在收到浏览器请求之后,会调用相关API对请求处理。

在这里插入图片描述

5.Mapping 问题:

  一个请求(Servlet)可以指定一个映射路径

<servlet>
  <servlet-name>hello</servlet-name>
  <servlet-class>cn.bloghut.servlet.HelloServlet</servlet-class>
</servlet>

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

  一个请求(Servlet)可以指定多个映射路径

<servlet>
  <servlet-name>hello</servlet-name>
  <servlet-class>cn.bloghut.servlet.HelloServlet</servlet-class>
</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-mapping>
  <servlet-name>hello</servlet-name>
  <url-pattern>/*</url-pattern>
</servlet-mapping>

指定一些后缀或者前缀

<servlet-mapping>
  <servlet-name>hello</servlet-name>
  <url-pattern>*.do</url-pattern>
</servlet-mapping>

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

6.ServletContext

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

6.1.共享数据

我在这个Servlet中保存的数据

在这里插入图片描述

放置数据的Servlet

/**
 * @author by 闲言
 * @classname HelloServlet
 * @description 放置数据
 * @date 2021/9/11 14:23
 */
public class setData extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        System.out.println("hello");

        ServletContext servletContext = this.getServletContext();

        String username = "闲言";//数据
        servletContext.setAttribute("username",username);//将一个数据保存在ServletContext中  名为:username  值为 闲言
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        doGet(req,resp);
    }
}


读取数据的Servlet
/**
 * @author by 闲言
 * @classname GetServlet
 * @description 获取数据
 * @date 2021/9/16 21:32
 */
public class GetData extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        ServletContext context = this.getServletContext();

        String username = (String) context.getAttribute("username");

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");
        PrintWriter writer = resp.getWriter();
        writer.write(username);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        doGet(req,resp);
    }
}

6.2获取初始化参数

<context-param>
    <param-name>url</param-name>
    <param-value>jdbc:mysql://localhost:3306/school</param-value>
</context-param>
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");
        
        System.out.println("url: "+url);
    }

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

6.3 请求转发

路径不会发生变化

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
    ServletContext context = this.getServletContext();
    //请求转发  /get 转发的路径
    RequestDispatcher dispatcher = context.getRequestDispatcher("/get");
    //调用forward 实现请求转发
    dispatcher.forward(req,resp);

}

在这里插入图片描述

6.4 读取配置文件

Properties
  在resources 目录下新建properties
  在java 目录下新建properties
发现:都被打包到了同一个路径下:classes,我们俗称这个路径为classpath;
思路:需要一个文件流

properties文件
username=xy123
password=123

代码

public class ServletDemo05 extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        InputStream stream = this.getServletContext().getResourceAsStream("/WEB-INF/classes/cn/bloghut/servlet/aa.properties");
//        InputStream stream = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
        Properties pt = new Properties();
        pt.load(stream);
        String username = pt.getProperty("username");
        String password = pt.getProperty("password");
        resp.getWriter().println(username+":"+password);
    }

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

效果
在这里插入图片描述

maven资源导出失败问题

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

6.5HttpServletResponse

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

  • 如果要获取客户端请求过来的参数:找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 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;
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_PROXY_AUTHENTICATION_REQUIRED = 407;
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;

下载文件

1.向浏览器输出消息
2.下载文件
  2.1.要获取文件的路径
  2.2下载的文件名是啥
  2.3设置想办法让浏览器能够支持下载我们需要的东西
  2.4获取下载文件的输入流
  2.创建缓冲区
  2.5获取OutputStream对象
  2.6将FileOutputStream流写入到buff缓冲区
  2.7使用OutputStream将缓冲区中的数据输出到客户端!

 @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //要获取文件的路径
//        String realPath = this.getServletContext().getRealPath("/1.png");
        String realPath = "G:\\JavaWeb\\狂\\servlet\\response-2\\target\\classes\\1.png";
        System.out.println("下载路径:" + realPath);
        //下载的文件名是啥
        String fileName = realPath.substring(realPath.lastIndexOf("//") + 1);
        //设置想办法让浏览器能够支持下载我们需要的东西
        //中文文件名URLEncoder.encode 编码,否则可能乱码
        resp.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName,"UTF-8"));
        //获取下载文件的输入流
        FileInputStream in = new FileInputStream(realPath);
        //创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
        //获取OutputStream对象
        ServletOutputStream out = resp.getOutputStream();
        //将FileOutputStream流写入到buff缓冲区
        //使用OutputStream将缓冲区中的数据输出到客户端!
        while ((len = in.read(buffer)) > 0) {
    
    
            out.write(buffer,0,len);
        }
        out.close();
        in.close();
    }

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

验证码功能

验证码怎么来的?
  1.前端实现
  2.后端实现,需要用到Java图片类,生成一个图片

public class ImageServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //如何让浏览器3秒自动刷新一次
        resp.setHeader("refresh", "3");

        //在内存中创建一个图片
        BufferedImage bufferedImage = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
        //得到图片
        Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics();//笔
        //设置背景颜色
        graphics.setColor(Color.white);
        graphics.fillRect(0, 0, 80, 20);
        //给图片写出去
        graphics.setColor(Color.BLUE);
        graphics.setFont(new Font(null,Font.BOLD,20));
        graphics.drawString(makeNumber(),0,20);

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

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

    }

    //生成随机数
    private String makeNumber() {
    
    
        Random random = new Random();

        String str = random.nextInt(9999) + "";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4 - str.length(); i++) {
    
    
            sb.append("0");
        }
        return   sb.toString() + str;
    }

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

实现重定向
在这里插入图片描述

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

  
  用户登录

public void sendRedirect(String location) throws IOException;

测试

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
    /**
     resp.setHeader("Location","/r2/img");
     resp.setStatus(302);
     */

    resp.sendRedirect("/r2/img");//重定

}

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

  • 相同点
    页面都会实现跳转
  • 不同点
    请求转发的时候,url不会产生变化
    重定向的时候,url地址栏会发生变化
@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:"+username+"   password:"+password);
    //重定向一定要注意:“路径问题”,否则404
    resp.sendRedirect("/r2/success.jsp");
}

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

  页面提交过来的HTTP请求包含了参数,放在URL里面了,tomcat自动解析封装在request对象里,再调用service方法,request可以根据键得到传过来的值


6.6HttpServletRequest

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

在这里插入图片描述

获取前端传递的参数
在这里插入图片描述

请求转发
  1.转发时"/“代表的是本应用程序的根目录 重定向时”/"代表的是webapps目录

  2.getRequestDispatcher分成两种,可以用request调用,也可以用getServletContext()调用 不同的是request.getRequestDispatcher(url)的url可以是相对路径也可以是绝对路径。而this.getServletContext().getRequestDispatcher(url)的url只能是绝对路径。

  转发是一个web应用内部的资源跳转

public class LoginServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //设置编码
        req.setCharacterEncoding("utf-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String[] hobbys = req.getParameterValues("hobbys");
        //后台接收中文乱码问题

        System.out.println(username+" : "+password+" :"+ Arrays.toString(hobbys));
        //通过请求转发
        //这里的 /  代表当前的web应用
        req.getRequestDispatcher("/success.jsp").forward(req,resp);

    }

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

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

  • 相同点
    页面都会实现跳转
  • 不同点
    请求转发的时候,url不会产生变化
    重定向的时候,url地址栏会发生变化

猜你喜欢

转载自blog.csdn.net/qq_42025798/article/details/120778094