Java从后台重定向(redirect)到另一个项目的方法

(1)通过ModelAndView跳转

1 @RequestMapping("alipayforward")
2     public ModelAndView alipayforward(HttpServletRequest req, HttpServletResponse resp) throws Exception {
3         String contNo =req.getParameter("contNo");
4         logger.info("访问/downloadRequestElecCont.action");
5         String url = "redirect:http://baidu.com/downloadRequestElecCont.action?contNo="+contNo; 
6         return new ModelAndView(url);
7     }

(2)通过HttpServletResponse跳转

1 @RequestMapping("alipayforward/{contNo}")
2     public void alipayforward(@PathVariable("contNo") String contNo, HttpServletRequest req, HttpServletResponse resp) throws Exception {
3         //String contNo =req.getParameter("contNo"); //保单号
4         logger.info("访问/downloadRequestElecCont.action");
5         resp.sendRedirect("http://baidu.com/downloadRequestElecCont.action?contNo="+contNo);
6     }

(3)通过redirect返回String类型跳转

注意:这种方法不允许Spring控制器用@RestController注解,因为@RestController相当于类中的所有方法都标注了@ResponseBody,这些方法不会返回一个视图,而是返回一个json对象,这样的话只是在页面上打印出字符串,而不跳转。控制器用@Controller注解即可

1 @RequestMapping("alipayforward")
2     public String alipayforward(@RequestParam("contNo") String contNo, HttpServletRequest req, HttpServletResponse resp) throws Exception {
3         //String contNo =req.getParameter("contNo"); //保单号
4         logger.info("访问/downloadRequestElecCont.action");
5         return "redirect:http://baidu.com/downloadRequestElecCont.action?contNo="+contNo;
6     }

下面是关于传参问题

重定向传参为get方式,如果传参数较多,可以封装到map或modelMap中

1 @RequestMapping(params = "action=alipayforward")
2     public String alipayforward(Map modelMap){
3         modelMap.put("userName", "呵呵");
4         modelMap.put("password", "123456");
5         modelMap.put("age", "25");
6         return "redirect:http://localhost:8088/era/user/alipayforward4?modelMap="+modelMap;
7     }

另一个项目用实体类对象接收

1 @RequestMapping("alipayforward4")
2     public void alipayforward4(User user, HttpServletRequest req) throws Exception {
3         System.out.println(user.getPassword());
4         String modelMap = req.getParameter("modelMap");
5         System.out.println(modelMap);
6     }

 

 

posted @ 2019-05-23 16:35  一聚风云便是皇  阅读(45779)  评论(0编辑  收藏  举报