2021-04-20

SpringMVC

SpringMVC的文件上传

1. 创建项目,完善结构,导入依赖,配置web.xml

<!-- 配置开发SpringMVC所以来的jar包 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.1.5.RELEASE</version>
</dependency>
<!-- 配置ServletAPI依赖 -->
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>
<!-- commons-fileupload组件 -->
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>

2. 创建SpringMVC配置文件

<?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
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    <!--开启注解-->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!--配置自动扫描包-->
    <context:component-scan base-package="com.wangxing.springmvc.controller"></context:component-scan>
    <!-- 视图解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--maxUploadSize上传文件的大小  -->
        <property name="maxUploadSize" value="104857600" />
        <!--maxInMemorySize内存大小 -->
        <property name="maxInMemorySize" value="4096" />
        <!--defaultEncoding默认字符编码 -->
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>
</beans>

3. 创建文件上传页面,和成功的页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>
    <!--
       1.form表单的method属性一定是post
       2.enctype属性一定要设置且取值multipart/form-data
        enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码
        application/x-www-form-urlencoded----在发送前编码所有字符(默认)
        multipart/form-data----不对字符编码。在使用包含文件上传控件的表单时,必须使用该值。
        text/plain---空格转换为 "+" 加号,但不对特殊字符编码。
       3.文件上传控件---<input type="file" name="myfile">
    -->
    <form action="upload.do" method="post" enctype="multipart/form-data">
        <input type="file" name="myfile"><br>
        <input type="submit" value="上传">
    </form>
</body>
</html>

4. 创建处理文件上传请求的控制器

package com.wangxing.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Iterator;
//文件上传控制器
@Controller
public class UploadController {
    @RequestMapping(value = "/upload.do",method = RequestMethod.POST)
    public ModelAndView  upload(HttpServletRequest request)throws Exception{
        ModelAndView  mav=new ModelAndView();
        //处理包含有文件的http请求
        //1. 将当前类中的ServletContext对象转换成CommonsMultipartResolver
        ServletContext servletContext=request.getSession().getServletContext();
        CommonsMultipartResolver commonsMultipartResolver=new CommonsMultipartResolver(servletContext);
        //2.检验HttpServletRequest是否是一个文件上传请求
        if(commonsMultipartResolver.isMultipart(request)){
            //3.将HttpServletRequest请求转换成文件上传请求
            MultipartHttpServletRequest multipartreq=(MultipartHttpServletRequest)request;
            //4.从文件上传请求中得到得到文件名称
            Iterator<String> itname=multipartreq.getFileNames();
            while(itname.hasNext()){
                 //得到input元素的name属性值
                String nameshuxing=itname.next().toString();  //myfile
                //根据name属性值得到上传来的文件对象
                MultipartFile multipartfile=multipartreq.getFile(nameshuxing);
                String newfilename=""; //保存上传来的文件的名称
                if(multipartfile!=null){
                    //得到被上传来的文件的真实名称【test.html】
                    String  zhenFileName=multipartfile.getOriginalFilename();
                    //得到文件的后缀名[.html]
                    String houzhuiming=zhenFileName.substring(zhenFileName.lastIndexOf("."));
                    //得到系统时间的毫秒数,将来作为文件的名称
                    long haomiaoshu=System.currentTimeMillis();
                    newfilename=haomiaoshu+houzhuiming;
                    //获取项目的根目录
                    String realPath = servletContext.getRealPath("/upload");
                    //创建保存文件的目录
                    File uploadpicdir = new File(realPath);
                    if(!uploadpicdir.exists()){
                        //创建upload目录
                        uploadpicdir.mkdirs();
                    }
                    //组织一个保存文件的对象【文件保存目录+文件名称】
                    String pathfile=uploadpicdir.getAbsolutePath()+File.separator+newfilename;
                    System.out.println(pathfile);
                    File saveFile=new File(pathfile);
                    //保存文件到本地磁盘
                    multipartfile.transferTo(saveFile);
                }
                     //得到上传成功以后的文件的http访问地址
                    String reqURL=request.getRequestURL().toString();
                    reqURL=reqURL.substring(0,reqURL.lastIndexOf("/"));
                    reqURL=reqURL+"/upload/"+newfilename;
                    //http://127.0.0.1:8080/upload/xxxxxx.jpg
                    System.out.println("reqURL=="+reqURL);
            }
            mav.setViewName("success.html");
        }
        return mav;
    }
}

5. 部署测试

SpringMVC的文件下载

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>
    <h1><a href="dowload.do?myfile=avatar.png">下载avatar.png</h1>
    <h1><a href="dowload.do?myfile=bgcolor.html">下载bgcolor.html</h1>
