Spring Boot中Spring MVC的基本配置讲解与实战(包括静态资源配置,拦截器配置,文件上传配置及实战 附源码)

简介: Spring Boot中Spring MVC的基本配置讲解与实战(包括静态资源配置,拦截器配置,文件上传配置及实战 附源码)

创作不易 觉得有帮助请点赞关注收藏

Spring MVC的定制配置需要配置类实现WebMvcConfigurer接口,并在配置类中使用@EnableWebMvc注解来开启对Spring MVC的配置支持,这样开发者就可以重写接口方法完成常用的配置

静态资源配置

应用程序的静态资源(CSS JS 图片)等需要直接访问,这时需要开发者在配置类重写public void addResourceHandlers(ResourceHandlerRegitry registry)接口方法来实现 部分代码如下

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableWebMvc;
import org.springframework.context.annotation.ResourceHandlerRegistry;
import org.springframework.context.annotation.WebMvcConfigurer;
import org.springframework.context.annotation.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages={"controller","service"}
public class SpringMVCConfig implements WebMvcConfigurer{
@Bean
}
@Override 
public class addResourceHandlers(ResourceHandlerRegistry registry){
}
}

根据上述配置 可以直接访问Web应用目录下html/目录下的静态资源

拦截器配置

Spring的拦截器(Interceptor)实现对每一个请求处理前后进行相关的业务处理,类似于Servlet的过滤器,开发者也可以自定义Spring的拦截器

文件上传配置

文件上传是应用中经常使用的功能,Spring MVC通过配置一个MultipartResolver来上传文件,在Spring MVC的控制器中,可以通过MultipartFile myfile来接收单个文件上传,通过List<MultipartFile>myfiles来接受多个文件上传

下面通过一个实例讲解如何上传多个文件

1:创建Web应用并导入相关的JAR包

创建Web应用ch2_6

2:创建多文件选择页面

在WebContent目录下创建JSP页面multFiles.jsp 具体代码如下

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/multifile" method="post" enctype="multipart/form-data">  
    选择文件1:<input type="file" name="myfile">  <br>
    文件描述1:<input type="text" name="description"> <br>
    选择文件2:<input type="file" name="myfile">  <br>
    文件描述2:<input type="text" name="description"> <br>
    选择文件3:<input type="file" name="myfile">  <br>
    文件描述3:<input type="text" name="description"> <br>
 <input type="submit" value="提交">   
</form> 
</body>
</html>

效果如下

3:创建POJO类

在src目录下创建pojo包,并创建实体类MultFileDomain 具体代码如下

package pojo;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
public class MultiFileDomain {
  private List<String> description;
  private List<MultipartFile> myfile;
  public List<String> getDescription() {
    return description;
  }
  public void setDescription(List<String> description) {
    this.description = description;
  }
  public List<MultipartFile> getMyfile() {
    return myfile;
  }
  public void setMyfile(List<MultipartFile> myfile) {
    this.myfile = myfile;
  }
}

4:创建控制器类

src目录下创建controller包 并创建控制器类MutiFilesController 具体代码如下

package controller;
import java.io.File;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import pojo.MultiFileDomain;
@Controller
public class MutiFilesController {
  // 得到一个用来记录日志的对象,这样打印信息时,能够标记打印的是哪个类的信息
  private static final Log logger = LogFactory.getLog(MutiFilesController.class);
  /**
   * 多文件上传
   */
  @RequestMapping("/multifile")
  public String multiFileUpload(@ModelAttribute MultiFileDomain multiFileDomain, HttpServletRequest request){
    String realpath = request.getServletContext().getRealPath("uploadfiles");  
    //上传到eclipse-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/ch2_6/uploadfiles
    File targetDir = new File(realpath); 
    if(!targetDir.exists()){  
      targetDir.mkdirs();  
        } 
    List<MultipartFile> files = multiFileDomain.getMyfile();
    for (int i = 0; i < files.size(); i++) {
      MultipartFile file = files.get(i);
      String fileName = file.getOriginalFilename();
      File targetFile = new File(realpath,fileName);
      //上传 
          try {  
            file.transferTo(targetFile);  
          } catch (Exception e) {  
              e.printStackTrace();  
          }  
    }
    logger.info("成功");
    return "showMulti";
  }
}

5:创建Web于Spring MVC配置类

Webconfig类代码如下

package config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class WebConfig implements WebApplicationInitializer{
  @Override
  public void onStartup(ServletContext arg0) throws ServletException {
    AnnotationConfigWebApplicationContext ctx 
    = new AnnotationConfigWebApplicationContext();
    ctx.register(SpringMVCConfig.class);//注册Spring MVC的Java配置类SpringMVCConfig
    ctx.setServletContext(arg0);//和当前ServletContext关联
    /**
     * 注册Spring MVC的DispatcherServlet
     */
    Dynamic servlet = arg0.addServlet("dispatcher", new DispatcherServlet(ctx));
    servlet.addMapping("/");
    servlet.setLoadOnStartup(1);
  }
}

SpringMVCConfig类代码如下

