Java重定向(redirect)跳转页面

时间:2024-02-29 20:18:44

背景:

  公司面向微信开发,可谓步步是坑,获取完微信用户信息之后,页面停留在微信的页面上,突然想到可以使用重定向把页面跳转回来,但是昨天屡屡失败,因为重定向返回了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);
     }