本例从0开始逐一整合SSM的步骤,实现基础的CRUD
开发环境:Eclipse4.6 + jdk1.8 + Tomcat8 + MySQL
SSM所需jar包和项目下载路径在文章最后
1.数据库
创建test数据库 ,file表
use test;
CREATE TABLE `file` (
`id` bigint(2) NOT NULL AUTO_INCREMENT,
`userId` bigint(2) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`path` varchar(255) DEFAULT NULL,
`size` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=UTF8;
2.准备数据
INSERT INTO `file` VALUES
('1', '10', 'tp1.jpg', '/Library/Tomcat/apache-tomcat-8.5.31/webapps/uploadDownloadFile/upload/tp1.jpg', '550714'),
('2', '7', '??????.xls', '/Library/Tomcat/apache-tomcat-8.5.31/webapps/uploadDownloadFile/upload/??????.xls', '76800'),
('3', '7', '3222.json', '/Library/Tomcat/apache-tomcat-8.5.31/webapps/uploadDownloadFile/upload/3222.json', '135482'),
('4', '7', 'tp2.jpg', '/Library/Tomcat/apache-tomcat-8.5.31/webapps/uploadDownloadFile/upload/tp2.jpg', '446418'),
('5', '1', 'tp7.jpg', '/Library/Tomcat/apache-tomcat-8.5.31/webapps/uploadDownloadFile/upload/tp7.jpg', '469380');
3.新建项目
在eclipse中新建项目uploadDownloadFile,选择Dynamic Web Project的方式。
4.导入jar包
将所需jar包复制到uploadDownloadFile/WebContent/WEB-INF/lib目录下(文章最后有jar包下载地址)。
5.domain File
package com.file.domain;
public class File {
private int id;
private int userId;
private String name;
private String path;
private int size;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
@Override
public String toString() {
return "File [id=" + id + ", userId=" + userId + ", name=" + name + ", path=" + path
+ ", size=" + size + "]";
}
}
6.FileMapper
package com.file.mapper;
import java.util.List;
import com.file.domain.File;
public interface FileMapper {
public int insert(File file);
public void delete(int id);
public File get(int id);
public int update(File file);
public List<File> getAll();
}
7.FileMapper.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.file.mapper.FileMapper">
<insert id="insert" parameterType="File" >
insert into file (userId,name,path,size) values (#{userId},#{name},#{path},#{size})
</insert>
<delete id="delete" parameterType="int" >
delete from file where id= #{id}
</delete>
<select id="get" parameterType="int" resultType="File">
select * from file where id= #{id}
</select>
<update id="update" parameterType="File" >
update file set userId=#{userId},name=#{name},path=#{path},size=#{size} where id=#{id}
</update>
<select id="getAll" resultType="File">
select * from file
</select>
</mapper>
8.FileService
package com.file.service;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
import com.file.domain.File;
public interface FileService {
void insert(MultipartFile file, String path);
void delete(int id);
File get(int id);
List<File> getAll();
}
9.FileServiceImpl
package com.file.service.impl;
import java.util.List;
import java.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.file.domain.File;
import com.file.mapper.FileMapper;
import com.file.service.FileService;
@Service
public class FileServiceImpl implements FileService {
@Autowired
private FileMapper fileMapper;
@Override
public void insert(MultipartFile file, String path) {
File f = new File();
int userId = new Random().nextInt(10) + 1;
f.setName(file.getOriginalFilename());
f.setPath(path);
f.setSize((int)file.getSize());
f.setUserId(userId);
fileMapper.insert(f);
}
@Override
public void delete(int id) {
fileMapper.delete(id);
}
@Override
public File get(int id) {
return fileMapper.get(id);
}
@Override
public List<File> getAll() {
return fileMapper.getAll();
}
}
10.FileController
package com.file.controller;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.file.service.FileService;
// 告诉spring mvc这是一个控制器类
@Controller
@RequestMapping("")
public class FileController {
@Autowired
FileService fileService;
@RequestMapping("listFile")
public ModelAndView listCategory(){
ModelAndView mav = new ModelAndView();
List<com.file.domain.File> fs= fileService.getAll();
// 放入转发参数
mav.addObject("fs", fs);
// 放入jsp路径
mav.setViewName("listFile");
return mav;
}
}
11.web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>uploadDownloadFile</display-name>
<!-- spring的配置文件-->
<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>
<!-- spring mvc核心:分发servlet -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- spring mvc的配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
12. 在项目中新建名为resource的Source Folder文件,在该目录下新建db.properties文件、log4j.properties文件、mybatis-config.xml,分别是数据库、日志、mybatis的配置文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=admin
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.file=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 配置框架的全局信息 -->
<!-- <settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="lazyLoadTriggerMethods" value="clone"/>
</settings> -->
<typeAliases>
<typeAlias type="com.file.domain.File" alias="file"/>
</typeAliases>
</configuration>
13.applicationContext.xml
在resource目录下新建applicationContext.xml文件,这是Spring的配置文件,其作用已在代码中注释
<?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:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- <context:annotation-config/>
<context:component-scan base-package="com.file"/> -->
<!-- 1. 识别数据源 -->
<context:property-placeholder location="classpath:db.properties" system-properties-mode="NEVER"/>
<!-- 2. 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</bean>
<!-- 3. 扫描存放SQL语句的Category.xml -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- mybatis的配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/file/mapper/*.xml"/>
</bean>
<!-- 4. 扫描Mapper,并将其生命周期纳入Spring的管理 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.file.mapper"/>
</bean>
<!-- 5.配置事务 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
14.在resource目录下新建springMVC.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- 1. 扫描Controller,并将其生命周期纳入Spring管理 DI IOC -->
<context:annotation-config/>
<context:component-scan base-package="com.file"/>
<!-- 2. 注解驱动,以使得访问路径与方法的匹配可以通过注解配置 MVC -->
<mvc:annotation-driven />
<!-- 3. 静态页面,如html,css,js,images可以访问 -->
<mvc:default-servlet-handler />
<!-- 4. 视图定位到/WEB/INF/jsp 这个目录下 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
15.listFile.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件列表</title>
</head>
<body>
<table align='center' border='1' cellspacing='0'>
<tr>
<td>id</td>
<td>userId</td>
<td>name</td>
<td>path</td>
<td>size</td>
</tr>
<c:forEach items="${fs}" var="c" varStatus="st">
<tr>
<td>${c.id}</td>
<td>${c.userId}</td>
<td>${c.name}</td>
<td>${c.path}</td>
<td>${c.size}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
16.部署成功之后测试地址:http://localhost:8080/uploadDownloadFile/listFile
17.jar包、项目下载路径
jar包: 链接: https://pan.baidu.com/s/1wtV2EQuon1oxpKeYmfGzRw 密码: j16a
项目:链接: https://pan.baidu.com/s/14Ehknu7pWbIIJV5lhvUdqQ 密码: m5gk