JavaWeb--1.Servlet

发布于:2024-05-04 ⋅ 阅读:(23) ⋅ 点赞:(0)

Servlet(基础)

1、配置依赖:

​ 在pom.xml文件中加入相关依赖

<dependencies>
        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>5.0.0</version>
            <scope>provided</scope>
        </dependency>
</dependencies>

2、Servlet的请求和返回的实现:

2.1、使用注解进行网页映射

​ Serlvet接口Sun公司有两个默认的实现类:HttpServlet,GenericServled,因此,在下面的代码中,通过使用HttpServlet来进行:

​ 首先,编写一个类对HttpServlet进行继承,然后重写doGET和doPOST方法。

@WebServlet("/hello")								//指定url的映射,类似于web.xml文件中注册url
public class FirstWeb extends HttpServlet  {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();			//获取一个响应流,然后通过这个对象中的write方法把内容响应给浏览器
        out.write("GET");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();			//获取一个响应流,然后通过这个对象中的write方法把内容响应给浏览器
        out.write("POST");
    }
}

2.2、通过web.xml注册的方式进行映射

  
      <!--注册Servlet-->
      <servlet>
          <servlet-name>hello</servlet-name>							<!--注册的映射的名字-->
          <servlet-class>com.firstweb.demo01.FirstWeb</servlet-class>  	<!--指定映射的类-->
      </servlet>
      <!--Servlet的请求路径-->
      <servlet-mapping>
          <servlet-name>hello</servlet-name>							<!--注册的映射的名字-->
          <url-pattern>/hello</url-pattern>								<!--注册的映射的url-->
      </servlet-mapping>

3、ServletContext

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

3.1、共享数据:

​ 首先,第一个类作为目标类,保存一个数据name到ServlertContext中:

@WebServlet("/hello")
public class FirstWeb extends HttpServlet  {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();

        ServletContext context = this.getServletContext();

        String name = "Bob";
        context.setAttribute("name",name);          //将一个数据保存在了ServletContext中,名字为:uname 。值 name

    }
}

​ 然后,第二个类作为测试类,写入如下代码,来获取ServletContext的内容:

@WebServlet("/context")
public class ContextTest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String name = (String) context.getAttribute("name");

        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().print("名字"+name);
    }
}

​ 随后,先访问目标类的url,使得第一个类被实例化成一个对象(在第一次访问类之前,第一个类没有进行实例化,所以如果直接访问第二个类的时候的结果name的值成了null),之后访问第二个类对应的url,可以看到输出结果出现了第一个类中的name的值。

3.2、获取初始化参数:

​ 首先是设置一个初始化的参数,在web.xml文件中加入如下标签:

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

​ 然后如下代码,可以获得到初始化的参数。

@WebServlet("/context")
public class ContextTest 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().print("url="+url);
    }
}

3.3、请求转发:

3.3.1、请求转发与重定向:
  • 请求转发是服务器端跳转,它只产生一次请求,客户端请求到达服务器之后中会发生一次转发,之后服务器才将结果发送到客户端。
  • 重定向是客户端跳转,它会产生两次请求,首先发一个response到浏览器,浏览器收到这个response后再发一个requeset到服务器,服务器接收后发新的response给浏览器。

在这里插入图片描述

3.3.2、相关代码:
@WebServlet("/context")
public class ContextTest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        System.out.println("进入了context");
        //RequestDispatcher requestDispatcher = context.getRequestDispatcher("/hello"); //转发的请求路径
        //requestDispatcher.forward(req,resp); //调用forward实现请求转发;
        context.getRequestDispatcher("/hello").forward(req,resp);
    }
}

​ 对于context这个路径的类帮助请求了hello这个路径,然后hello这个路径的类把响应交给了context这个路径的类,最后响应给了浏览器。

3.4、读取资源文件

  • 在java目录下新建properties
  • 在resources目录下新建properties

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

​ 思路:需要一个文件流

username=root12312
password=zxczxczxc
public class ServletDemo05 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/com/kuang/servlet/aa.properties");

        Properties prop = new Properties();
        prop.load(is);
        String user = prop.getProperty("username");
        String pwd = prop.getProperty("password");

        resp.getWriter().print(user+":"+pwd);

    }

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

4、HttpServletResponse:

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

  • 如果要获取客户端请求过来的参数:找HttpServletRequest
  • 如果要给客户端响应一些信息:找HttpServletResponse4

4.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;

