SpringMVC
MVC
- 模型(Model) 【dao service】
- 视图(View)【jsp】
- 控制器(Controller)【Servlet】
SpringMVC特点:
- 轻量级
- 高校,基于请求响应的MVC框架
- 功能强大:RESTful、数据验证、格式化、本地化、主题等
DispatcherServlet
1 SpringMVC的配置
新建Moudle,添加web依赖
导入相关依赖
配置web.xml,注册DispatcherServlet
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!-- 注册DispatcherServlet (核心) 请求分发器,前端控制器--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- DispatchServlet要绑定Spring的配置文件 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <!-- 启动级别 --> <load-on-startup>1</load-on-startup> </servlet> <!-- / : 只匹配所有的请求,不会匹配jsp页面 /* : 配置所有的请求,包括jsp页面 --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>springmvc-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 处理器映射器 --> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" /> <!-- 处理器适配器 --> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" /> <!-- 视图解析器 : 模板引擎 Thymeleaf Freemarker...--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver"> <!-- 前缀 --> <property name="prefix" value="/WEB-INF/jsp/" /> <!-- 后缀 --> <property name="suffix" value=".jsp" /> </bean>
<!-- BeanNameUrlHandlerMapping:要配置bean --> <bean id="/hello" class="com.Rickduck.controller.HelloController" />```
问题:页面显示404,打包的target中缺少lib文件夹
解决: Project Structure -- Artifacts 中添加lib文件夹并将jar包导入
2. SpringMVC执行流程
3. 使用注解开发SpringMVC
- 注解配置
web.xml配置DispatchServlet:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
<!-- 注册DispatcherServlet (核心) 请求分发器,前端控制器-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- DispatchServlet要绑定Spring的配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<!-- 启动级别 -->
<load-on-startup>1</load-on-startup>
</servlet>
<!--
/ : 只匹配所有的请求,不会匹配jsp页面
/* : 配置所有的请求,包括jsp页面
-->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app> springmvc配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 自动扫描包,让指定包下的注解生效 -->
<context:component-scan base-package="com.Rickduck.Controller" />
<mvc:default-servlet-handler />
<mvc:annotation-driven />
<!-- 视图解析器 : 模板引擎 Thymeleaf Freemarker...-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
</beans> 编写控制类及页面跳转关系
package com.Rickduck.Controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/hello") public class HelloController { @RequestMapping("/h1") public String hello(Model model){ model.addAttribute("msg","Hello SpringMVC"); return "hello"; } }web页面
<%--
Created by IntelliJ IDEA.
User: 63008
Date: 2020/12/26
Time: 13:01
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Hello</title>
</head>
<body>
${msg}
</body>
</html> 注解
//识别前端的对象名
@RequestParam("username") String name
4. Restful风格
通过请求的方式进行判断
功能
- 资源:忽略文所有事物都可抽象为资源
- 资源操作(不同请求方式)
- POST:添加
- DELETE:删除
- PUT:修改
- GET:查询
方法级别注解,组合注解:
@GetMapping @PostMapping @PutMapping @DeleteMapping @PatchMapping
好处:
- 使路径边的更加简洁(安全)
- 支持缓存
- 获得参数更加方便,框架会自动进行类型转换
- 通过路径变量类型可以约束访问参数
5. 转发与重定向
SpringMVC实现转发和重定向
@Controller
public class RestfulController {
//转发
@GetMapping("/add/a/b")
public String test1(@PathVariable int a,@PathVariable int b, Model model){
model.addAttribute("msg",a+b);
return "hello";
}
//重定向
@RequestMapping("/test")
public String test2(){
return "redirect:/hello.jsp";
}
}
6. Json
依赖导入:
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
<scope>provided</scope>
</dependency>
6.1Jackson
Jackson乱码配置:
在springMVC配置文件中设置:
<!--JSON乱码问题配置-->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
7. 拦截器
- 自带静态资源过滤
- 指挥访问拦***问的控制方法
- 新建一个config文件,添加MyInterceptor类并实现HandlerInterceptor接口
- 重写拦截方法
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
- 配置springmvc-config,添加拦截器配置
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.Rickduck.config.MyInterceptor" />
</mvc:interceptor>
</mvc:interceptors> 8. 文件上传
- 导入pom依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency> - 配置springmvc-config文件,注入相关Bean
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8" />
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960" />
</bean> - 设置表单提交的类型
<form action = "${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
<input type = "file" name = "file" />
<input type = "submit" value = "upload" />
</form> - 编写Controller类添加文件
@RequestMapping("upload")
public String fileLoad(@RequestParam("file")CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//上传路径
String path = request.getServletContext().getRealPath("/upload");
File realPath = new File(path);
if(!realPath.exists()){
realPath.mkdir();
}
//上传文件地址
System.out.println(realPath);
//通过CommonsMultipartFile提供的方法直接写文件
file.transferTo(new File(realPath+"/"+file.getOriginalFilename()));
return "test";
} 


京公网安备 11010502036488号