Spring MVC Implements Upload and Download Function

Keywords: xml Java Spring Mybatis

Configuration resources (jar package)

 

Tidy up front-end pages:

 

Write several core configuration files (application Context + wed. XML + jdbc. properties + log4j + spring MVC. xml)

All in the src directory:

applicationContext-mybatis.xml (file associated with configuration and mybatis)

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
    <!--Connect to the database-->
    <bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${driver1}"/>
        <property name="url" value="${url1}"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    <!--Get sqlsession-->
    <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="ds"/>
        <property name="typeAliasesPackage" value="com.bjsxt.pojo"/>
    </bean>

    <!--scanning mapper file-->
    <bean id="mapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="factory"/>
        <property name="basePackage" value="com.bjsxt.mapper"/>
    </bean>
</beans> 

 

applicationContext-service.xml (Configuration service layer):

<!--Scanning Business Layer Annotations-->
    <context:component-scan base-package="com.bjsxt.service.impl"></context:component-scan>

 

If transactional operations are required:

<!--Configuration declaration transaction-->
    <bean id="TransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="ds"></property>
    </bean>

    <!--Scanning transaction annotations-->
    <tx:annotation-driven></tx:annotation-driven>

 

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>mvc</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>

    </servlet>
    <servlet-mapping>
        <servlet-name>mvc</servlet-name>
        <!--Handle jsp All available-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext-*.xml</param-value>
    </context-param>
    <!--Configuration listener-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

 

MVC stratification:

 

Control layer:

Because it is to test the function of uploading and downloading, I did not write the corresponding control layer separately, so I wrote a file and accessed it with annotations.

package com.bjsxt.controller;

import com.bjsxt.pojo.Student;
import com.bjsxt.service.StudentService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.font.MultipleMaster;
import java.io.*;
import java.util.List;
import java.util.UUID;

@Controller
public class MyCon {

    @Autowired
    StudentService ss;

    //Download Picture Operation
    @RequestMapping("download")
    public void download(String filename, String filetype, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //Get the image path of the server
        String realPath = req.getServletContext().getRealPath("/upload");

        //Get the name and type of the image String filename,String filetype

        File file=new File(realPath+"/"+filename);

        //Write the file
        InputStream inputStream=new FileInputStream(file);

        //Setting properties to download locally
        //1. Setting Length
        resp.setContentLength((int)file.length());

        //2. Setting type
        resp.setContentType(filetype);

        //3. Setting Response Header
        resp.setHeader("Content-Disposition","attachment;filename="+filename);

        //Write read files locally
        OutputStream outputStream = resp.getOutputStream();
        IOUtils.copy(inputStream,outputStream);

        //Closed flow
        outputStream.close();
        inputStream.close();


    }

    @RequestMapping("filee")
    public String filee(String uname, String pwd, MultipartFile fil) throws IOException {
        System.out.println(uname+":"+pwd);
        System.out.println(fil.getName()+"---"+fil.getSize()+"---"+fil.getContentType()+"---"+fil.getOriginalFilename());
        fil.transferTo(new File("F:/img/"+fil.getOriginalFilename()));
        return "redirect:/index.jsp";
    }

    @RequestMapping("insertStu")
    public String insertStu(String name,int age,Double score, MultipartFile filename, HttpServletRequest req) throws IOException {
        /*System.out.println(uname+":"+pwd);
        System.out.println(fil.getName()+"---"+fil.getSize()+"---"+fil.getContentType()+"---"+fil.getOriginalFilename());*/

       /* if (fil.getSize()>2*1024){
            req.setAttribute("error","The largest upload file is 2kb ";
            return "forward:/zhuce.jsp";
       }*/
        String realPath = req.getServletContext().getRealPath("/upload");
        /*To prevent the same file name, overwrite the original file*/
        String uuid = UUID.randomUUID().toString();
        //The suffix name of the intercepted picture
        String filname = filename.getOriginalFilename().substring(filename.getOriginalFilename().lastIndexOf("."));
        String fname=uuid+filname;
        File file=new File(realPath);
        if (!file.exists()){
            file.mkdirs();
        }
        //File upload completed
        filename.transferTo(new File(file,fname));

        Student student=new Student();
        student.setAge(age);
            student.setFilename(fname);
        student.setName(name);
        student.setScore(score);
        student.setFiletype(filename.getContentType());
        //Call the business layer
        int addstu = ss.addstu(student);
        if (addstu>0){
            //Insert success
            return "redirect:/findall";
        }else {
            //Insert failure
            req.setAttribute("error","Insert failure");
            return "forward:/save.jsp";

        }

    }

    @RequestMapping("findall")
    public String findall(HttpServletRequest req){
        List<Student> students = ss.finall();
        req.setAttribute("students",students);
        return "forward:/stuList.jsp";
    }

}

 

Mapper interface:

package com.bjsxt.mapper;

import com.bjsxt.pojo.Student;

import java.util.List;

public interface StudentMapper {
    int insetstu(Student student);

    List<Student> selAll();
}

 

Mapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bjsxt.mapper.StudentMapper">
    <insert id="insetstu" parameterType="student" >
        insert into student values(default,#{name},#{age},#{score},#{filename},#{filetype})
    </insert>

    <select id="selAll" resultType="Student">
        select * from student
    </select>
</mapper>

 

Service interface:

package com.bjsxt.service;

import com.bjsxt.pojo.Student;

import java.util.List;

public interface StudentService {
    public int addstu(Student student);

    public List<Student> finall();
}

 

Service implementation class

package com.bjsxt.service.impl;

import com.bjsxt.mapper.StudentMapper;
import com.bjsxt.pojo.Student;
import com.bjsxt.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("ssi")
public class StudentServiceImpl implements StudentService {

    @Autowired
    StudentMapper studentMapper;

    @Override
    public int addstu(Student student) {
        int insetstu = studentMapper.insetstu(student);
        return insetstu;
    }

    @Override
    public List<Student> finall() {
        List<Student> students = studentMapper.selAll();
        return students;
    }
}

 

The pojo entity class:

package com.bjsxt.pojo;

import java.io.Serializable;

public class Student implements Serializable {
    private  int id;
    private  String name;
    private  int age;
    private  double score;
    private  String filename;
    private  String filetype;

    public Student(int id, String name, int age, double score, String filename, String filetype) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.score = score;
        this.filename = filename;
        this.filetype = filetype;
    }

    public Student() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }

    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    public String getFiletype() {
        return filetype;
    }

    public void setFiletype(String filetype) {
        this.filetype = filetype;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                ", filename='" + filename + '\'' +
                ", filetype='" + filetype + '\'' +
                '}';
    }
}

 

Achieving results:

 

Posted by rReLmy on Sun, 06 Oct 2019 13:38:47 -0700