前言:

本文内容:登录判断验证、文件上传下载、总结

推荐免费SpringMVC基础教程视频:【狂神说Java】SpringMVC最新教程IDEA版通俗易懂_哔哩哔哩_bilibili

SpringMVC笔记代码下载地址:

蓝奏云:下载地址 密码:joker

百度云:下载地址 提取码:pzla

登录判断验证

  1. 新建main.jsplogin.jsp

    main.jsp

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    <title>首页</title>
    </head>
    <body>
    <h1>首页</h1>
    <p><a href="${pageContext.request.contextPath}/user/logout">注销登录</a></p>
    </body>
    </html>

    loign.jsp

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    <title>登录页面</title>
    </head>
    <body>
    <h2>登录</h2>
    <form action="${pageContext.request.contextPath}/user/login" method="post">
    账号:<input type="text" name="uname"><br/>
    密码:<input type="password" name="pwd"><br/>
    <input type="submit" value="登录">
    </form>
    </body>
    </html>

    index.jsp

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    <title>$Title$</title>
    </head>
    <body>
    <p>
    <a href="${pageContext.request.contextPath}/user/goLogin">登录页面</a>
    </p>
    <p>
    <a href="${pageContext.request.contextPath}/user/main">首页</a>
    </p>
    </body>
    </html>
  2. 新建LoginController

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    package com.jokerdig.config;

    import org.springframework.web.servlet.HandlerInterceptor;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;

    /**
    * @author Joker大雄
    * @data 2022/6/18 - 10:48
    **/
    public class LoginInterceptor implements HandlerInterceptor {
    // 拦截未登录访问首页

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    // 放行判断
    HttpSession session = request.getSession();

    if(session.getAttribute("uname")!=null){
    return true;
    }
    // 放行登录页面本身
    if(request.getRequestURI().contains("goLogin")){
    return true;
    }
    // 第一次登录拦截不验证session
    if(request.getRequestURI().contains("login")){
    return true;
    }

    response.sendRedirect("/user/goLogin");
    return false;
    }
    }
  3. 运行测试

    我们发现,不登录也可以直接访问首页,这是我们实际开发中所不允许的,通过拦截器拦截未登录直接访问首页的请求。

  4. 新建LoginInterceptor

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    package com.jokerdig.config;

    import org.springframework.web.servlet.HandlerInterceptor;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;

    /**
    * @author Joker大雄
    * @data 2022/6/18 - 10:48
    **/
    public class LoginInterceptor implements HandlerInterceptor {
    // 拦截未登录访问首页

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    // 放行判断
    HttpSession session = request.getSession();

    if(session.getAttribute("uname")!=null){
    return true;
    }
    // 放行登录页面本身
    if(request.getRequestURI().contains("goLogin")){
    return true;
    }
    // 第一次登录拦截不验证session
    if(request.getRequestURI().contains("login")){
    return true;
    }

    response.sendRedirect("/user/goLogin");
    return false;
    }
    }
  5. 测试访问首页,拦截成功

文件上传和下载

准备工作

SpringMVC很好的支持文件上传,但是在上下文中默认没有装配MultipartResolver,因此默认情况下不能处理文件上传工作。如果想使用文件上传功能,则要在上下问配置MultipartResolver

前端表单要求:为了能上传文件,必须将表单的method设置为POST,并将enctype设置为multipart/form-data,这样浏览器才会把用户选择的文件以二进制数据发送给服务器。

enctype属性说明:

描述
application/x-www-form-urlencoded 在发送前编码所有字符(默认)
multipart/form-data 不对字符编码。在使用包含文件上传控件的表单时,必须使用该值。
text/plain 空格转换为 “+” 加号,但不对特殊字符编码。
1
2
3
4
<form action="" enctype="multipart/form-data" method="post">
<input type="file" name="file">
<input type="submit">
</form>

简单测试

  1. 新建module,springmvc-09-file,添加web支持

  2. 配置web.xml和applicationContext.xml

  3. 在pom中引入需要的依赖

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <!--文件上传-->
    <dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
    </dependency>
    <!--javax.servlet-api-->
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    </dependency>

  4. 编写index.jsp

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    <title>文件上传</title>
    </head>
    <body>
    <form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
    <input type="file" multiple="multiple" name="file">
    <input type="submit">
    </form>
    <a href="${pageContext.request.contextPath}/download">下载</a>
    </body>
    </html>
  5. 新建UploadController

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    package com.jokerdig.controller;

    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.commons.CommonsMultipartFile;

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

    /**
    * @author Joker大雄
    * @data 2022/6/18 - 12:02
    **/
    @RestController
    public class UploadController {

    @RequestMapping("/upload")
    public String fileUpload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
    //获取文件名 : file.getOriginalFilename();
    String uploadFileName = file.getOriginalFilename();

    //如果文件名为空,直接回到首页!
    if ("".equals(uploadFileName)){
    return "redirect:/index.jsp";
    }
    System.out.println("上传文件名 : "+uploadFileName);

    //上传路径保存设置
    String path = request.getServletContext().getRealPath("/upload");
    //如果路径不存在,创建一个
    File realPath = new File(path);
    if (!realPath.exists()){
    realPath.mkdir();
    }
    System.out.println("上传文件保存地址:"+realPath);

    InputStream is = file.getInputStream(); //文件输入流
    OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); //文件输出流

    //读取写出
    int len=0;
    byte[] buffer = new byte[1024];
    while ((len=is.read(buffer))!=-1){
    os.write(buffer,0,len);
    os.flush();
    }
    os.close();
    is.close();
    return "redirect:/index.jsp";
    }

    @RequestMapping("upload2")
    public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
    //保存上传文件的设置
    String path = request.getServletContext().getRealPath("/upload");
    File realPath = new File(path);
    if (!realPath.exists()){
    realPath.mkdir();
    }
    //上传文件的地址
    System.out.println("上传文件保存地址:"+realPath);
    //通过CommonsMultipartFile的方法直接写文件(注意这个时候)

    file.transferTo(new File(realPath+"/"+file.getOriginalFilename()));

    return "redirect:/index.jsp";
    }
    // 文件下载
    @RequestMapping("/download")
    public String fileDownload(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // 文件下载
    //要下载的图片地址
    String path = request.getServletContext().getRealPath("/upload");
    String fileName = "111.txt";

    //1、设置response 响应头
    response.reset(); //设置页面不缓存,清空buffer
    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);
    //2、 读取文件--输入流
    InputStream input=new FileInputStream(file);
    //3、 写出文件--输出流
    OutputStream out = response.getOutputStream();

    byte[] buff =new byte[1024];
    int index=0;
    //4、执行 写出操作
    while((index= input.read(buff))!= -1){
    out.write(buff, 0, index);
    out.flush();
    }
    out.close();
    input.close();
    return null;
    }
    }
  6. 在applicationContext.xml中配置

    1
    2
    3
    4
    5
    <!--    配置文件上传-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="utf-8"/>
    <property name="maxUploadSize" value="10240000"/>
    </bean>
  7. 测试运行,在同学电脑上上传下载成功

    这里博主一直404,在同学的电脑上运行就没错误,/(ㄒoㄒ)/~~

总结

总结导图 【JavaWeb】JavaWeb 从入门到实战 (16)