引言
在构建现代 web 应用时,Spring MVC 作为一种流行的框架,为开发者提供了高效的解决方案。它采用了 MVC(模型-视图-控制器)设计模式,旨在将应用的业务逻辑与用户界面分离,从而提高代码的可维护性和可扩展性。本文将详细介绍 Spring MVC 的核心概念和操作,包括依赖配置、请求参数处理、注解开发、JSON 处理、拦截器以及文件上传和下载功能。
SpringMVC的依赖
步骤
- 先弄好pom.xml
- 再配置web.xml
- 还有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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.youren.controller"/> <mvc:default-servlet-handler/> <mvc:annotation-driven/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!-- 一前一后 --> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
<dependencies> <dependency> <groupId>org.eclipse.ecf</groupId> <artifactId>javax.servlet</artifactId> <version>3.1.0.v201410161800</version> </dependency> <!--jstl依赖--> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.10.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>3.2.8.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.5</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.14.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency> </dependencies>
<?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"> <servlet> <servlet-name>spring</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> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
<?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>org.example</groupId> <artifactId>springmvc</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.eclipse.ecf</groupId> <artifactId>javax.servlet</artifactId> <version>3.1.0.v201410161800</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2.1-b03</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.0.RELEASE</version> </dependency> </dependencies> </project>
package com.youren.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; //public class HelloController implements Controller { @Controller public class HelloController { // @Override // public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { @RequestMapping("/hello") public String test(ModelAndView model){ // 业务代码 String result="HelloSpringMVC"; model.addObject("msg",result); // 视图跳转 // model.setViewName("test"); return "test"; } }
请求参数与回显
public String test(String name,ModelAndView model) { System.out.println("name="+name); // 业务代码 String result = "HelloSpringMVC"; model.addObject("msg", result); return "test"; } http://localhost:8080/myMaven_war_exploded/hello?name=youren @RequestMapping("/hello") public String test(@RequestParam("username") String name, ModelAndView model) { System.out.println("name="+name); // 业务代码 String result = "HelloSpringMVC"; model.addObject("msg", result); return "test"; } http://localhost:8080/hello?username=youren
lombok
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> </dependency> @Data @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String name; private int age; } @RequestMapping("hello2") public String test02(User user) { System.out.println(user); return "test"; } http://localhost:8080/hello2?name=youren&age=8&id=10
过滤器的使用
package com.youren.controller; import javax.servlet.*; import java.io.IOException; public class EncodingFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletRequest.setCharacterEncoding("utf-8"); servletResponse.setCharacterEncoding("utf-8"); filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { } }
<filter> <filter-name>encoding</filter-name> <filter-class>com.youren.controller.EncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/</url-pattern> </filter-mapping>
使用注解开发
@RequestMapping 用于把 url 跟具体的 action 方法进行匹配
@ RequestParam 绑定单个 请求 数据,
@ModelAttribute ,绑定 数据到 Model
@value 指定 请求的实际url
@method 请求 类型
@params 设置参数必须包含的内容
@headers 设置请求头 包含的内容
@ResponseBody 通常用来返回 json数据 或则xml 文件
json
@ResponseBody //它就不会走视图解析器,会直接返回一个字符串 @RequestMapping("json1") public String json1(){ User user = new User(1,"youren",8); return user.toString(); }
@Data @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String name; private int age; }
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.14.2</version> </dependency>
public String json1() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); User user = new User(1,"youren",8); String s = mapper.writeValueAsString(user); return s; }
//乱码解决 @RequestMapping(value="json1",produces="application/json;charset=UTF-8") <!--解决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>
public static void main(String[] args) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); User user = new User(2,"youren",10); String s = mapper.writeValueAsString(user); System.out.println(s);//json System.out.println(user);//对象, }
拦截器
创建 一个 类继承HandlerInterceptor
public class MyInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{ System.out.println("===========处理前=========="); return false; // 当return false 不会执行之后的 } //日志 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception{ System.out.println("===========处理后=========="); } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception{ System.out.println("===========清理 =========="); } }
<!--拦截器 的配置 --> <mvc:interceptors> <mvc:interceptor> <!-- 包括这个 请求 下面 的 所有请求 --> <!-- /** 文件下所有--> <!-- /* 文件下一个--> <mvc:mapping path="/**"/> <bean class="com.youren.interceptor.MyInterceptor"/> </mvc:interceptor> </mvc:interceptors>
model
当 没有视图 解析器 时
package com.youren.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class ModelTest { @RequestMapping("/hello") public String test(ModelAndView model) { // 业务代码 String result = "HelloSpringMVC"; model.addObject("msg", result); return "forward:/WEB-INF/jsp/test.jsp"; // return "redirect:index.jsp"; } }
有视图解析器则可以直接返回
文件的上传和下载
<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency>
<!-- the file upload configuration--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- request encoding default is ISO-8859-1 --> <property name="defaultEncoding" value="utf-8" /> <!-- max 10485760=10m --> <property name="maxUploadSize" value="10485760"/> <property name="maxInMemorySize" value="40960"/> </bean>
@RestController public class fileController { @RequestMapping("/upload") public String upload(@RequestParam("file")CommonsMultipartFile file, HttpServletRequest request) throws IOException { // get the filename String uploadFileName = file.getOriginalFilename(); // judge if("".equals(uploadFileName)){ return "redirect:/index.jsp"; } System.out.println("the upload filename is:"+uploadFileName); // save the file path String path= request.getServletContext().getRealPath("/upload"); // if the path is not existing create it File realPath= new File(path); if(!realPath.exists()){ realPath.mkdirs(); } System.out.println("the upload file path is :"+realPath); InputStream inputStream = file.getInputStream(); // input stream OutputStream outputStream =new FileOutputStream(new File(realPath,uploadFileName)); // 读取写出 int len = 0; byte[] buffer= new byte[1024]; while ((len=inputStream.read(buffer))!=-1){ outputStream.write(buffer,0,len); outputStream.flush(); } outputStream.close(); inputStream.close(); return "redirect:/index.jsp"; } }
pom.xml
<dependency> <groupId>org.eclipse.ecf</groupId> <artifactId>javax.servlet</artifactId> <version>3.1.0.v201410161800</version> </dependency> <!--jstl依赖--> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>6.0.6</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>6.0.6</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.13</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>3.0.1</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.26</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.14.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency> </dependencies>
注意点
注意jsp或html等文件是直属于Webcontent,与【META-INF】【WEB-INF】平级,不要将jsp文件放置到【WEB-INF】下面,WEB-INF是Java的WEB应用的安全目录。所谓安全就是客户端无法访问,只有服务端可以访问的目录。所以会引起404错误。
只能通过controller 或者servlet 访问