JAVA重定向的几种方法

1.通过ModelAndView跳转

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

2.通过HttpServletResponse跳转

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

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

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

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

@RequestMapping(params = "action=redirect")
public String redirect(Map modelMap){
  modelMap.put("userName", "呵呵");
  modelMap.put("password", "123456");
  modelMap.put("age", "25");
  return "redirect:http://localhost:8088/era/user/alipayforward4?modelMap="+modelMap;
}
@RequestMapping("redirect")
public void redirect(User user, HttpServletRequest req) throws Exception {
  System.out.println(user.getPassword());
  String modelMap = req.getParameter("modelMap");
  System.out.println(modelMap);
}

你可能感兴趣的:(持续输出,java)