這篇文章主要介紹了詳解Java從後台重定向(redirect)到另一個專案的方法,非常具有實用價值,需要的朋友可以參考下
(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); }
以上是Java從後台redirect到另一個專案的實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!