与servlet技术功能相等,实现表现层开发:
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>6.0.11version>
dependency>
<dependency>
<groupId>jakarta.servletgroupId>
<artifactId>jakarta.servlet-apiartifactId>
<version>5.0.0version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13.2version>
<scope>testscope>
dependency>
dependencies>
@Controller // 使用controller定义bean
public class test {
@GetMapping("/hello")
@ResponseBody // 直接返回给浏览器
public String testMVC(){
System.out.println("接收到请求");
return "hello world!";
}
}
容器配置:
package com.xjy.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan({"com.xjy.controller"})
public class MvcConfig {
}
定义 Spring MVC应用程序的初始化器:
package com.xjy.config;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;
public class MvcContainerInit extends AbstractDispatcherServletInitializer {
//创建DispatcherServlet的应用程序上下文(ApplicationContext)
@Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(MvcConfig.class);
return ctx;
}
//指定DispatcherServlet的映射路径
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
@Override
protected WebApplicationContext createRootApplicationContext() {
return null;
}
public WebApplicationContext context(){
return this.createServletApplicationContext();
}
}
注意对应的版本:
部署tomcat程序:
启动程序后浏览器访问:
@GetMapping("/get") // 接受get请求
@ResponseBody
public String get(){
System.out.println("接受到请求");
return "get";
}
@PostMapping("/post")
@ResponseBody
public String post(){
System.out.println("接受到请求");
return "post";
}
@PutMapping("/put")
@ResponseBody
public String put(){
System.out.println("接受到请求");
return "put";
}
@DeleteMapping("/delete")
@ResponseBody
public String delete(){
System.out.println("接受到请求");
return "delete";
}
@Controller
@RequestMapping("/user")
public class userController {
@RequestMapping("/hello")
@ResponseBody
public String save(){
System.out.println("接受到请求");
return "hello word!";
}
}
访问:
直接参数接收:
@GetMapping("/get")
@ResponseBody
public String get(int id){
System.out.println("接受到请求"+id);
return "get";
}
@GetMapping("/get")
@ResponseBody
public String get(student stu){
System.out.println("接受到请求"+stu.getName()+stu.getAge());
return "get";
}
发送请求:
@GetMapping("/get/{id}")
@ResponseBody
public String get(@PathVariable int id){
System.out.println("接受到路劲参数:"+id);
return "get";
}
发送请求:
@PostMapping("/post")
@ResponseBody
public String post(@RequestParam List<Integer> list){
System.out.println("接受到请求"+list.get(0));
return "ok";
}
发送请求:
@GetMapping("/get")
@ResponseBody
public String get(@DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date){
System.out.println("接受到时间参数:"+date);
return "get";
}
发送:
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.13.3version>
dependency>
@Configuration
@ComponentScan({"com.xjy.controller"})
@EnableWebMvc
public class MvcConfig {
}
@PostMapping("/post")
@ResponseBody
public String post(@RequestBody student stu){
System.out.println("接受到请求"+ stu.getName());
return "{'status','ok'}";
}
发送数据:
方法中直接return
返回json: @ResponseBody 加上注解
@RestController -> @controller + @ResponseBody
注解需要配包扫描:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public String exceptionHandler(Exception ex){
System.out.println("处理到异常");
return "err";
}
}
模拟异常:
自定义拦截:
public class interceptorDo implements HandlerInterceptor {
@Override // 拦截方法
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("拦截到请求");
return true;//返回true放行,返回不放行;
}
@Override //资源运行后执行
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override //视图渲染完毕后执行
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
配置拦截器:
@Configuration
@ComponentScan({"com.xjy.controller"})
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
@Bean
public interceptorDo getInteceptor(){
return new interceptorDo();
}
@Autowired
private interceptorDo interceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(interceptor)
.excludePathPatterns("/long");//过滤登录拦截
}
}