package config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"controller","service"})
public class SpringMVCConfig implements WebMvcConfigurer {
  /**
   * 配置视图解析器
   */
  @Bean
  public InternalResourceViewResolver getViewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setPrefix("/WEB-INF/jsp/");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
  }
  /**
   * 配置静态资源
   */
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/html/**").addResourceLocations("/html/");
    //addResourceHandler指的是对外暴露的访问路径
    //addResourceLocations指的是静态资源存放的位置
  }
  /**
   * MultipartResolver配置
   */
  @Bean
  public MultipartResolver multipartResolver() {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    //设置上传文件的最大值,单位为字节
    multipartResolver.setMaxUploadSize(5400000);
    //设置请求的编码格式,默认为iso-8859-1
    multipartResolver.setDefaultEncoding("UTF-8");
    return multipartResolver;
  }
}

6:创建成功显示页面

在WEB-INF目录下 创建多文件上传成功显示页面showMulti.jsp 代码如下

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
  <table>
    <tr>
      <td>详情</td><td>文件名</td>
    </tr>
    <!-- 同时取两个数组的元素 -->
    <c:forEach items="${multiFileDomain.description}" var="description" varStatus="loop">
      <tr>
        <td>${description}</td>
        <td>${multiFileDomain.myfile[loop.count-1].originalFilename}</td>
      </tr>
    </c:forEach>
    <!-- fileDomain.getMyfile().getOriginalFilename() -->
  </table>
</body>
</html>

效果如下 当上传文件成功时 详情和文件名有会对应的输出

7:发布并运行应用

发布应用到Tomcat服务器并启动它,然后访问http://localhost:8080/ch2_6/multiFiles.jsp运行多文件选择页面即可

相关文章
|
6天前
|
Web App开发 编解码 Java
B/S基层卫生健康云HIS医院管理系统源码 SaaS模式 、Springboot框架
基层卫生健康云HIS系统采用云端SaaS服务的方式提供,使用用户通过浏览器即能访问,无需关注系统的部署、维护、升级等问题,系统充分考虑了模板化、配置化、智能化、扩展化等设计方法,覆盖了基层医疗机构的主要工作流程,能够与监管系统有序对接,并能满足未来系统扩展的需要。
33 4
|
24天前
|
缓存 前端开发 Java
【Java】仓库管理系统 SpringBoot+LayUI+DTree(源码)【独一无二】
【Java】仓库管理系统 SpringBoot+LayUI+DTree(源码)【独一无二】
|
8天前
|
人工智能 移动开发 前端开发
Springboot医院智慧导诊系统源码:精准推荐科室
医院智慧导诊系统是在医疗中使用的引导患者自助就诊挂号,在就诊的过程中有许多患者不知道需要挂什么号,要看什么病,通过智慧导诊系统,可输入自身疾病的症状表现,或选择身体部位,在经由智慧导诊系统多维度计算,精准推荐科室,引导患者挂号就诊,实现科学就诊,不用担心挂错号。
18 2
|
9天前
|
人工智能 前端开发 Java
Java语言开发的AI智慧导诊系统源码springboot+redis 3D互联网智导诊系统源码
智慧导诊解决盲目就诊问题,减轻分诊工作压力。降低挂错号比例,优化就诊流程,有效提高线上线下医疗机构接诊效率。可通过人体画像选择症状部位,了解对应病症信息和推荐就医科室。
149 10
|
9天前
|
Java 关系型数据库 MySQL
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
UWB (ULTRA WIDE BAND, UWB) 技术是一种无线载波通讯技术,它不采用正弦载波,而是利用纳秒级的非正弦波窄脉冲传输数据,因此其所占的频谱范围很宽。一套UWB精确定位系统,最高定位精度可达10cm,具有高精度,高动态,高容量,低功耗的应用。
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
|
10天前
|
存储 数据可视化 安全
Java全套智慧校园系统源码springboot+elmentui +Quartz可视化校园管理平台系统源码 建设智慧校园的5大关键技术
智慧校园指的是以物联网为基础的智慧化的校园工作、学习和生活一体化环境,这个一体化环境以各种应用服务系统为载体,将教学、科研、管理和校园生活进行充分融合。无处不在的网络学习、融合创新的网络科研、透明高效的校务治理、丰富多彩的校园文化、方便周到的校园生活。简而言之,“要做一个安全、稳定、环保、节能的校园。
35 6
|
12天前
|
消息中间件 运维 供应链
springboot区域云HIS医院信息综合管理平台源码
云HIS系统分为两个大的系统,一个是基层卫生健康云综合管理系统,另一个是基层卫生健康云业务系统。基层卫生健康云综合管理系统由运营商、开发商和监管机构使用,用来进行运营管理、运维管理和综合监管。基层卫生健康云业务系统由基层医院使用,用来支撑医院各类业务运转。
21 2
|
14天前
|
数据采集 前端开发 Java
数据塑造:Spring MVC中@ModelAttribute的高级数据预处理技巧
数据塑造:Spring MVC中@ModelAttribute的高级数据预处理技巧
23 3
|
14天前
|
存储 前端开发 Java
会话锦囊:揭示Spring MVC如何巧妙使用@SessionAttributes
会话锦囊:揭示Spring MVC如何巧妙使用@SessionAttributes
14 1
|
14天前
|
前端开发 Java Spring
数据之桥:深入Spring MVC中传递数据给视图的实用指南
数据之桥:深入Spring MVC中传递数据给视图的实用指南
30 3