背景:
公司面向微信開發,可謂步步是坑,獲取完微信用戶信息之后,頁面停留在微信的頁面上,突然想到可以使用重定向把頁面跳轉回來,但是昨天屢屢失敗,因為重定向返回了json數據,實在百思不得其解,今天偶然看到一篇博客,記錄一下
原文鏈接:https://www.cnblogs.com/java-dyb/p/10912749.html
這里總結一下重定向的方法
(1)通過ModelAndView跳轉
@RequestMapping("alipayforward")
public ModelAndView alipayforward(HttpServletRequest req, HttpServletResponse resp) throws Exception {
String contNo =req.getParameter("contNo");
logger.info("訪問/downloadRequestElecCont.action");
String url = "redirect:http://baidu.com/downloadRequestElecCont.action?contNo="+contNo;
return new ModelAndView(url);
}
(2)通過HttpServletResponse跳轉
@RequestMapping("alipayforward/{contNo}")
public void alipayforward(@PathVariable("contNo") String contNo, HttpServletRequest req, HttpServletResponse resp) throws Exception {
//String contNo =req.getParameter("contNo"); //保單號
logger.info("訪問/downloadRequestElecCont.action");
resp.sendRedirect("http://baidu.com/downloadRequestElecCont.action?contNo="+contNo);
}
(3)通過redirect返回String類型跳轉
注意:這種方法不允許Spring控制器用@RestController注解,因為@RestController相當於類中的所有方法都標注了@ResponseBody,這些方法不會返回一個視圖,而是返回一個json對象,這樣的話只是在頁面上打印出字符串,而不跳轉。控制器用@Controller注解即可
@RequestMapping("alipayforward")
public String alipayforward(@RequestParam("contNo") String contNo, HttpServletRequest req, HttpServletResponse resp) throws Exception {
//String contNo =req.getParameter("contNo"); //保單號
logger.info("訪問/downloadRequestElecCont.action");
return "redirect:http://baidu.com/downloadRequestElecCont.action?contNo="+contNo;
}
下面是關於傳參問題
重定向傳參為get方式,如果傳參數較多,可以封裝到map或modelMap中
@RequestMapping(params = "action=alipayforward") public String alipayforward(Map modelMap){ modelMap.put("userName", "呵呵"); modelMap.put("password", "123456"); modelMap.put("age", "25"); return "redirect:http://localhost:8088/era/user/alipayforward4?modelMap="+modelMap; }
另一個項目用實體類對象接收
@RequestMapping("alipayforward4")
public void alipayforward4(User user, HttpServletRequest req) throws Exception {
System.out.println(user.getPassword());
String modelMap = req.getParameter("modelMap");
System.out.println(modelMap);
}
