使用SpingMVC完成注册登录、多个文件的上传、文件列表显示、下载文件、未登录拦截等功能。

前言

使用SpingMVC完成注册登录、多个文件的上传、文件列表显示、下载文件、未登录拦截等功能。
注册的用户和下载的文件名存在session中。

一、使用效果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

二、实现代码

2.1配置文件

2.1.1pom.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.blb</groupId>
  <artifactId>springmvcfileuploadanddownload</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>springmvcfileuploadanddownload Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

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

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.30.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.16</version>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
    </dependency>

    <!--    jackson-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.12.1</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.12.1</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.12.1</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.75</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>springmvcfileuploadanddownload</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

2.1.2web.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>
    <multipart-config />
  </servlet>

  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!-- 解决文件名显示编码问题之配置过滤器 -->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>

  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

</web-app>

2.1.3springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvs="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://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.blb.controller"/>


    <!--视图解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

<!--    启用MVC配置-->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg name="defaultCharset" value="UTF-8"/>
            </bean>
            <!--    <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
            <property name="defaultCharset" value="UTF-8"/>
        </bean>-->
        </mvc:message-converters>
    </mvc:annotation-driven>
<!--    拦截器-->
        <mvs:interceptors>
            <mvc:interceptor>
                <mvc:mapping path="/index_"/>
                <bean class="com.blb.interceptor.Interceptor1"/>
            </mvc:interceptor>

        </mvs:interceptors>

<!--    异常页面-->
<!--    <bean class="com.blb.exception.ExceptionResolver"/>-->

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="defaultCharset" value="UTF-8"/>
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
</beans>

2.2webapp

2.2.1sign.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>注册页面</title>
</head>
<body>
<h1>注册</h1>
<form action="sign" method="post">
  姓名:  <input type="text" name="name"> <br />
  密码:  <input type="password" name="password"> <br />
    <input type="submit" > <br />
 </form>

</body>
</html>

2.2.2login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录页面</title>
</head>
<body>
<h1>登录</h1>
<form method="post" action="login">
    用户名:<input name="name"> <br />
    密码:<input type="password" name="password"> <br />
    ${msg} <br />
    <input type="submit">
</form>

</body>
</html>

2.2.3index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>欢迎${username}登录成功</h1>
<form action="upload" method="post" enctype="multipart/form-data">
        <input type="file" name="files" multiple="multiple" /> <br />
        <input type="submit" name="上传"> <br />
</form>

<h1>文件列表</h1>
<br>
<c:forEach items="${fileList}" var="file">
    <a href="/download/${file}">${file} </a> <br />
</c:forEach>
</body>
</html>

2.3java

2.3.1entity实体类-User

package com.blb.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@AllArgsConstructor
@Data
public class User {
    private String name;
    private String password;
}

2.3.2interceptor拦截器

package com.blb.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 Interceptor1 implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String username = (String) request.getSession().getAttribute("username");
        //未登录,则去登录
        System.out.println("登录的用户名"+username);
        if(username == null){
            response.sendRedirect("login_");
            return false;
        }else{
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
     /*   if (httpServletRequest.getSession().getAttribute("username")==null){
            modelAndView.setViewName("login_");
        }*/

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

2.3.3controller层

2.3.3.1ViewController
package com.blb.controller;

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

@Controller
public class ViewController {

    @RequestMapping("{view}_")
    public String view(@PathVariable("view") String view) {
        return view;
    }
}

2.3.3.2UserController
package com.blb.controller;

import com.blb.entity.User;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

@Controller
@SessionAttributes(value = {"user"})
public class UserController {
    private ArrayList<User> userList = new ArrayList<>();
    private ArrayList<String> fileList = new ArrayList<>();

    /**
     *
     * @param session
     */
    public void findFile(HttpSession session){
        if (!fileList.isEmpty()){
            fileList.clear();
        }
        File file = new File("D:\\upload");
        File[] fileList1 = file.listFiles();
        for (File f:fileList1) {
            if (f.isFile()) {
                fileList.add(f.getName());
            }
        }
        session.setAttribute("fileList",fileList);
    }

    @RequestMapping("")
    public String index() {
        return "redirect:sign_";
    }

    @RequestMapping("sign")
    public String sign(String name, String password, Model model) {
        User user = new User(name, password);
        System.out.println("注册的"+user);
        userList.add(user);
        model.addAttribute("user", userList);
        System.out.println(userList);
        return "redirect:login_";
    }

    @RequestMapping("login")
    public String login(String name, String password, RedirectAttributes model, HttpSession session){
        System.out.println(name);
        System.out.println(password);
        for (User u :userList) {
            if (u.getName().equals(name)){
                if (u.getPassword().equals(password)){
                    session.setAttribute("userList",userList);
                    session.setAttribute("username" ,name);
                    findFile(session);
                    System.out.println(fileList);
                    return "redirect:index_";
                }else {
                    model.addFlashAttribute("msg", "密码错误");
                    return "redirect:login_";
                }
            }
        }
        model.addFlashAttribute("msg", "用户名不存在");
        return "redirect:login_";
    }

    @PostMapping("upload")
    public String upload(MultipartFile[] files,HttpSession session) throws IOException {
        for(MultipartFile file:files){
            File file1 = new File("D:\\upload\\" + file.getOriginalFilename());
            if (!file1.getParentFile().exists()){
                file1.getParentFile().mkdir();
            }
            file.transferTo(file1);
        }
        findFile(session);
        System.out.println(fileList);
        return "redirect:index_";
    }

    @GetMapping("download/{file:.+}")
    public ResponseEntity download(@PathVariable String file) throws IOException {
        File file1 = new File("D:\\upload\\" + file);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return  new ResponseEntity(FileCopyUtils.copyToByteArray(file1), httpHeaders, HttpStatus.OK);
    }

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱喝皮蛋瘦肉粥的小饶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值