Servlet

1、Servlet简介

(1)Tomcat工作机制

(2)什么是Servlet?

Java Servlet 是运行在 Web 服务器或应用服务器上的程序,它是作为来自 Web 浏览器或其他 HTTP 客户端的请求和 HTTP 服务器上的数据库或应用程序之间的中间层。

(3)编写Servlet

①创建一个HelloServlet继承HttpServlet,重写doGet和doPost方法(快捷键Alt+Ins),也就是看请求的方式是get还是post,然后用不同的处理方式来处理请求。

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

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

②在web.xml中配置HelloServlet (让浏览器发出的请求知道到达哪个servlet,也就是让tomcat将封装好的request找到对应的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>hello</servlet-name>
        <servlet-class>com.yu.servlet.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

配置之后,浏览器是如何通过我们配置的信息来找到对应的servlet的呢?

按照步骤,首先浏览器通过http://localhost:8080/s1/HelloServlet来找到web.xml中的url-pattern,这就是第一步,匹配到了url-pattern后,就会找到第二步servlet的名字hello,知道了名字,就可以通过servlet-name找到第三步,到了第三步,也就能够知道servlet的位置了。然后到其中找到对应的处理方式进行处理。

例图:

2、ServletContext

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

(1)共享数据

在一个Servlet中保存的数据,可以在另一个Servlet中获取到。

package com.yu.servlet;

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 HelloServlet extends HttpServlet {

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

        ServletContext context = this.getServletContext();
        String username = "jack"; //数据
        context.setAttribute("username", username); //将数据保存在ServletContext中,名字为username

        System.out.println("hello");
        
    }
}
package com.yu.servlet;

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;

//拿HelloServlet的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-8");
        resp.getWriter().println("名字:" + username);
    }
}

测试

①先访问http://localhost:8080/s2/hello
②再访问http://localhost:8080/s2/getc

结果

(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>gp</servlet-name>
        <servlet-class>com.yu.servlet.ServletDemo03</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>gp</servlet-name>
        <url-pattern>/gp</url-pattern>
    </servlet-mapping>

②创建一个ServletDemo03的java文件

package com.yu.servlet;

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 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 {
        super.doPost(req, resp);
    }
}

运行结果

(3)请求转发

①在web.xml文件中添加以下代码

servlet>
        <servlet-name>sd4</servlet-name>
        <servlet-class>com.yu.servlet.ServletDemo04</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>sd4</servlet-name>
        <url-pattern>/sd4</url-pattern>
    </servlet-mapping>

②创建一个ServletDemo04的java文件

package com.yu.servlet;

import javax.servlet.RequestDispatcher;
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 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("/gp"); //转发的请求路径
//        requestDispatcher.forward(req, resp); //调用forward实现请求转发
        context.getRequestDispatcher("/gp").forward(req, resp);
    }

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

运行结果


(4)读取资源文件

3、HttpServletResponse

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

  • 获取客户端请求过来的参数:HttpServletRequest
  • 给客户端响应一些信息:HttpServletResponse

(1)常用方法

(2)常见应用

①向浏览器输出信息

②下载文件

③实现重定向


重定向:一个web资源B收到客户端A的请求后,B会通知A去访问另一个web资源C。
resp.sendRedirect("s/img") //重定向
(例如:用户登录)

重定向和转发的区别?

相同点:

  • 页面都会实现跳转

不同点:

  • 请求转发时,url不会产生不会
  • 重定向时,url地址栏会发生变化

4、HttpServletRequest

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

    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.yu.servlet.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
</web-app>

②LoginServlet.java

package com.yu.servlet;

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.util.Arrays;

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("hobby");
        System.out.println(username+"--"+password);
        System.out.println(Arrays.toString(hobbies));
        System.out.println("=====================");
        //通过请求转发到登录成功界面
        req.getRequestDispatcher("/success.jsp").forward(req,resp);
    }

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

③index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
    <title>登录</title>
</head>
<body>
<h1>登录</h1>
<div>
    <!-- ${pageContext.request.contextPath} -->
    <form action="/login" method="get">
        用户名:<input type="text" name="username"> <br>
        密码:<input type="password" name="password"> <br>
        爱好:
        <input type="checkbox" name="hobby" value="女孩">女孩
        <input type="checkbox" name="hobby" value="唱歌">唱歌
        <input type="checkbox" name="hobby" value="打球">打球
        <input type="checkbox" name="hobby" value="电影">电影
        <br>
        <input type="submit">
    </form>
</div>
</body>
</html>

④跳转页面success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>登录成功!</h1>
</body>
</html>

运行结果


admin--123
[女孩, 电影]
=====================

(2)请求转发和重定向

参考链接:
https://www.cnblogs.com/whgk/p/6399262.html
https://blog.csdn.net/qq_19782019/article/details/80292110
https://www.bilibili.com/video/BV12J411M7Sj?p=10

posted @ 2020-10-23 21:52  yu10001  阅读(70)  评论(0编辑  收藏  举报