SpringMVC
|字数总计:4.5k|阅读时长:21分钟|阅读量:
HelloWorld
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cuc.mvc</groupId> <artifactId>springMVC-demo1</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging>
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.1</version> </dependency>
<dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency>
<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency>
<dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>3.0.12.RELEASE</version> </dependency> </dependencies>
</project>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| <context:component-scan base-package="com.cuc.mvc.controller" />
<bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver"> <property name="order" value="1"/> <property name="characterEncoding" value="UTF-8"/> <property name="templateEngine"> <bean class="org.thymeleaf.spring5.SpringTemplateEngine"> <property name="templateResolver"> <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="/WEB-INF/templates/"/>
<property name="suffix" value=".html"/> <property name="templateMode" value="HTML5"/> <property name="characterEncoding" value="UTF-8" /> </bean> </property> </bean> </property> </bean>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springMVC.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern> </servlet-mapping>
|
1 2 3 4 5 6 7 8 9
| @Controller public class HelloController {
@RequestMapping("/") public String index(){ return "index"; } }
|
@RequestMapping
标识位置
可以使用在类上或方法上
1 2 3 4 5 6 7 8 9
| @Controller @RequestMapping("/hello") public class HelloController {
@RequestMapping("/index") public String index(){ return "index"; } }
|
属性
参数 |
解释 |
name |
string |
value |
string[] |
path |
string[] |
method |
RequestMethod[] |
params |
string[] |
headers |
string[] |
consumes |
string[] |
produces |
string[] |
1 2 3 4 5
| @RequestMapping("/success") public String toSuccess(){ return "success"; }
|
1 2 3 4 5 6
|
@RequestMapping(value = "/test1",method = {RequestMethod.POST}) public String byPost(){ return "success"; }
|
1 2 3 4 5 6 7 8 9
|
@GetMapping(value = "/test4",params = {"username","password!=123456"}) public String test4(){ return "success"; }
|
派生注解
- @GetMapping
- @PostMapping
- @PutMapping
- @DeleteMapping
1 2 3 4 5
| @GetMapping("/test2") public String test2(){ return "success"; }
|
ant风格路径
1 2 3 4 5 6 7 8
|
@RequestMapping("/**/*te?t5") public String test5(){ return "success"; }
|
占位符
1 2 3 4 5 6 7
| @RequestMapping("/test6/{id}/{username}") public String test6(@PathVariable("id")Integer id,@PathVariable("username")String username){ System.out.println("id:"+id); System.out.println("username:"+username); return "success"; }
|
SpringMVC获取请求参数
ServletAPI(原生写法)
1 2 3 4 5 6 7 8 9 10 11
| @RequestMapping("/servletAPI")
public String servletAPI(HttpServletRequest request){ HttpSession session = request.getSession(); String username = request.getParameter("username"); String password = request.getParameter("password"); System.out.println("username:"+username+",password:"+password); return "success"; }
|
控制器形参
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
@RequestMapping("/test1") public String test1( @RequestParam(value = "user_name",required = false,defaultValue = "root") String username, String password, // 当有多个相同名称为hobby参数传递过来时,各个参数值会被,隔开 // 如果 String 改成 String[],则会被各个参数值会被存进数组 String hobby, // 获取请求头参数,属性跟@RequestParam相同(value、required、defaultValue) @RequestHeader("Host") String host, @CookieValue("JSESSIONID") String JSESSIONID) {
System.out.println("username:"+username+",password:"+password+",hobby:"+hobby); System.out.println("host:"+host); System.out.println("JSESSIONID:"+JSESSIONID); return "success"; }
|
实体类形参
1 2 3 4 5 6
| @RequestMapping("/test2")
public String test2(User user){ System.out.println(user); return "success"; }
|
解决中文乱码
web.xml中配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
<filter> <filter-name>CharacterEncodingFilter</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> <init-param> <param-name>forceResponseEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
|
域对象共享数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| @Controller @RequestMapping("/scope") public class ScopeController {
@RequestMapping("/test1") public String test1(HttpServletRequest request){ request.setAttribute("requestScope","servletAPI"); return "getScopeValue"; }
@RequestMapping("/test2") public ModelAndView test2(){ ModelAndView mav = new ModelAndView(); mav.addObject("requestScope","ModelAndView"); mav.setViewName("getScopeValue"); return mav; }
@RequestMapping("/test3") public String test3(Model model){ model.addAttribute("requestScope","Model"); return "getScopeValue"; }
@RequestMapping("/test4") public String test4(Map<String,Object> map){ map.put("requestScope","map"); return "getScopeValue"; }
@RequestMapping("/test5") public String test5(ModelMap modelMap){ modelMap.addAttribute("requestScope","ModelMap"); return "getScopeValue"; }
@RequestMapping("/test6") public String test6(HttpSession session){ session.setAttribute("sessionScope","session"); return "getScopeValue"; }
@RequestMapping("/test7") public String test7(HttpSession session){ ServletContext application = session.getServletContext(); application.setAttribute("applicationScope","application"); return "getScopeValue"; } }
|
SpringMVC视图
相关操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| @Controller @RequestMapping("/view") public class ViewController {
@RequestMapping("/test1") public String test1(){ return "success"; }
@RequestMapping("/test2") public String test2(){ return "forward:/view/test1"; }
@RequestMapping("/test3") public String test3(){ return "redirect:/view/test1"; } }
|
视图控制器
1 2 3 4 5 6 7 8 9
|
<mvc:view-controller path="/" view-name="index" />
<mvc:annotation-driven />
|
RESTFul
解决PUT、DELETE请求问题
web.xml配置:
1 2 3 4 5 6 7 8 9 10
|
<filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
|
操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| @Controller @RequestMapping("/rest") public class UserController {
@RequestMapping(value = "/user", method = RequestMethod.GET) public String getAllUser(){ System.out.println("所有用户信息"); return "success"; }
@RequestMapping(value = "/user/{id}",method = RequestMethod.GET) public String getUserById(@PathVariable("id")Integer id){ System.out.println("id为"+id+"的用户信息"); return "success"; }
@RequestMapping(value = "/user", method = RequestMethod.POST) public String addUser(User user){ System.out.println("添加用户:"+user.toString()); return "success"; }
@RequestMapping(value = "/user", method = RequestMethod.PUT) public String updateUser(User user){ System.out.println("更新用户信息:"+user.toString()); return "success"; }
}
|
处理静态资源
springmvc配置文件:
1 2 3 4 5 6 7 8
|
<mvc:default-servlet-handler />
<mvc:annotation-driven />
|
HttpMessageConverter
HttpMessageConverter,报文信息转换器,将请求报文转换为Java对象,或将Java对象转换为响应报文
HttpMessageConverter提供了两个注解和两个类型:@RequestBody
、@ResponseBody
、RequestEntity
、ResponseEntity
依赖
1 2 3 4 5 6
| <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.1</version> </dependency>
|
操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| @Controller public class HttpController {
@RequestMapping("/test1") public String test1(@RequestBody String requestBody){ System.out.println("RequestBody:"+requestBody); return "success"; }
@RequestMapping("/test2") public String test2(RequestEntity<String> requestEntity){ System.out.println("请求头:"+requestEntity.getHeaders()); System.out.println("请求体:"+requestEntity.getBody()); return "success"; }
@RequestMapping("/test3") public void test3(HttpServletResponse response) throws IOException { response.getWriter().print("hello,response"); }
@RequestMapping("/test4") @ResponseBody public String test4(){ return "hello,ResponseBody"; }
@RequestMapping("/test5") @ResponseBody public User test5(){ return new User(1001,"admin","123",12,"男"); }
@RequestMapping("/test6") @ResponseBody public String test6(String username,String password){ System.out.println("username:"+username+",password:"+password); return "axios请求成功"; } }
|
@RestController注解
@RestController
注解是SpringMVC提供的一个复合注解,标识在控制器的类上,相当于为类添加@Controller
注解,并且为类中的每个方法添加@ResponseBody
注解
文件上传与下载
文件下载
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| @RequestMapping("/downLoad") public ResponseEntity<byte[]> downLoad(HttpSession session) throws IOException { ServletContext servletContext = session.getServletContext(); String realPath = servletContext.getRealPath("/static/img/1.jpg"); InputStream is = new FileInputStream(realPath); byte[] bytes = new byte[is.available()]; is.read(bytes); MultiValueMap<String, String> headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment;filename=1.jpg"); HttpStatus statusCode = HttpStatus.OK; ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode); is.close(); return responseEntity; }
|
文件上传
依赖
1 2 3 4 5 6
| <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
|
配置文件上传解析器
springmvc配置文件:
1 2
| <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
|
实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| @RequestMapping("/upLoad") public String upLoad(MultipartFile photo, HttpSession session) throws IOException {
String fileName = photo.getOriginalFilename(); String hzName = fileName.substring(fileName.lastIndexOf(".")); fileName = UUID.randomUUID().toString() + hzName; ServletContext servletContext = session.getServletContext(); String photoPath = servletContext.getRealPath("photo"); File file = new File(photoPath); if(!file.exists()){ file.mkdir(); } String finalPath = photoPath + File.separator + fileName; photo.transferTo(new File(finalPath)); return "success"; }
|
拦截器
用于拦截控制器方法的执行,SpringMVC中的拦截器需要实现HandlerInterceptor
或者继承HandlerInterceptorAdapter
类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <mvc:interceptors>
<mvc:interceptor> <mvc:mapping path="/interceptor/*"/> <ref bean="firstInterceptor" /> </mvc:interceptor>
<mvc:interceptor> <mvc:mapping path="/interceptor/*"/> <ref bean="secondInterceptor" /> </mvc:interceptor> </mvc:interceptors>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| @Component public class FirstInterceptor implements HandlerInterceptor {
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("FirstInterceptor-->preHandle"); return true; }
@Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("FirstInterceptor-->postHandle"); }
@Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("FirstInterceptor-->afterCompletion"); } }
|
异常处理
SpringMVC提供了一个处理控制器方法执行过程中所出现异常的接口:HandlerExceptionResolver
它的实现类有:DefaultHandlerExceptionResolver
和SimpleMappingExceptionResolver
基于配置文件
1 2 3 4 5 6 7 8 9 10 11
| <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="java.lang.ArithmeticException">error</prop> </props> </property> <property name="exceptionAttribute" value="ex" /> </bean>
|
1 2 3 4 5 6 7 8 9 10
| @ControllerAdvice @RequestMapping("/exception") public class ExceptionController {
@RequestMapping("/test2") public void test2(){ int i = 10/0; }
}
|
基于注解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| @ControllerAdvice @RequestMapping("/exception") public class ExceptionController {
@ExceptionHandler(value = {ArithmeticException.class,NullPointerException.class}) public String test1(Exception ex, Model model){ model.addAttribute("ex",ex); return "error"; }
@RequestMapping("/test2") public void test2(){ int i = 10/0; }
}
|
注解配置SpringMVC
使用配置类和注解代替web.xml和SpringMVC配置文件的功能
替代Spring
1 2 3 4 5
| @Configuration public class SpringConfig { ... }
|
替代SpringMVC配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
@Configuration
@ComponentScan("com.cuc.mvc.controller")
@EnableWebMvc public class WebConfig implements WebMvcConfigurer {
@Bean public ITemplateResolver templateResolver() { WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext(); ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver( webApplicationContext.getServletContext()); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); templateResolver.setCharacterEncoding("UTF-8"); templateResolver.setTemplateMode(TemplateMode.HTML); return templateResolver; }
@Bean public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver) { SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver); return templateEngine; }
@Bean public ViewResolver viewResolver(SpringTemplateEngine templateEngine) { ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setCharacterEncoding("UTF-8"); viewResolver.setTemplateEngine(templateEngine); return viewResolver; }
@Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); }
@Override public void addInterceptors(InterceptorRegistry registry) { TestInterceptor testInterceptor = new TestInterceptor(); registry.addInterceptor(testInterceptor).addPathPatterns("/**"); }
@Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/hello").setViewName("hello"); }
@Bean public MultipartResolver multipartResolver(){ CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(); return commonsMultipartResolver; }
@Override public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) { SimpleMappingExceptionResolver exceptionResolver = new SimpleMappingExceptionResolver(); Properties prop = new Properties(); prop.setProperty("java.lang.ArithmeticException","error"); exceptionResolver.setExceptionMappings(prop); exceptionResolver.setExceptionAttribute("ex"); resolvers.add(exceptionResolver); } }
|
替代web.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override protected Class<?>[] getRootConfigClasses() { return new Class[]{SpringConfig.class}; }
@Override protected Class<?>[] getServletConfigClasses() { return new Class[]{WebConfig.class}; }
@Override protected String[] getServletMappings() { return new String[]{"/"}; }
@Override protected Filter[] getServletFilters() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter(); characterEncodingFilter.setEncoding("utf-8"); characterEncodingFilter.setForceResponseEncoding(true);
HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
return new Filter[]{characterEncodingFilter,hiddenHttpMethodFilter}; } }
|