栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

servlet重定向

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

servlet重定向

请求转发和重定向的区别


相同点:都能实现网页跳转
不同点:请求转发时,url地址栏不会发生变化;而重定向时url地址栏会变化

index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


<%--form表单请求的路径要加上项目路径,前端无法识别相对路径--%>

请登录!

用户名:
密码:

当提交form表单时,表单数据username和password会提交到 p a g e C o n t e x t . r e q u e s t . c o n t e x t P a t h / r e d i r e c t , 其 中 {pageContext.request.contextPath}/redirect, 其中 pageContext.request.contextPath/redirect,其中{pageContext.request.contextPath}是在jsp中嵌入java代码,找到当前项目的路径;整句话的意思是找到当前项目路径下的redirect请求。

servlet实现类Redirect
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 Redirect extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //重定向到指定页面时,一定要加上本项目的路径前缀,否则找不到指定资源
        resp.sendRedirect("/RedirectServlet_war/success.jsp");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println("用户名:"+username+"  "+"密码:"+password);
    }

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

该类主要实现重定向并获取表单数据。

web.xml


    redirectServlet
    Redirect

    
        redirectServlet
        /redirect
    


注册servlet实现类Redirect。

success.jsp
<%--
  Created by IntelliJ IDEA.
  User: zhmsky
  Date: 2021/10/17
  Time: 16:31
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    重定向页面
    

success

即重定向的指定页面。

梳理

整个项目的执行流程:运行这个servlet程序,浏览器显示index.jsp界面,通过form表单的提交将执行/redirect请求,而在web.xml中/redirect请求绑定Redirect实现类,进入其doGet方法,在doGet方法中,服务器响应重定向到success.jsp界面,并获取请求参数。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/333190.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号