第一个Respose重定向

依旧在我们的maven项目中,上一章中有具体的Maven配置

本次主要就是使用response重定向我们的网页,了解response在接收请求后如何做出响应

首先在我们的java源码文件夹下创建一个包和类,(上一张中有具体的配置,就能明白为啥java是源码文件)
在这里插入图片描述


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 FirstResponse extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("进入doGet请求");
        //获取request请求中的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //在控制台打印一下
         System.out.println(username + ":" + password);
        //重定向到一个网页
        resp.sendRedirect("Success.jsp");
    }

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

在我们的web.xml中注册我们的servlet,注册的原因:我们这个浏览器访问的是我们的服务器,因此我们需要把我们的servlet注册到我们的服务器中,并且在注册的同时,我们需要把路径配置,以便于我们的浏览器在我们的服务器中找到我们的servlet。
xml配置
在这里插入图片描述

<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>first</servlet-name>
        <servlet-class>Responseqaq.FirstResponse</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>first</servlet-name>
        <url-pattern>/first</url-pattern>
    </servlet-mapping>

</web-app>

我们写一个index.jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>haha</title>
</head>
<body>
<form action="/RedirectAction" method="get">
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="password">
    <br>
    <input type="submit" value="登录">
</form>
</body>
</html>

再写一个Success.jsp界面

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

最后在浏览器中输入:http://localhost:8888/First.jsp(可以先运行index.jsp页面,然后以输入First.jsp),
在这里插入图片描述
点击登录后,我们可以发现跳转界面
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200908174341741.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3poZW5naHVpc2hlbmdx,size_16,color_FFFFFF,t_70#pic_center

猜你喜欢

转载自blog.csdn.net/zhenghuishengq/article/details/108472281
今日推荐