SpringMVC一个拦截器和文件上传下载的完整程序代码示例以及IDEA2024部署报错 找不到此 Web 模块的 out\artifacts\..问题

news2024/10/20 4:40:58

一、SpringMVC一个拦截器和文件上传下载的完整程序代码示例

        本文章是一个 SpringMVC拦 截器和文件上传下载的完整程序代码示例,使用的开发工具是 IntelliJ IDEA 2024.1.6 (Ultimate Edition), 开发环境是 OpenJDK-21 java version 21.0.2。Tomcatt版本为9.0.96,整体程序目录结构如下:

        本程序演示了 SpringMVC中的  interceptor 拦截器的使用,基于此拦截器实现对其它控制器如后台控制器中用户管理的操作程序示例。同时在用户管理控制器添加了基于 spring 的 CommonsMultipartResolver 类实现 文件上传和文件下载的代码程序示例。

A、xml 配置文件

1. pom.xml 配置文件

<?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>com.kermit</groupId>
    <artifactId>springmvc-05</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.39</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>

    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

</project>

2. 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">
    
    <servlet>
        <servlet-name>springmvc</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>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


</web-app>

3. resource目录下springmvc.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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.kermit.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>

<!--    文件上传的固定配置,不用修改-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
        <property name="defaultEncoding" value="utf-8" />
<!--        最大上传大小 100M-->
        <property name="maxUploadSize"  value="104857600" />
        <property name="maxUploadSizePerFile" value="104857600" />
        <property name="maxInMemorySize" value="10485760" />
        <property name="uploadTempDir" value="/WEB-INF/tmp" />
    </bean>

