一起学习SSM框架之SpringMVC(二)

it2024-11-06  8

SpringMVC

跳转1.转发2.重定向3.跳转细节 传值1.Request和Session2.JSP中取值3.Model4.ModelAndView5.@SessionAttributes和SessionStatus

跳转

跳转关键字 forward: redirect:

1.转发

@Controller @RequestMapping("/jump") public class ForwardController { @RequestMapping("/test1") public String test1(){ System.out.println("test1"); return "forward:/hello.jsp"; } @RequestMapping("/test2") public String test2(){ System.out.println("test2"); return "forward:/jump/test1"; //绝对路径 } @RequestMapping("/test3") public String test3(){ System.out.println("test3"); return "forward:test1"; //相对路径 }

2.重定向

@RequestMapping("/test4") public String test4(){ System.out.println("test4"); return "redirect:/hello.jsp"; } @RequestMapping("/test5") public String test5(){ System.out.println("test5"); return "redirect:/jump/test4";//绝对路径 } @RequestMapping("/test6") public String test6(){ System.out.println("test6"); return "redirect:test4";//相对路径 }

3.跳转细节

1.增删改操作,为了防止请求重复提交,选择重定向redirect2.查询操作,选择转发Forward

传值

1.Request和Session

public class DataController { @RequestMapping("/test1") public String test1(HttpServletRequest httpServletRequest, HttpSession httpSession){ System.out.println("test1"); httpServletRequest.setAttribute("name","张三"); httpSession.setAttribute("age","23"); return "data"; }

2.JSP中取值

在jsp用EL表达式,取值就可以 requestScope sessionScope

<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> name:${requestScope.name}<br> age:${sessionScope.age}<br> name:${requestScope.name} </body> </html>

3.Model

// model中的数据,会在v渲染之前,将数据复制一份给request @RequestMapping("/test2") public String test2(Model model){ System.out.println("test2"); model.addAttribute("name","李四"); return "data"; }

4.ModelAndView

// 可以集中管理 跳转和数据 @RequestMapping("/test4") public ModelAndView test4(){ ModelAndView modelAndView=new ModelAndView(); modelAndView.setViewName("forward:/hello.jsp"); modelAndView.addObject("claz","123"); return modelAndView; }

5.@SessionAttributes和SessionStatus

@SessionAttributes(names = {“city”,“street”}) model中的city,street数据会存入session

@RequestMapping("/test5") public String test5(Model model){ model.addAttribute("city","南京"); model.addAttribute("street","123"); return "data"; }

SessionStatus

@RequestMapping("/test3") public String test3(SessionStatus sessionStatus){ // 清空所有 通过model存入的session sessionStatus.setComplete();; return "data"; }
最新回复(0)