如图
@FunctionalInterface
public interface Controller {
@Nullable
ModelAndView handleRequest(HttpServletRequest var1, HttpServletResponse var2) throws Exception;
}
缺点:
实现接口是很老的办法,一般不使用
<context:component-scan base-package="controller" />
@Component //组件
@Controller //控制器
@Service //服务层
@Repository //dao
RestFul就是一个资源定位以及资源操作的风格。不是标准也不是协议,就是一种风格
资源:互联网上所有的资源都可以抽象为资源
资源操作:使用POST、DELETE、PUT、GET,使用不同的方法对资源进行操作
可以通过请求方式来区别操作方法,与链接无关
@RequestMapping("/add/{a}/{b}")
public String test(@PathVariable int a, @PathVariable int b, Model model){
int res = a + b;
model.addAttribute("msg", res);
return "test";
}
1.通过@RequestMapping中的method来指定POST、DELETE、PUT、GET等
@RequestMapping(value="/add/{a}/{b}",method = {
RequestMethod.GET})
public String test(@PathVariable int a, @PathVariable int b, Model model){
int res = a + b;
model.addAttribute("msg", res);
return "test";
}
2.直接通过注解指定
@GetMapping("/add/{a}/{b}") //get请求
@PostMapping("/add/{a}/{b}") //post请求
@DeleteMapping("/add/{a}/{b}") //delete请求
@PutMapping("/add/{a}/{b}") //put请求
public String test(@PathVariable int a, @PathVariable int b, Model model){
int res = a + b;
model.addAttribute("msg", res);
return "test";
}
1.ModelAndView 视图解析器
2.支持Servlet方式
@RequestMapping("/add/{a}/{b}")
public String test2(HttpServletRequest request, HttpServletResponse response){
request.getSession();
response.sendRedirect("test"); //重定向
request.getRequestDispatcher("test").forward(request, response);//转发
return "test";
}
3.SpringMVC 封装的操作
@RequestMapping("/test3")
public String test3(){
return "redirect:/index.jsp"
}
@RequestMapping("/test4")
public String test4(){
return "forward:/index.jsp"
}
使用@RequestParam
@RequestMapping("/test5")
//localhost:8080/test5?param=test
public String test5( @RequestParam("param") String param,Model model){
model.addAttribute("res", param);
return "test";
}
使用@RequestBody可以接收一个对象,map、list、实体类
通过过滤器解决乱码问题,SpringMVC提供了支持
<filter>
<filter-name>characterEncodingfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>characterEncodingfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
@ResponseBody
@RequestMapping("/json")
@ResponseBody //这个注解不会走视图解析器,他会直接返回一个字符串
public String test6(){
Map map = new HashMap<String,String>();
map.put("name", "白牛");
map.put("age", "21");
JSONObject obj = new JSONObject(map);
return obj.toString();
}
@RestController
@RestController //这个控制器下所有的方法只会返回字符串
public class HelloController {
}