http://localhost:8080/hello
400的错误请求有问题
500代码有问题
Restful 风格 简洁高效安全
@RequestMapping("/h1")
@Controller
public class RestFulController {
//映射访问路径
@RequestMapping("/add/{p1}/{p2}")
public String index(@PathVariable int p1, @PathVariable int p2, Model model){
int result = p1+p2;
//Spring MVC会自动实例化一个Model对象用于向视图中传值
model.addAttribute("msg", "结果:"+result);
//返回视图位置
return "test";
}
}
@RequestMapping(value = "/hello",method = {RequestMethod.GET})
public String index2(Model model){
model.addAttribute("msg", "hello!");
return "test";
}
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
转发:地址栏不变
重定向:地址栏发生变化
@Controller
public class ResultSpringMVC2 {
@RequestMapping("/rsm2/t1")
public String test1(){
//转发
return "test";
}
@RequestMapping("/rsm2/t2")
public String test2(){
//重定向
return "redirect:/index.jsp";
//return "redirect:hello.do"; //hello.do为另一个请求/
}
}
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name){
System.out.println(name);
return "hello";
}
Model 只有寥寥几个方法只适合用于储存数据,简化了新手对于Model对象的操作和理解;
ModelMap 继承了 LinkedMap ,除了实现了自身的一些方法,同样的继承 LinkedMap 的方法和特性;
ModelAndView 可以在储存数据的同时,可以进行设置返回的逻辑视图,进行控制展示层的跳转。
<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>
@Controller
public class UserController {
@RequestMapping("/j1")
@ResponseBody//他就不会走视图解析器,会直接返回一个 字符串
public String json1() throws JsonProcessingException {
//jackson,ObjectMapper
ObjectMapper mapper = new ObjectMapper();
//创建一个对象
User user = new User(1, "秦疆一号", 12);
//System.out.println(user);
String str = mapper.writeValueAsString(user);
return str;
}
@RestController(直接加到类上即可)