配置资源(jar包)

将前端页面整理好:

写核心的几个配置文件(applicationContext+wed.xml+jdbc.properties+log4j+springMVC.xml)

都是在src目录下:

applicationContext-mybatis.xml(配置和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>
<!--连接数据库-->
<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> <!--获得sqlsession-->
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="ds"/>
<property name="typeAliasesPackage" value="com.bjsxt.pojo"/>
</bean> <!--扫描mapper文件-->
<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(配置service层):

<!--扫描业务层注解-->
<context:component-scan base-package="com.bjsxt.service.impl"></context:component-scan>

如果需要进行事务操作:

<!--配置声明事务-->
<bean id="TransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="ds"></property>
</bean> <!--扫描事务注解-->
<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>
<!--处理jsp都可以使用-->
<url-pattern>/</url-pattern>
</servlet-mapping> <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-*.xml</param-value>
</context-param>
<!--配置监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>

MVC分层:

控制层(controller):

由于是为了测试上传下载的功能,我并没有将功能对应的控制层分开写,就写了一个文件,用注解去访问

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; //下载图片操作
@RequestMapping("download")
public void download(String filename, String filetype, HttpServletRequest req, HttpServletResponse resp) throws IOException {
//获取服务器的图片路径
String realPath = req.getServletContext().getRealPath("/upload"); //获取图片的名称和类型 String filename,String filetype File file=new File(realPath+"/"+filename); //将文件写入
InputStream inputStream=new FileInputStream(file); //设置属性下载到本地
//1.设置长度
resp.setContentLength((int)file.length()); //2.设置类型
resp.setContentType(filetype); //3.设置响应头
resp.setHeader("Content-Disposition","attachment;filename="+filename); //将读取的文件写入本地
OutputStream outputStream = resp.getOutputStream();
IOUtils.copy(inputStream,outputStream); //关闭流
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","最大的上传文件是2kb");
return "forward:/zhuce.jsp";
}*/
String realPath = req.getServletContext().getRealPath("/upload");
/*为了防止文件名相同,覆盖原文件*/
String uuid = UUID.randomUUID().toString();
//截取图片的后缀名
String filname = filename.getOriginalFilename().substring(filename.getOriginalFilename().lastIndexOf("."));
String fname=uuid+filname;
File file=new File(realPath);
if (!file.exists()){
file.mkdirs();
}
//文件上传完毕
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());
//调用业务层
int addstu = ss.addstu(student);
if (addstu>0){
//插入成功
return "redirect:/findall";
}else {
//插入失败
req.setAttribute("error","插入失败");
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接口:

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接口:

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实现类

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;
}
}

pojo实体类:

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 + '\'' +
'}';
}
}

实现效果:

SpringMVC实现上传下载功能的更多相关文章

  1. springmvc文件上传下载简单实现案例(ssm框架使用)

    springmvc文件上传下载实现起来非常简单,此springmvc上传下载案例适合已经搭建好的ssm框架(spring+springmvc+mybatis)使用,ssm框架项目的搭建我相信你们已经搭 ...

  2. SpringMVC文件上传下载(单文件、多文件)

    前言 大家好,我是bigsai,今天我们学习Springmvc的文件上传下载. 文件上传和下载是互联网web应用非常重要的组成部分,它是信息交互传输的重要渠道之一.你可能经常在网页上传下载文件,你可能 ...

  3. JavaWeb实现文件上传下载功能实例解析

    转:http://www.cnblogs.com/xdp-gacl/p/4200090.html JavaWeb实现文件上传下载功能实例解析 在Web应用系统开发中,文件上传和下载功能是非常常用的功能 ...

  4. 【转】Android 服务器之SFTP服务器上传下载功能

    原文网址:http://blog.csdn.net/tanghua0809/article/details/47056327 本文主要是讲解Android服务器之SFTP服务器的上传下载功能,也是对之 ...

  5. 【转】Android 服务器之SFTP服务器上传下载功能 -- 不错

    原文网址:http://blog.csdn.net/tanghua0809/article/details/47056327 本文主要是讲解Android服务器之SFTP服务器的上传下载功能,也是对之 ...

  6. JavaWeb实现文件上传下载功能实例解析 (好用)

    转: JavaWeb实现文件上传下载功能实例解析 转:http://www.cnblogs.com/xdp-gacl/p/4200090.html JavaWeb实现文件上传下载功能实例解析 在Web ...

  7. SpringMVC文件上传下载

    在Spring MVC的基础框架搭建起来后,我们测试了spring mvc中的返回值类型,如果你还没有搭建好springmvc的架构请参考博文->http://www.cnblogs.com/q ...

  8. SpringMVC 文件上传下载

    目录 文件上传 MultipartFile对象 文件下载 上传下载示例 pom.xml增加 创建uploadForm.jsp 创建uploadForm2.jsp 创建userInfo.jsp spri ...

  9. java中文上传下载功能实现(自己测试项目)

    1.新建maven项目打war包 2.搭建springMVC框架 web.xml文件配置 <?xml version="1.0" encoding="UTF-8&q ...

随机推荐

  1. PHP关于access_token失效问题

    PHP关于access_token失效问题 有时候PHP设置了缓存 明明就是没有过期 但却提示失效这情况一般就是1 多个appid和secrete 生成的access_token互相覆盖了 所以 这种 ...

  2. egret编译速度慢解决方法

    egret编译速度慢解决方法 直接用增量更新egret run -a 每次改完代码 保存都会自动编译

  3. T-SQL Part IX, PIVOT and UNPIVOT

    不同于CROSS JOIN, CROSS APPLY, OUTER APPLY,MSDN文档对PIVOT和UNPIVOT 想得重视了一点,单独做了一个页面来介绍. 简单来说,PIVOT用来把行转成列, ...

  4. [LC]35题 Search Insert Position (搜索插入位置)

    ①英文题目 Given a sorted array and a target value, return the index if the target is found. If not, retu ...

  5. 【Error】Maven Dependency 下载失败问题

    原文 前言 在使用Maven私服Sonatype Nexus的时候,经常会出现依赖包找不到的问题. 此时通过浏览器去私服页面查看,发现依赖包坐标是存在的,对应的文件(比如jar文件). 或者私服上面也 ...

  6. hdu 1269 迷宫城堡 (tarjan)

    迷宫城堡Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submiss ...

  7. nyoj 484-The Famous Clock

    484-The Famous Clock 内存限制:64MB 时间限制:1000ms 特判: No 通过数:2 提交数:2 难度:1 题目描述: Mr. B, Mr. G and Mr. M are ...

  8. nyoj 268-荷兰国旗问题 (count)

    268-荷兰国旗问题 内存限制:64MB 时间限制:3000ms 特判: No 通过数:15 提交数:20 难度:1 题目描述: 荷兰国旗有三横条块构成,自上到下的三条块颜色依次为红.白.蓝.现有若干 ...

  9. 领扣(LeetCode)设计哈希映射 个人题解

    不使用任何内建的哈希表库设计一个哈希映射 具体地说,你的设计应该包含以下的功能 put(key, value):向哈希映射中插入(键,值)的数值对.如果键对应的值已经存在,更新这个值. get(key ...

  10. Elasticsearch系列---简单入门实战

    概要 本篇主要介绍一下Elasticsearch Document的数据格式,在Java应用程序.关系型数据库建模的对比,介绍在Kibana平台编写Restful API完成基本的集群状态查询,Doc ...