springmvc教程-返回字符串实现转发、重定向页面

介绍

在 Controller 方法中,通过 返回 字符串类型 ,实现 转发、重定向 页面

返回 视图名

返回 视图名 实现 转发(forward)
该视图名 是 普通字符串 ,会 当成页面名字,然后通过 视图解析器 ,拼装 前缀 和 后缀,就得到 完整的页面路径,然后进行 转发(forward)

本文根据 springmvc教程-第一个工程(idea) 整理

Controller

package top.malaoshi.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloCtrl {
    @RequestMapping("/hello")
    public String hello(){
        return "hello";
    }
}

springmvc.xml

完整配置如下:

<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="top.malaoshi.controller"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

说明

Controller返回的字符串,视图解析配置的 前缀、后缀,最终文件路径为: /webapp/hello.jsp,然后进行 转发(forward方式)

返回字符串以 forward: 开头

Controller方法返回 字符串的开头 是 forward:,会 转发(forward)页面,但是 视图解析器不起作用,所以要写 页面全路径

Controller

package top.malaoshi.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloCtrl {
    @RequestMapping("/hello")
    public String hello(){
        return "forward:/hello.jsp";
    }
}

注意: 视图解析器不起作用,所以要写 页面全路径

返回字符串以 redirect: 开头

返回字符串以 redirect: 开头 实现 重定向(redirect)

Controller方法返回 字符串的开头 是:redirect:,表示重定向。视图解析器不起作用,所以要写 页面全路径

例子1

@RequestMapping("/query")
public String query()  {
    return "redirect:http://www.baidu.com";
}

例子2

@RequestMapping("/query")
public String query()  {
    return "redirect:/index.jsp";
}

这种方式重定向,/ 表示 http://ip:port/context/index.jsp 不需要加上下文,springmvc 会自动添加


原文出处:/show_1IX5DiDzAQC.html