SSM(Mybatis + Spring + Spring MVC)框架整合詳細步驟(附jar包和項目下載,免費的)

本例從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/1VD5mz_9fBFpPNaKJJVGuQg  密碼:7d0d

項目:鏈接:https://pan.baidu.com/s/1cu6F61e9xXQDZk4iDif1hQ  密碼:111i

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章