Spring MVC中使用Controller如何进行重定向

目录
  • Controller如何进行重定向
    • 本人知道的有两种方式
      • 注意
    • 具体看demo理解这两种方式的实现
  • controller请求转发,重定向
    • 了解
    • 转发forward
    • 重定向redirect

Controller如何进行重定向

Spring MVC中进行重定向

本人知道的有两种方式

方法返回的URI(相对路径)中加上"redirect:"前缀,声明要重定向到该地址

使用HttpServletResponse对象进行重定向

注意

"redirect:"后面跟着的是"/"和不跟着"/"是不一样的:

1) "redirect:"后面跟着"/": 说明该URI是相对于项目的Context ROOT的相对路径

2) "redirect:"后面没有跟着"/": 说明该URI是相对于当前路径

具体看demo理解这两种方式的实现

RedirectURLController.java:

package edu.mvcdemo.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import edu.mvcdemo.utils.StringUtils;

/**
 * @编写人: yh.zeng
 * @编写时间:2017-7-13 上午9:10:29
 * @文件描述: Spring MVC重定向demo
 */
@Controller
@Scope("singleton") //只实例化一个bean对象(即每次请求都使用同一个bean对象),默认是singleton
@RequestMapping("/redirect")
public class RedirectURLController {
	private Logger logger = Logger.getLogger(RedirectURLController.class);	

	/**
	 * 方式一:方法返回的URI(相对路径)中加上"redirect:"前缀,声明要重定向到该地址
	 *        "redirect:"后面跟着的是"/"和不跟着"/"是不一样的:
	 *        1) "redirect:"后面跟着"/": 说明该URI是相对于项目的Context ROOT的相对路径
	 *        2) "redirect:"后面没有跟着"/": 说明该URI是相对于当前路径
	 * @return
	 */
	@RequestMapping(value="/demo1", method=RequestMethod.GET)
	private String testRedirect1(){
		//注意:"redirect:/hello/world" 和 "redirect:hello/world"这两种写法是不一样的!!
		//     本案例中:
		//     "redirect:/hello/world" 重定向到的URL路径为:协议://服务器IP或服务器主机名:端口号/项目的Context ROOT/hello/world
		//     "redirect:hello/world"  重定向到的URL路径为:协议://服务器IP或服务器主机名:端口号/项目的Context ROOT/redirect/hello/world
		return "redirect:/hello/world";
	}

	/**
	 * 方式二:使用HttpServletResponse对象进行重定向,HttpServletResponse对象通过方法入参传入
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="/demo2", method=RequestMethod.GET)
	private void testRedirect2(HttpServletRequest request ,HttpServletResponse response){
        String pathPrefix = StringUtils.getWebContextPath(request);
        String redirectURL = pathPrefix + "/hello/world";
		logger.info(redirectURL);
		try {
			response.sendRedirect(redirectURL);
		} catch (IOException e) {
			logger.error(StringUtils.getExceptionMessage(e));
		}
	}
}

StringUtils.java:

package edu.mvcdemo.utils;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.http.HttpServletRequest;
/**
 * @编写人: yh.zeng
 * @编写时间:2017-7-9 下午2:56:21
 * @文件描述: todo
 */
public class StringUtils {
    /**
     * 获取异常信息
     *
     * @param e
     * @return
     */
    public static String getExceptionMessage(Exception e) {
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);
        e.printStackTrace(printWriter);
        return stringWriter.toString();
    }    

    /**
     * 返回web项目的context path,格式 为:协议://服务器IP或服务器主机名:端口号/项目的Context ROOT
     * @param request
     * @return
     */
    public static String getWebContextPath(HttpServletRequest request){
		StringBuilder webContextPathBuilder = new StringBuilder();
		webContextPathBuilder.append(request.getScheme())
		                     .append("://")
		                     .append(request.getServerName())
		                     .append(":")
		                     .append(request.getServerPort())
		                     .append(request.getContextPath());
		return webContextPathBuilder.toString();
    }
}

效果:

页面输入 http://localhost:8080/MavenSpringMvcDemo/redirect/demo1 或 http://localhost:8080/MavenSpringMvcDemo/redirect/demo2 都会重定向到http://localhost:8080/MavenSpringMvcDemo/hello/world

controller请求转发,重定向

了解

转发(forward):浏览器地址不会改变,始终是同一个请求。

重定向(sendRedirect):浏览器地址会改变,是两个请求。

转发forward

有异常抛出就好了:

跳首页:浏览器的url地址不变.可能会找不到静态文件:

  @GetMapping(value = "/index")
    @ApiOperation("首页")
    public void index(HttpServletRequest request, HttpServletResponse response)  throws Exception  {
   request.getRequestDispatcher("/index.html").forward(request, response);
   }

重定向redirect

controller中返回值为void

 @GetMapping(value = "/index")
    @ApiOperation("首页")
    public void index(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.sendRedirect("/index.html");
    }

第三种方式:controller中返回值为ModelAndView