4.2、下载文件:

  1. 向浏览器输出消息 (前面一直在讲,就不说了)
  2. 下载文件
    1. 要获取下载文件的路径。
    2. 下载的文件名是啥?
    3. 想办法设置让浏览器能够支持下载我们需要的东西。
    4. 获取下载文件的输入流。
    5. 创建缓冲区。
    6. 获取OutputStream对象。
    7. 将FileOutputStream流写入到buffer缓冲区。
    8. 使用OutputStream将缓冲区中的数据输出到客户端!
  • 创建一个新的Maven项目:response
  • 创建结构目录
  • 改变web.xml的代码为最新版
  • 创建包com.yang.servlet
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.获取下载文件的路径
        String realPath = "C:\\Users\\20820\\Downloads\\bg.jpg";
        System.out.println("下载文件的路径: " + realPath);
        //2.下载的文件名
        String fileName = realPath.substring(realPath.lastIndexOf("\\")+1);
        //3.设置浏览器支持(Content-Disposition)下载我们要的东西,。中文名称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 将FileInputStream写入到buffer,使用OutputStream将缓冲区的数据输出到客户端
        while ((len = in.read(buffer)) >0) {
            out.write(buffer,0,len);
        }
        in.close();
        out.close();
    }

4.3、验证码功能:

​ 生成验证码的两种方式:

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

新建一个类ImageServlet进行测试验证码图片

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

        //在内存中创建一个图片  宽:80,高:20
        BufferedImage Image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);

        //得到图片,创建画笔
        Graphics2D graphics =(Graphics2D) Image.getGraphics();

        //设置图片的背景颜色  从(0,0) 到(80,20)
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0,0,80,20); //填充颜色

        //给图片中写入数据
        graphics.setColor(Color.black);
        graphics.setFont(new Font(null,Font.BOLD,20));
        graphics.drawString(makeNum(),0,20); //画一个字符串

        //告诉浏览器以图片的方式打开
        resp.setContentType("image/jpeg");

        //浏览器中有缓存,不让浏览器缓存
        resp.setDateHeader("expires",-1); //-1:表示不缓存
        resp.setHeader("Cache-Control","no-cache");
        resp.setHeader("Pragma","no-cache");

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

    }

    //生成随机数
    private String makeNum(){
        Random random = new Random();
        String num = random.nextInt(9999999)+""; //字符串
        //创建对象,填充数字不足的位置为0  ,stringBuffer:可变字符串
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 7-num.length(); i++) {
            stringBuffer.append("0");
        }
        num = stringBuffer.toString()+num;
        return num;
    }

4.4、实现重定向:

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

常见场景:

  • 用户登录
void sendRedirect(String var1) throws IOException;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.sendRedirect("/demo01_war/image"); //重定向

    /*
     * resp.sendRedirect("/response/image");可以拆分为:
     *   resp.setHeader("Location","/response/image");
     *   resp.setStatus(302);
     * */
}

4.5、测试登陆用户重定向:

  • 新建一个类RedirectTest类
  • 在web.xml中进行RedirectTest类Servlet的注册
  • 在页面index.jsp中进行html代码编写
  • 新建一个页面success.jsp

新建一个用来处理重定向的类

@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("/demo01_war/success.jsp");
    }

修改index.jsp文件:

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

导入jsp的包:

<dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.1</version>
</dependency>

success.jsp:

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

5、HttpServletRequest:

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

​ 获取前端传递的参数 请求转发

获取参数方法:

  • getParameter(String s)
  • getParameterMap() 很少用
  • getParameterNames() 很少用
  • getParameterValues(String s)

包内新建一个类LoginServlet:

    @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[] hobbies = req.getParameterValues("hobbies");

        System.out.println("======================");
        System.out.println(username);
        System.out.println(password);
        //输出数组:Arrays.toString(hobbies)
        System.out.println(Arrays.toString(hobbies));
        System.out.println("======================");

        //输出对应项目的路径
        System.out.println(req.getContextPath());

        //通过请求转发
        //这里的 / 代表当前web应用
        req.getRequestDispatcher("/success.jsp").forward(req,resp);

    }

在index.jsp中编写代码

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

<div style="text-align: center">
    <%--    这里表单提交的方式:以post方式提交表单,提交到login页面--%>
    <form action="${pageContext.request.contextPath}/log" method="get">
        用户名:<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="checkbox" name="hobbies" value="打网球">打网球
        <br>
        <input type="submit">
    </form>
</div>
</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>

name=“hobbies” value=“学习”>学习
旅游
听歌
打羽毛球
打网球




新建一个success.jsp页面

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

网站公告

今日签到

点亮在社区的每一天
去签到