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

相关文章
|
8月前
|
JavaScript Java Maven
【SpringBoot(二)】带你认识Yaml配置文件类型、SpringMVC的资源访问路径 和 静态资源配置的原理!
SpringBoot专栏第二章,从本章开始正式进入SpringBoot的WEB阶段开发,本章先带你认识yaml配置文件和资源的路径配置原理,以方便在后面的文章中打下基础
625 4
|
8月前
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
754 2
|
9月前
|
人工智能 Java 机器人
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
Spring AI Alibaba集成Ollama,基于Java构建本地大模型应用,支持流式对话、knife4j接口可视化,实现高隐私、免API密钥的离线AI服务。
7159 2
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
存储 JSON Java
944 0
|
10月前
|
监控 Java API
Spring Boot 3.2 结合 Spring Cloud 微服务架构实操指南 现代分布式应用系统构建实战教程
Spring Boot 3.2 + Spring Cloud 2023.0 微服务架构实践摘要 本文基于Spring Boot 3.2.5和Spring Cloud 2023.0.1最新稳定版本,演示现代微服务架构的构建过程。主要内容包括: 技术栈选择:采用Spring Cloud Netflix Eureka 4.1.0作为服务注册中心,Resilience4j 2.1.0替代Hystrix实现熔断机制,配合OpenFeign和Gateway等组件。 核心实操步骤: 搭建Eureka注册中心服务 构建商品
1449 3
|
安全 Java Apache
微服务——SpringBoot使用归纳——Spring Boot中集成 Shiro——Shiro 身份和权限认证
本文介绍了 Apache Shiro 的身份认证与权限认证机制。在身份认证部分,分析了 Shiro 的认证流程,包括应用程序调用 `Subject.login(token)` 方法、SecurityManager 接管认证以及通过 Realm 进行具体的安全验证。权限认证部分阐述了权限(permission)、角色(role)和用户(user)三者的关系,其中用户可拥有多个角色,角色则对应不同的权限组合,例如普通用户仅能查看或添加信息,而管理员可执行所有操作。
673 0
|
安全 Java 数据安全/隐私保护
微服务——SpringBoot使用归纳——Spring Boot中集成 Shiro——Shiro 三大核心组件
本课程介绍如何在Spring Boot中集成Shiro框架,主要讲解Shiro的认证与授权功能。Shiro是一个简单易用的Java安全框架,用于认证、授权、加密和会话管理等。其核心组件包括Subject(认证主体)、SecurityManager(安全管理员)和Realm(域)。Subject负责身份认证,包含Principals(身份)和Credentials(凭证);SecurityManager是架构核心,协调内部组件运作;Realm则是连接Shiro与应用数据的桥梁,用于访问用户账户及权限信息。通过学习,您将掌握Shiro的基本原理及其在项目中的应用。
504 0
|
消息中间件 Java 微服务
微服务——SpringBoot使用归纳——Spring Boot中集成ActiveMQ——发布/订阅消息的生产和消费
本文详细讲解了Spring Boot中ActiveMQ的发布/订阅消息机制,包括消息生产和消费的具体实现方式。生产端通过`sendMessage`方法发送订阅消息,消费端则需配置`application.yml`或自定义工厂以支持topic消息监听。为解决点对点与发布/订阅消息兼容问题,可通过设置`containerFactory`实现两者共存。最后,文章还提供了测试方法及总结,帮助读者掌握ActiveMQ在异步消息处理中的应用。
590 0