@RequestMapping("/t2") public String test2(){ return "/WEB-INF/views/test.jsp"; }
@RequestMapping("/t2") public String test2(){ return "forward:/WEB-INF/views/test.jsp"; }
return:默認轉發前端
@RequestMapping("/t2") public String test2(){ return "test"; }
重定向不須要視圖解析器,本質就是從新請求一個新東方,因此只須要注意路徑問題!java
能夠重定向到另一個請求實現;web
@RequestMapping("/t4") public String test4(){ return "redirect:/index.jsp"; }
提交數據: http://localhost:8080/hello?name=zhangsanspring
處理方法:app
@RequestMapping("/param") public String test(String name){ System.out.println(name); return "hello"; }
提交數據: http://localhost:8080/hello?username=zhangsanjsp
處理方法:post
//@RequestParam("username") : username:提交的域的名稱 . @RequestMapping("/hello") public String hello(@RequestParam("username") String name){ System.out.println(name); return "hello"; }
實體類User測試
package com.star.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class User { private String username; private int age; private String sex; }
處理方法:url
@RequestMapping("/user") public String test(User user){ System.out.println(user); return "hello"; }
注意:若是使用對象的話,前端傳遞的參數名和對象名必須一致,不然就是null。3d
public class ControllerTest1 implements Controller { public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { //返回一個模型視圖對象 ModelAndView mv = new ModelAndView(); mv.addObject("msg","ControllerTest1"); mv.setViewName("hello"); return mv; } }
@RequestMapping("/param") public String test(@RequestParam() String name, ModelMap model){ System.out.println(name); model.addAttribute("username",name); return "hello"; }
@RequestMapping("/param") public String test(@RequestParam() String name, Model model){ System.out.println(name); model.addAttribute("username",name); return "hello"; }
Model:只有幾個方法只適用於儲存數據,簡化了新手對於Model對象的操做和理解;
ModelMap:繼承了LinkedMap,除了實現自身的一些方法,一樣的繼承LinkedMao的方法和特性;
ModelAndView:能夠在儲存數據的同時,能夠進行設置返回的邏輯視圖,進行控制展現層的跳轉。
測試亂碼
<form action="encode" method="post"> <input type="text" name="name"> <input type="submit"> </form>
@PostMapping("/encode") public String test(String name,Model model){ model.addAttribute("name",name);//將數據傳到前端 return "hello"; }
<h1>${name}</h1>
測試結果:
能夠看到出現亂碼,SpringMVC爲咱們提供了一個過濾器,能夠在web.xml中配置。
<filter> <filter-name>encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>