SpringMVC (九)重定向和转发

重定向和转发分为:重定向到页面,转发到页面,重定向到处理器方法和转发到处理器方法

1.重定向到页面

准备一个控制器

@Controller
public class RedirectAndForword {
    //重定向到页面
    @RequestMapping("/first")
    public String doFirst(Model model){
        model.addAttribute("msg","username");
        return "redirect:/success.jsp";
    }
}

配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="demo11RedirectAndForword"></context:component-scan>

    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--注解驱动--><!--<mvc:annotation-driven/>-->



</beans>

成功页面上:success.jsp

<%--
  Created by IntelliJ IDEA.
  User: mycom
  Date: 2018/3/26
  Time: 11:57
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  ${username}登录成功!
</body>
</html>

测试的时候直接方法处理器方法的ResultMapping就可以

2.转发到页面

//转发到页面
    @RequestMapping("/second")
    public String doSecond(Model model){
        /*model.addAttribute("msg","username");*/
        return "success";
    }

其他和第一种一样

3.重定向到处理器方法和转发到处理器方法

 //重定向到处理器
    @RequestMapping("/third")
    public String doThird(Model model){
        model.addAttribute("msg","username");
        return "redirect:/first";
    }

    //转发到处理器
    @RequestMapping("four")
    public String doFour(Model model){
        model.addAttribute("msg","username");
        return "forward:/second";
    }
原文地址:https://www.cnblogs.com/my-123/p/8671547.html