Spring MVC中Controller如何进行重定向

24 篇文章 0 订阅
24 篇文章 0 订阅

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


 

  • 6
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring MVC ,可以使用重定向和转发来进行请求的跳转。下面是设定重定向和转发的几种方式: 1. 重定向: - 使用 `RedirectView` 类:可以在控制器方法返回一个 `RedirectView` 对象,设置重定向的目标 URL。 - 使用 `RedirectAttributes` 类:可以在控制器方法重定向的目标 URL 添加到 `RedirectAttributes` 对象,并使用 `redirect:` 前缀来指示重定向。 2. 转发: - 使用 `ModelAndView` 类:可以在控制器方法返回一个 `ModelAndView` 对象,设置转发的视图名称。 - 使用 `forward:` 前缀:可以在控制器方法使用 `return "forward:/path"` 的方式来指示转发到指定的路径。 下面是一个示例,展示如何在控制器方法设定重定向和转发: ```java @Controller public class MyController { @GetMapping("/redirect") public RedirectView redirectToUrl() { RedirectView redirectView = new RedirectView(); redirectView.setUrl("https://www.example.com"); return redirectView; } @GetMapping("/redirectWithAttributes") public String redirectWithAttributes(RedirectAttributes attributes) { attributes.addAttribute("param", "value"); return "redirect:/targetUrl"; } @GetMapping("/forward") public ModelAndView forwardToView() { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("forward:/targetView"); return modelAndView; } } ``` 上述代码,`/redirect` 路径的请求会被重定向到 `https://www.example.com`,`/redirectWithAttributes` 路径的请求会带着参数重定向到 `/targetUrl`,`/forward` 路径的请求会被转发到 `targetView` 视图。 需要注意的是,在设定重定向和转发时,可以使用绝对路径或相对路径,具体根据需求来确定。同时,还可以在路径使用占位符和路径参数来实现动态的跳转。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值