SpringMVC的拦截器与Controller里return "redirect:XXX"的问题

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

自己在网上也找到遇到同样问题的两篇文章:

http://q.cnblogs.com/q/62314/

http://stackoverflow.com/questions/9786028/spring-mvc-interceptor-addobject/9786096#9786096

下面分享一下个人对这个问题的解决办法,同时也请有更好解决方法的高手不吝指教!

首先是controller层:(这是点击页面“注册”按钮,表单提交的action)

// 保存到数据库
	@RequestMapping(value = "doRegister", method = RequestMethod.POST)
	public RedirectView createUser(@ModelAttribute("user") User user, RedirectAttributes redirectAttributes,
			HttpServletResponse response) {

		// 模拟数据库保存
		System.out.println(user.getUsername() + "   is saved!");
		redirectAttributes.addAttribute("username", user.getUsername());
		return new RedirectView("{username}");
	}


    // 注册成功后展现用户主页
    @RequestMapping(value = "{username}", method = RequestMethod.GET)
    public String showUserHome(@PathVariable String username, Model model, HttpServletRequest request) {
             model.addAttribute(username);
        return request.getAttribute(Keys.SKIN_DIR_NAME) + "home";
    }
其次是拦截器:(加入一些全局配置,如基本的站点信息)
@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2,
			ModelAndView modelAndView) throws Exception {

		final Map model = modelAndView.getModel();

		if (!(modelAndView.getView() instanceof RedirectView)) {
			model.put("param1", "value1");
			model.put("param2", "value2");
			model.put("param3", "value3");
		} else {
			//进行其它操作
		}

	}



关键点是org.springframework.web.servlet.view.RedirectView。

转载于:https://my.oschina.net/u/138589/blog/317210

你可能感兴趣的:(SpringMVC的拦截器与Controller里return "redirect:XXX"的问题)