return new ModelAndView(“redirect:/toList”);

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • controller接口跳转到另一个controller接口的实现

    controller接口跳转到另一个controller接口 @RestController @RequestMapping("/aaa") public class TestController{ @RequestMapping("/test1") public ModelAndView test1(HttpServletResponse response) { ModelAndView view = new ModelAndView(); view.setVie

  • Spring Boot项目@RestController使用重定向redirect方式

    目录 Spring Boot @RestController重定向redirect 解决方法如下 @RestController 注释下的重定向探讨 背景 那么springmvc内部的逻辑是如何走的呢? 下面是springmvc 默认的15种HandlerMethodReturnValueHandler Spring Boot @RestController重定向redirect Spring MVC项目中页面重定向一般使用return "redirect:/other/controller/&

  • springboot 如何重定向redirect 并隐藏参数

    目录 springboot 重定向redirect 并隐藏参数 1.全局异常处理方法 2.重定向方法 springboot redirect 传参问题 具体案例 springboot 重定向redirect 并隐藏参数 在做全局异常处理的时候,碰到重定向到全局错误页面 所谓隐藏参数无非是把参数放到了session中,再重定向后将该值清除 1.全局异常处理方法 @ExceptionHandler(value = Exception.class) public ModelAndView except

  • Spring MVC中使用Controller如何进行重定向

    目录 Controller如何进行重定向 本人知道的有两种方式 注意 具体看demo理解这两种方式的实现 controller请求转发,重定向 了解 转发forward 重定向redirect Controller如何进行重定向 Spring MVC中进行重定向 本人知道的有两种方式 方法返回的URI(相对路径)中加上"redirect:"前缀,声明要重定向到该地址 使用HttpServletResponse对象进行重定向 注意 "redirect:"后面跟着的是&

  • Spring MVC中的Controller进行单元测试的实现

    目录 导入静态工具方法 初始化MockMvc 执行测试 测试GET接口 测试POST接口 测试文件上传 定义预期结果 写在最后 对Controller进行单元测试是Spring框架原生就支持的能力,它可以模拟HTTP客户端发起对服务地址的请求,可以不用借助于诸如Postman这样的外部工具就能完成对接口的测试.具体来讲,是由Spring框架中的spring-test模块提供的实现,详见MockMvc. 如下将详细阐述如何使用MockMvc测试框架实现对“Spring Controller”进行单

  • 详解Http请求中Content-Type讲解以及在Spring MVC中的应用

    详解Http请求中Content-Type讲解以及在Spring MVC中的应用 引言: 在Http请求中,我们每天都在使用Content-type来指定不同格式的请求信息,但是却很少有人去全面了解content-type中允许的值有多少,这里将讲解Content-Type的可用值,以及在spring MVC中如何使用它们来映射请求信息. 1.  Content-Type MediaType,即是Internet Media Type,互联网媒体类型:也叫做MIME类型,在Http协议消息头中,

  • spring mvc中的@ModelAttribute注解示例介绍

    前言 本文介绍在spring mvc中非常重要的注解@ModelAttribute.这个注解可以用在方法参数上,或是方法声明上.这个注解的主要作用是绑定request或是form参数到模型对象.可以使用保存在request或session中的对象来组装模型对象.注意,被@ModelAttribute注解的方法会在controller方法(@RequestMapping注解的)之前执行.因为模型对象要先于controller方法之前创建. 请看下面的例子 ModelAttributeExample

  • Spring MVC中Ajax实现二级联动的简单实例

    今天写项目遇到了二级联动,期间遇到点问题,写个博客记录一下. 后台Controller: @RequestMapping("/faultType") @ResponseBody public Map<String,Object> faultType(int id,HttpServletRequest request)throws IOException { String ReturnMessage = ""; //获取所有子类故障类型 List<F

  • spring mvc中的@PathVariable获得请求url中的动态参数

    spring mvc中的@PathVariable是用来获得请求url中的动态参数的,十分方便,复习下: @Controller public class TestController { @RequestMapping(value="/user/{userId}/roles/{roleId}",method = RequestMethod.GET) public String getLogin(@PathVariable("userId") String user

  • spring mvc中注解@ModelAttribute的妙用分享

    前言 本文主要给大家介绍了关于spring mvc注解@ModelAttribute妙用的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧. 在Spring mvc中,注解@ModelAttribute是一个非常常用的注解,其功能主要在两方面: 运用在参数上,会将客户端传递过来的参数按名称注入到指定对象中,并且会将这个对象自动加入ModelMap中,便于View层使用: 运用在方法上,会在每一个@RequestMapping标注的方法前执行,如果有返回值,则自动将该返回值

  • Spring MVC中基于自定义Editor的表单数据处理技巧分享

    面向对象的编程方式极大地方便了程序员在管理数据上所花费的精力.在基于Spring MVC的Web开发过程当中,可以通过对象映射的方式来管理表单提交上来的数据,而不用去一个一个地从request中提取出来.另外,这一功能还支持基本数据类型的映射.例如in.long.float等等.这样我们就能从传统单一的String类型中解脱出来.然而,应用是灵活的.我们对数据的需求是千变万化的.有些时候我们需要对表单的数据进行兼容处理. 例如日期格式的兼容: 中国的日期标注习惯采用yyyy-MM-dd格式,欧美

  • Spring MVC中处理ajax请求的跨域问题与注意事项详解

     前言 有时候前后台做数据交互,会遇到烦人的跨域请求问题,如果你还是一枚编程小白来说,无疑来说是很痛苦的事. 当然网上也肯定会有一些解决方法.但自身实力有限,不一定会看的懂,能把问题解决了.所以下面这篇文章就来给大家总结介绍在Spring MVC中处理ajax请求的跨域问题与一些注意事项,话不多说了,来一起看看详细的介绍吧. 为何跨域 简单的说即为浏览器限制访问A站点下的js代码对B站点下的url进行ajax请求.假如当前域名是www.abc.com,那么在当前环境中运行的js代码,出于安全考虑

  • 详解spring mvc中url-pattern的写法

    1.设置url-pattern为*.do(最为常见的方式) 只要你的请求url中包含配置的url-pattern,该url就可以到达DispatcherServlet.当然这里业内通常都将url-pattern配置为*.do的方式,所以你最好也这么去做. 2.设置url-pattern为/*(这种方式是很不好) 如果将url-pattern设置为/*之后,web项目中的jsp都不能访问了会报出404的错误,这是因为DispatcherServlet会将向JSP页面的跳转请求也当作是一个普通的 C

随机推荐