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运行多文件选择页面即可

相关文章
|
18天前
|
人工智能 Java 机器人
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
Spring AI Alibaba集成Ollama,基于Java构建本地大模型应用,支持流式对话、knife4j接口可视化,实现高隐私、免API密钥的离线AI服务。
373 1
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
存储 JSON Java
210 0
|
25天前
|
人工智能 Java 开发者
【Spring】原理解析:Spring Boot 自动配置
Spring Boot通过“约定优于配置”的设计理念,自动检测项目依赖并根据这些依赖自动装配相应的Bean,从而解放开发者从繁琐的配置工作中解脱出来,专注于业务逻辑实现。
|
3月前
|
前端开发 Java API
Spring Cloud Gateway Server Web MVC报错“Unsupported transfer encoding: chunked”解决
本文解析了Spring Cloud Gateway中出现“Unsupported transfer encoding: chunked”错误的原因,指出该问题源于Feign依赖的HTTP客户端与服务端的`chunked`传输编码不兼容,并提供了具体的解决方案。通过规范Feign客户端接口的返回类型,可有效避免该异常,提升系统兼容性与稳定性。
199 0
|
3月前
|
SQL Java 数据库连接
Spring、SpringMVC 与 MyBatis 核心知识点解析
我梳理的这些内容,涵盖了 Spring、SpringMVC 和 MyBatis 的核心知识点。 在 Spring 中,我了解到 IOC 是控制反转,把对象控制权交容器;DI 是依赖注入,有三种实现方式。Bean 有五种作用域,单例 bean 的线程安全问题及自动装配方式也清晰了。事务基于数据库和 AOP,有失效场景和七种传播行为。AOP 是面向切面编程,动态代理有 JDK 和 CGLIB 两种。 SpringMVC 的 11 步执行流程我烂熟于心,还有那些常用注解的用法。 MyBatis 里,#{} 和 ${} 的区别很关键,获取主键、处理字段与属性名不匹配的方法也掌握了。多表查询、动态
116 0
|
3月前
|
JSON 前端开发 Java
第05课:Spring Boot中的MVC支持
第05课:Spring Boot中的MVC支持
180 0
|
6月前
|
前端开发 Java Maven
Spring 和 Spring Boot 之间的比较
本文对比了标准Spring框架与Spring Boot的区别,重点分析两者在模块使用(如MVC、Security)上的差异。Spring提供全面的Java开发基础设施支持,包含依赖注入和多种开箱即用的模块;而Spring Boot作为Spring的扩展,通过自动配置、嵌入式服务器等功能简化开发流程。文章还探讨了两者的Maven依赖、Mvc配置、模板引擎配置、启动方式及打包部署等方面的异同,展示了Spring Boot如何通过减少样板代码和配置提升开发效率。总结指出,Spring Boot是Spring的增强版,使应用开发、测试与部署更加便捷高效。
763 12
|
7月前
|
安全 Java Apache
微服务——SpringBoot使用归纳——Spring Boot中集成 Shiro——Shiro 身份和权限认证
本文介绍了 Apache Shiro 的身份认证与权限认证机制。在身份认证部分,分析了 Shiro 的认证流程,包括应用程序调用 `Subject.login(token)` 方法、SecurityManager 接管认证以及通过 Realm 进行具体的安全验证。权限认证部分阐述了权限(permission)、角色(role)和用户(user)三者的关系,其中用户可拥有多个角色,角色则对应不同的权限组合,例如普通用户仅能查看或添加信息,而管理员可执行所有操作。
331 0
|
7月前
|
安全 Java 数据安全/隐私保护
微服务——SpringBoot使用归纳——Spring Boot中集成 Shiro——Shiro 三大核心组件
本课程介绍如何在Spring Boot中集成Shiro框架,主要讲解Shiro的认证与授权功能。Shiro是一个简单易用的Java安全框架,用于认证、授权、加密和会话管理等。其核心组件包括Subject(认证主体)、SecurityManager(安全管理员)和Realm(域)。Subject负责身份认证,包含Principals(身份)和Credentials(凭证);SecurityManager是架构核心,协调内部组件运作;Realm则是连接Shiro与应用数据的桥梁,用于访问用户账户及权限信息。通过学习,您将掌握Shiro的基本原理及其在项目中的应用。
257 0