import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class Params { public Params() { System.out.println("costructor...."); } /* * 方式1:通过注入httpServletRequest进行参数设置,并跟随返回的视图传递到页面 */ @RequestMapping("/ppp1") public String param(HttpServletRequest req) { req.setAttribute("msg", "fuck you"); return "/WEB-INF/hello.jsp"; } /* * 方式2:通过原始的modelAndView设置模型数据和视图名称,,并返回 */ @RequestMapping("/ppp2") public ModelAndView param2() { ModelAndView mav = new ModelAndView(); User user = new User(); user.setName("俩后"); mav.addObject("user", user); mav.setViewName("/WEB-INF/hello.jsp"); mav.addObject("msg", "dick"); return mav; } /* * 方式3:通过向方法注入形参Model类的对象,该对象由spring自动功能创建添加,model对象添加模型数据 * 而返回的字符串负责指向要跳转的视图名称 */ @RequestMapping("/ppp3") public String param3(Model model) { User user = new User(); user.setName("俩后的"); model.addAttribute("user", user); model.addAttribute("msg", "suck your dick"); return "/WEB-INF/hello.jsp"; } /* * 方式4:直接将返回值作为模型对象返回 * 此时,视图名就是该方法的访问地址,即/ppp4, */ @RequestMapping("/ppp4") public User param4() { User user = new User(); user.setName("俩后的"); return user; } }
上面四种方式都是将数据放在request作用域中的,通过${requestScope.xxx}可以取出数据
时间: 2024-10-12 07:29:37