@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>