</body>
</html>
package com.wangxing.springmvc.controller;
import org.apache.commons.io.FileUtils;
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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
@Controller
public class DowloadController {
    @RequestMapping(value = "/dowload.do",method = RequestMethod.GET)
    public ResponseEntity<byte[]> dowloadMethod(HttpServletRequest req)throws Exception{
        //得到请求中的文件名称
        String filename=req.getParameter("myfile");
        String realPath = req.getSession().getServletContext().getRealPath("/upload");
        //创建保存文件的目录的文件对象
        File uploadpicdir = new File(realPath);
        //创建被下载的文件对象
        File file=new File(uploadpicdir,filename);
        System.out.println(file.getAbsolutePath());
        //设置http协议头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment",filename);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
    }
}

SSM

1. 创建数据库表

用户基本信息表

create  table t_user(
user_id int primary key auto_increment,
user_name varchar(20),
user_age int,
user_address varchar(30)
);

2. 创建项目,完善结构

3. 导入依赖

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.1.5.RELEASE</version>
</dependency>
<!-- spring-jdbc -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.1.5.RELEASE</version>
</dependency>
<!-- spring_tx -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>5.1.5.RELEASE</version>
</dependency>
<!-- MyBatis依赖 -->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.6</version>
</dependency>
<!-- mybatis-spring 整合包 -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.1</version>
</dependency>
<!-- mysql数据库驱动 -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.38</version>
</dependency>
<!--druid 阿里的连接池-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.7</version>
</dependency>
<!-- 配置开发SpringMVC所以来的jar包 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.1.5.RELEASE</version>
</dependency>
<!-- 配置ServletAPI依赖 -->
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.8</version>
</dependency>

4. 配置web.xml文件

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>dispatcherServle</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServle</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

5. 创建javabean

6. 创建数据访问接口

7. 在resources目录下创建数据连接文件和SQL映射文件

8. 创建业务访问接口以及实现类【@Service/注入Mapper】

9. 创建控制器类以及请求处理方法【注入Service】

package com.wangxing.ssm.controller;
import com.wangxing.ssm.bean.ResBean;
import com.wangxing.ssm.bean.UserBean;
import com.wangxing.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@RequestMapping(value = "/user")
public class UserBeanController {
    @Autowired
    private UserService userService;
    @RequestMapping(value = "/add.do")
    @ResponseBody
    public ResBean  addUserBean(UserBean userBean){
        try{
            userService.insertUser(userBean);
            return new ResBean(true,"添加成功");
        }catch(Exception e){
            e.printStackTrace();
            return new ResBean(false,"添加失败");
        }
    }
    @RequestMapping(value = "/update.do")
    @ResponseBody
    public ResBean  updateUserBean(UserBean userBean){
        try{
            userService.updateUser(userBean);
            return new ResBean(true,"修改成功");
        }catch(Exception e){
            e.printStackTrace();
            return new ResBean(false,"修改失败");
        }
    }
    @RequestMapping(value = "/findOne.do")
    @ResponseBody
    public UserBean  findOneUserBean(int userid) {
        UserBean userBean = null;
        try {
            userBean=userService.selectUserById(userid);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userBean;
    }
    @RequestMapping(value = "/findAll.do")
    @ResponseBody
    public List<UserBean>  findAllUserBean() {
        List<UserBean> userBeanList = null;
        try {
            userBeanList=userService.selectUser();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userBeanList;
    }
    @RequestMapping(value = "/delete.do")
    @ResponseBody
    public ResBean  deleteUserBean(int userid) {
        try {
            userService.deleteUser(userid);
            return new ResBean(true,"删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new ResBean(false,"删除失败");
        }
    }
}

10. 在resources目录下创建并配置applicationContext.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:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--开启注解-->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!--配置自动扫描包-->
    <context:component-scan base-package="com.wangxing.ssm"></context:component-scan>
    <!--配置加载mydata.properties-->
    <context:property-placeholder location="classpath:mydata.properties"></context:property-placeholder>
    <!--配置数据源-->
    <!-- com.alibaba.druid.pool.DruidDataSource-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${mydriver}"></property>
        <property name="url" value="${myurl}"></property>
        <property name="username" value="${myusername}"></property>
        <property name="password" value="${mypassword}"></property>
    </bean>
    <!-- 配置SqlSessionFactory -->
    <!-- org.mybatis.spring.SqlSessionFactoryBean-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
        <!--注入sql映射文件路径-->
        <property name="mapperLocations" value="classpath:mapper/UserBeanMapper.xml"></property>
    </bean>
    <!--配置扫描数据库访问接口包,创建数据库访问接口对象-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.wangxing.ssm.mapper"></property>
    </bean>
</beans>

 

猜你喜欢

转载自blog.csdn.net/weixin_53123681/article/details/115897039