<!--    拦截器配置,/** 匹配所有, /admin/* 匹配 admin下面的请求。-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.kermit.interceptor.AdminInterceptor" />
        </mvc:interceptor>
    </mvc:interceptors>

</beans>

B、JAVA程序文件

1. controller下的LoginController 控制器程序

package com.kermit.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    //测试拦截器,并结合 session 试验登录 退出的基本逻辑。
    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping("/logincheck")
    public String logincheck(HttpSession session){
        session.setAttribute("admin", "kermit");
        return "redirect:/admin/user";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.setAttribute("admin", null);
        return "redirect:/login";
    }
}

2. controller下的UserController 控制器程序

package com.kermit.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@Controller
public class UserController {

    //试拦截器
    @RequestMapping("/admin/user")
    public String index(Model model) {
        model.addAttribute("message", "Hello World");
        return "admin/user";
    }

    //测试spring 文件上传下载
    @ResponseBody
    @RequestMapping("/admin/upload")
    public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        //处理用户上传的文件
        // 需要在 spring 配置里写一个 bean配置,固定的。
        String path = request.getServletContext().getRealPath("/upload");
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdirs();
        }

        System.out.println("realpath:"+ realPath);
        file.transferTo(new File(realPath + "/" + file.getOriginalFilename()));
        return "upload success.";
    }

    @ResponseBody
    @RequestMapping("/admin/download/{filename}")
    public String download(@PathVariable("filename") String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {

        String path = request.getServletContext().getRealPath("/upload");
        if(filename == "") filename = "test.jpg";

        //清空BUFFER;
        response.reset();
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");

        File file = new File(path, filename);
        InputStream inputStream = new FileInputStream(file);
        OutputStream outputStream = response.getOutputStream();

        byte[] buffer = new byte[1024];
        int index=0;
        while((index=inputStream.read(buffer))!=-1){
            outputStream.write(buffer, 0 ,index);
            outputStream.flush();
        }

        outputStream.close();
        inputStream.close();
        return "download success.";
    }
}

3. 拦截器 interceptor 下的 AdminInterceptor

package com.kermit.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AdminInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("------------------pre-----------------");

        //登录页允许访问
        if(request.getRequestURI().contains("login")){
            return true;
        }

        //已登录用户直接放行
        if(request.getSession().getAttribute("admin") != null) {
            return true;
        }

        //其它页面如果未有 session 跳转
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
        return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
        System.out.println("------------------拦截后-----------------");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("------------------清理后-----------------");
        // HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}

C、视图文件

1.  jsp下的login.jsp文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录页面</title>
</head>
<body>
未登录想直接去后台:被阻止
<a href="${pageContext.request.contextPath}/admin/user" >
    <input type="button" value="直接去后台" />
</a>

已输入账号密码登录:<br><br>
    <a href="${pageContext.request.contextPath}/logincheck" >
        <input type="button" value="跳转验证成功后进入后台" />
    </a>

</body>
</html>

2.  jsp下的index.jsp文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${message}
</body>
</html>

3.  jsp下admin目录中的user.jsp文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>成功进入管理后台-用户页面</h1>
<br>

<h2>在此页面测试上传一个文件</h2>
<form action="${pageContext.request.contextPath}/admin/upload" method="post" enctype="multipart/form-data">
    Select file to upload:
    <input type="file" name="file" id="file">
    <input type="submit" value="Upload File" name="submit">
</form>

<h2>使用流下载一个文件</h2>
<a href="${pageContext.request.contextPath}/admin/download/24112.jpg">点击下载</a>

<br>
清理 session 退出<br><br>
<a href="${pageContext.request.contextPath}/logout" >
    <input type="button" value="退出后台" />
</a>
</body>
</html>

二、IDEA2024部署找不到此Web模块out\artifacts\等问题

1.  IDEA2024部署报错 找不到此 Web 模块的 out\artifacts\问题

       在使用 IDEA2024 开发项目时,多次修改了项目名称,移动了项目路径,导致出现了一些问题,完整的问题修复已经无法再完整记录。进行了各种尝试,部署都不能成功,报错。

        在这个过程中我删除了工件,然后点击+号重建,期间碰到报错:IDEA 无法保存设置 源根 D:XXXX在模块XXX中重复之类的错误。最后成功的一次是删除工件之后,在新建中选择 WEB应用程序展开型时选择了【基于模块】,最后才成功启动了项目。如下图所示:

最后成功后发现浏览器上的路径也有细微差别:

http://localhost:8080/springmvc_05_war_exploded/login   成功
http://localhost:8080/springmvc_05_Web_exploded/login  失败

         一个是war地址,一个是web地址。这是Web项目部署中,有两种常见的 exploded 形式:Web exploded 和 War exploded。Web exploded 都是将一个已经打包好的 Web 应用(通常是一个 WAR 文件)解压到指定的目录中。但两者有所不同,与 Web exploded的区别在于War exploded 只会将 WAR 文件中的类文件和库文件解压到指定的目录中,而不包括其他资源文件。这应该就是在出现问题的时候发现 jsp目录、web.xml文件都没有在 out 目录中显示。

2. MVN仓库网站 https://mvnrepository.com/ 总是要验证真人烦

        MVN仓库网站 https://mvnrepository.com/ 总是要验证真人烦,真觉得很烦!总是显示:正在验证你是否为真人,请耐心等待!而且我不只碰到过一次,它持续在这个页面循环跳了多次,还出现过失败!我直接浏览器里访问还不是真人吗?可见他的技术也就这个鸟样!这么明显的真人请求都能验错!

3. springmvc开发时getServletContex() 方法报红

        另外在使用 springmvc开发时,一段文件上传的代码里需要  HttpServletRequest request) 
request.getServletContext().getRealPath getServletContex() 方法报红找不到,相关的包也已经导入,是因为导入的包: javax.servlet-api 版本过低,目前使用的是2.5版本,导入 3.1.0 或者4.0.1 最新版都能解决。 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2219004.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Flux.concat 使用说明书

public static <T> Flux<T> concat(Iterable<? extends Publisher<? extends T>> sources)Concatenate all sources provided in an Iterable, forwarding elements emitted by the sources downstream. 连接可迭代集合中提供的所有源&#xff0c;将…

【web】JDBC

项目连接数据库 右侧导航栏找到databsae 如果没有驱动&#xff0c;先下载驱动 填写数据库用户名密码 勾选对应的表即可 JDBC代码流程 1,配置信息 2,加载驱动 从MySQL Connector/J 5.1版本开始&#xff0c;推荐使用com.mysql.cj.jdbc.Driver这个新的驱动类。 3,链接数据库…

【MR开发】在Pico设备上接入MRTK3(三)——在Unity中运行MRTK示例

在前面的文档中&#xff0c;介绍了如何在Unity工程中配置号MRTK和Pico SDK 【MR开发】在Pico设备上接入MRTK3&#xff08;一&#xff09;在Unity中导入MRTK3依赖【MR开发】在Pico设备上接入MRTK3&#xff08;二&#xff09;在Unity中配置Pico SDK 本文将介绍如何运行一个简单…

SQL进阶技巧:如何找出开会时间有重叠的会议室?| 时间区间重叠问题

目录 0 场景描述 1 数据准备 2 问题分析 方法1:利用 lateral view posexplode()函数将表展开成时间明细表 方法2:利用数学区间讨论思想求解 3 小结 0 场景描述 有7个会议室,每个会议室每天都有人开会,某一天的开会时间如下: 查询出开会时间有重叠的是哪几个会议室?…

Agentic RAG(基于智能体的检索增强生成)是检索增强生成(Retrieval-Augmented Generation,RAG)技术的一种高级形式

Agentic RAG&#xff08;基于智能体的检索增强生成&#xff09;是检索增强生成&#xff08;Retrieval-Augmented Generation&#xff0c;RAG&#xff09;技术的一种高级形式&#xff0c;它通过引入人工智能代理&#xff08;Agent&#xff09;的概念&#xff0c;为语言模型赋予了…

C#从零开始学习(用unity探索C#)(unity Lab1)

初次使用Unity 本章所有的代码都放在 https://github.com/hikinazimi/head-first-Csharp Unity的下载与安装 从 unity官网下载Unity Hub Unity的使用 安装后,注册账号,下载unity版本,然后创建3d项目 设置窗口界面布局 3D对象的创建 点击对象,然后点击Move Guzmo,就可以拖动…

018_FEA_Structure_Static_in_Matlab三维结构静力学分析

刹车变形分析 本示例展示了如何使用 MATLAB 软件进行刹车变形分析。 这个例子是Matlab官方PDE工具箱的第一个例子&#xff0c;所需要的数据文件都由Matlab提供&#xff0c;包括CAD模型文件。 步骤 1: 导入 CAD 模型 导入 CAD 模型&#xff0c;这里使用的是一个带有孔的支架模…

HTTP cookie 与 session

一种关于登录的场景演示 - B 站登录和未登录 问题&#xff1a;B 站是如何认识我这个登录用户的&#xff1f;问题&#xff1a;HTTP 是无状态&#xff0c;无连接的&#xff0c;怎么能够记住我&#xff1f; 一、引入 HTTP Cookie 定义 HTTP Cookie&#xff08;也称为 Web Cooki…

【最新华为OD机试E卷-支持在线评测】VLAN资源池(100分)多语言题解-(Python/C/JavaScript/Java/Cpp)

🍭 大家好这里是春秋招笔试突围 ,一枚热爱算法的程序员 💻 ACM金牌🏅️团队 | 大厂实习经历 | 多年算法竞赛经历 ✨ 本系列打算持续跟新华为OD-E/D卷的多语言AC题解 🧩 大部分包含 Python / C / Javascript / Java / Cpp 多语言代码 👏 感谢大家的订阅➕ 和 喜欢�…

R语言复杂抽样调查数据统计描述和分析

gtsummary包中tbl_svysummary提供了统计描述&#xff1b;tableone包中的svyCreateTableOne提供了统计比较&#xff1b;原始描述和比较可以是有table1包。 #测试数据 library(survey) setwd("F://") data(Titanic) sur_des<-survey::svydesign(~1, data as.data.…

Leetcode—1117. H2O 生成【中等】(多线程)

2024每日刷题&#xff08;182&#xff09; Leetcode—1117. H2O 生成 C实现代码 class H2O { public:H2O() {sem_init(&hydrogenSem, 0, 1);sem_init(&oxygenSem, 0, 0);}~H2O() {sem_destroy(&hydrogenSem);sem_destroy(&oxygenSem);}void hydrogen(functio…

重学SpringBoot3-Spring WebFlux简介

更多SpringBoot3内容请关注我的专栏&#xff1a;《SpringBoot3》 期待您的点赞&#x1f44d;收藏⭐评论✍ 重学SpringBoot3-Spring WebFlux简介 1. 什么是 WebFlux&#xff1f;2. WebFlux 与 Spring MVC 的区别3. WebFlux 的用处3.1 非阻塞 I/O 操作3.2 响应式编程模型3.3 更高…

机械视觉光源选型

光源是机器视觉系统的重要组成部分&#xff0c;直接影响到图像的质量&#xff0c;进而影响到系统的性 能。在一定程度上&#xff0c;光源的设计与选择是机器视觉系统成败的关键。光源最重要的功能就 是使被观察的图像特征与被忽略的图像特征之间产生最大的对比度&#xff0c;…

RISC-V笔记——RVWMO基本体

1. 前言 RISC-V使用的内存模型是RVWMO(RISC-V Weak Memory Ordering)&#xff0c;它是Release Consistency的扩展&#xff0c;因此&#xff0c;RVWMO的基本特性类似于RC模型。 2. RC模型 Release consistency(RC)的提出是基于一个观察&#xff1a;将所有同步操作用FENCE围在一…

基于x86_64汇编语言简单教程1: 环境预备与尝试

目录 前言 环境配置 基本硬件与操作系统要求 WSL VSCode基本配置(For Windows) 安装基本的依赖 为您的VSCode安装插件&#xff1a; 学习要求 入门 先试试味道 前言 笔者最近正在梭哈使用NASM汇编器的x86 32位汇编&#xff0c;笔者这里记录一下一个晚上的成果。 环境…

【含开题报告+文档+PPT+源码】贫困儿童一对一扶贫帮扶系统设计与实现

开题报告 根据《中华人民共和国慈善法》第五十八条规定&#xff0c;慈善组织确定慈善受益人&#xff0c;应当坚持公开、公平、公正的原则&#xff0c;不得指定慈善组织管理人员的利害关系人作为受益人[2]。以上所列举的平台基本没有做到公开、公平、公正的原则&#xff0c;例如…

一起搭WPF架构之livechart的MVVM使用介绍

一起搭WPF架构之livechart使用介绍 前言ModelViewModelView界面设计界面后端 效果总结 前言 简单的架构搭建已经快接近尾声了&#xff0c;考虑设计使用图表的形式将SQLite数据库中的数据展示出来。前期已经介绍了livechart的安装&#xff0c;今天就详细介绍一下livechart的使用…

应用层协议 序列化

自定义应用层协议 例子&#xff1a;网络版本计算器 序列化反序列化 序列化&#xff1a;将消息&#xff0c;昵称&#xff0c;日期整合成消息-昵称-日期 反序列化&#xff1a;消息-昵称-日期->消息&#xff0c;昵称&#xff0c;日期 在序列化中&#xff0c;定义一个结构体…

Python案例小练习——小计算器

文章目录 前言一、代码展示二、运行展示 前言 这是用python实现一个简单的计器。 一、代码展示 def calculate(num1, op, num2):if op "":return float(num1) float(num2)elif op "-":return float(num1) - float(num2)elif op "*":return…

案例分享-优秀蓝色系UI界面赏析

蓝色UI设计界面要提升舒适度&#xff0c;关键在于色彩搭配与对比度。选择柔和的蓝色调作为主色&#xff0c;搭配浅灰或白色作为辅助色&#xff0c;能营造清新、宁静的氛围。同时&#xff0c;确保文字与背景之间有足够的对比度&#xff0c;避免视觉疲劳&#xff0c;提升阅读体验…