網上發佈了不少關於搭建Spring+SpringMVC+Mybatis的技術文章,但是基本都是缺斤少兩。我利用閒餘時間自己搭建了一個完整的項目,希望對各位coder有所幫助,此項目僅供參考,自己搭建一遍纔會有所收穫。搭建過程中出現什麼問題可以提出來大家一起解決。
開發工具:Eclipse
框架選型:SpringMVC、Spring、Mybatis
數據庫:MySQL
Jar包依賴方式:apache-maven-3.6.0
JDK版本:jdk1.8.0_201
Tomcat容器:apache-tomcat-8.5.24
流程:搭建maven項目 > 搭建SpriingMVC > 搭建Spring > 搭建Mybatis > 新建各種類(controller/service...)
文章結尾附有開發所需下載鏈接
-
一、創建Maven項目
新建成功的項目結構:
新建項目只有一個 src/main/resources,
並且項目會出現錯誤,而且項目報下面的The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Patht 錯誤
解決方案:右擊項目>點擊Properties > 點擊Java Build Path >選擇Library > 點擊Add Library > 選擇Server Runtime > Apache Tomcat7 服務器(Tomcat8 需要 web版本3.0)
點擊Apply,幹掉項目錯誤後,項目結構發生了改變,自動生成了src/main/java
和src/test/java
目錄
此時,新建項目的jre版本是1.5,web.xml版本爲2.3。我們需要對版本進行修改
修改pom.xml中的配置
代碼如下:
<build>
<finalName>Demo_SSM_Maven</finalName>
<plugins>
<!-- 根據自己的JRE版本修改maven默認的JRE編譯版本 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
修改完配置,會出現下面這個問題
解決方法:只需要更新maven。右擊項目> 點擊Maven >點擊Update Project..
把jre 指定到Workspace default JRE
修改web.xml版本
默認的Dynamic Web Module爲2.3,使用Tomcat 8.5,需要修改爲3.0
方法一:修改maven工程所在目錄下org.eclipse.wst.common.project.facet.core.xml
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<fixed facet="wst.jsdt.web"/>
<installed facet="java" version="1.8"/>
<!—2.3修改爲3.0 -->
<installed facet="jst.web" version="2.3"/>
<installed facet="wst.jsdt.web" version="1.0"/>
</faceted-project>
方法二:右擊項目>點擊Properties >點擊Project Facets(項目模板)
如下圖,可以看到Dynamic Web Module版本爲 2.3
直接修改3.0會出現錯誤不允許修改
解決方法:先取消Dynamic Web Module前面的勾選,再選擇3.0,然後Apple and Close
重新打開這個頁面,對Dynamic Web Module進行勾選。
這時候先不要着急保存關閉。點擊下面的Furter configuration avail…
修改Content directory爲webapp,並勾選下面,如果保存保存保存
最後的項目結構是這樣的
此時的web.xml是這樣的
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Demo_SSM_Maven</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
二、搭建SpringMVC
Maven項目搭建好了以後,就開始搭建SpringMVC框架
1.pom.xml文件中添加springmvc依賴
<!-- springMVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.14.RELEASE</version>
</dependency>
2.創建springmvc配置文件
在src/main/resource下創建spring-mvc.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:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<!-- 開啓註解 -->
<mvc:annotation-driven />
<!-- 讓掃描spring掃描這個包下所有的類,讓標註spring註解的類生效 -->
<context:component-scan base-package="com.ryx.demo.controller"></context:component-scan>
<!-- 視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/" />
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
3.在web.xml中添加配置
<!-- 定義前端控制器springmvc -->
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 指定路徑 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<!-- 隨spring啓動而啓動 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
4.創建一個controller測試SpringMVC框架(可以使用PostMan接口測試工具進行測試)
@RequestMapping("/demo")
@Controller
public class studentController {
@RequestMapping("/test")
@ResponseBody
public String test() {
return "hello,word";
}
}
三、搭建Spring
SpringMVC框架搭建成功後,就開始搭建Spring框架
由於在依賴springmvc的時候已經添加了許多spring相關包了,所以此時不需要添加額外的包,可以直接創建配置文件了。
1.創建spring-context.xml配置文件
在src/main/resource下創建spring-context.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:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>
溫馨提示:如果xml文件頭文件報錯 ,並顯示一下錯誤
解決方式:window > Prefereces > XML > XML Files > Validation > 取消掉Honour all XML schema locations 前面的對勾
2. web.xml中配置spring
<!-- 配置適配器spring -->
<listener>
<description>啓動spring容器</description>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-context.xml</param-value>
</context-param>
3.pom.xml中配置 數據源+數據庫 的依賴jar包(我用的數據源是C3P0)
<!-- 數據庫連接 //start -->
<!-- c3p0 數據庫連接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- 數據庫 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<!-- 數據庫連接 //end -->
4.在spring-context.xml配置c3p0數據源
<!-- 配置c3p0 -->
<!-- 連接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost/demo?characterEncoding=utf8&serverTimezone=UTC"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
<property name="minPoolSize" value="1"></property>
<property name="maxPoolSize" value="5"></property>
<property name="initialPoolSize" value="1"></property>
<property name="acquireIncrement" value="1"></property>
</bean>
5.配置spring聲明式事務管理,pom.xml中添加 聲明式事務的依賴jar包
<!-- spring聲明式事務管理 //start -->
<!-- spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.14.RELEASE</version>
</dependency>
<!-- spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.14.RELEASE</version>
</dependency>
<!-- spring聲明式事務管理 //end -->
6.在spring-context.xml配置事務管理器
<!-- 配置spring聲明式事務管理 -->
<!-- 配置事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 使用註解來控制事務 -->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
四、搭建Mybatis
配置好SpringMVC、Spring後,開始搭建Mybatis
1.pom.xml中添加Mybatis的依賴jar包
<!-- Mybatis //start -->
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<!-- mybatis-spring//無縫整合mybatis+spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!-- cglib代理 -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.2</version>
</dependency>
<!-- Mybatis //end -->
2.創建mybatis-config.xml配置文件
在src/main/resource下創建mybatis-config.xml,內容如下
<?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="cacheEnabled" value="true" />
<!-- 設置超時時間,它決定驅動等待數據庫響應的秒數 -->
<setting name="defaultStatementTimeout" value="3000" />
<!-- 是否開啓自動駝峯命名規則(camel case)映射 -->
<setting name="mapUnderscoreToCamelCase" value="true" />
<!-- 代理 -->
<!-- 指定 Mybatis 創建具有延遲加載能力的對象所用到的代理工具 -->
<setting name="proxyFactory" value="CGLIB" />
<!-- 延遲加載 -->
<setting name="lazyLoadingEnabled" value="true" />
</settings>
</configuration>
3. spring-context.xml中配置mybatis
<!-- 配置mybatis, 綁定c3p0 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<property name="mapperLocations" >
<list>
<value>classpath:mapper/*.xml</value>
</list>
</property>
</bean>
<!-- 掃描生成所有dao層 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ryx.demo.dao"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
五、創建entity、controller、servcie . . . .class
項目結構如下
我這裏用到了阿里的fastjson,用的時候需要在pom.xml中引入依賴
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.54</version>
</dependency>
下面是java代碼:
Po實體類層
public class Student {
private int sid;
private String sname;
private String adress;
private String username;
private String password;
private String createtime;
private String updatetime;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(int sid, String sname, String adress, String username, String password, String createtime,
String updatetime) {
super();
this.sid = sid;
this.sname = sname;
this.adress = adress;
this.username = username;
this.password = password;
this.createtime = createtime;
this.updatetime = updatetime;
}
public Student(String sname, String adress, String createtime) {
super();
this.sname = sname;
this.adress = adress;
this.createtime = createtime;
}
public Student(int sid, String sname, String adress, String updatetime) {
super();
this.sid = sid;
this.sname = sname;
this.adress = adress;
this.updatetime = updatetime;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCreatetime() {
return createtime;
}
public void setCreatetime(String createtime) {
this.createtime = createtime;
}
public String getUpdatetime() {
return updatetime;
}
public void setUpdatetime(String updatetime) {
this.updatetime = updatetime;
}
@Override
public String toString() {
return "Student [sid=" + sid + ", sname=" + sname + ", adress=" + adress + ", username=" + username
+ ", password=" + password + ", createtime=" + createtime + ", updatetime=" + updatetime + "]";
}
}
Controller控制層
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
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 com.alibaba.fastjson.JSON;
@RequestMapping("/student")
@Controller
public class StudentController {
@Autowired
public IStudentService service;
@RequestMapping("/test")
@ResponseBody
public String test() {
return "hello,word";
}
/**
* 查詢所有學生
* @return
*/
@ResponseBody
@RequestMapping(value="/queryStudentList",produces = "text/plain;charset=UTF-8")
public String queryStudentList() {
List<Student> list = service.queryStudentList();
return JSON.toJSONString(list);
}
/**
* 通過id查詢學生
* @return
*/
@ResponseBody
@RequestMapping(value="/queryStudentById",produces = "text/plain;charset=UTF-8")
public String queryStudentById() {
Student student = service.queryStudentById(1002);
return JSON.toJSONString(student);
}
/**
* 添加學生信息
* @return
*/
@ResponseBody
@RequestMapping(value="/addStudent",produces = "text/plain;charset=UTF-8")
public String addStudent() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Student student = new Student("測試員", "四川成都",sdf.format(new Date()));
int i = service.addStudent(student);
return "添加成功";
}
/**
* 刪除學生信息
* @return
*/
@ResponseBody
@RequestMapping(value="/deleteStudent",produces = "text/plain;charset=UTF-8")
public String deleteStudent() {
int i = service.deleteStudent(1009);
return "刪除成功";
}
/**
* 修改學生信息
* @return
*/
@ResponseBody
@RequestMapping(value="/updateStudent",produces = "text/plain;charset=UTF-8")
public String updateStudent() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Student student = new Student(1009, "測試專員", "西藏拉薩",sdf.format(new Date()));
int i = service.updateStudent(student);
return "修改成功";
}
}
Service層
public interface IStudentService {
public List<Student> queryStudentList();
public Student queryStudentById(int sid);
public int addStudent(Student student);
public int updateStudent(Student student);
public int deleteStudent(int sid);
}
ServiceImpl業務邏輯層
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class StudentServiceImpl implements IStudentService{
@Autowired
StudentMapper mapper;
@Override
public List<Student> queryStudentList() {
// TODO Auto-generated method stub
return mapper.queryStudentList();
}
@Override
public Student queryStudentById(int sid) {
// TODO Auto-generated method stub
return mapper.queryStudentById(sid);
}
@Override
public int addStudent(Student student) {
// TODO Auto-generated method stub
return mapper.addStudent(student);
}
@Override
public int updateStudent(Student student) {
// TODO Auto-generated method stub
return mapper.updateStudent(student);
}
@Override
public int deleteStudent(int sid) {
// TODO Auto-generated method stub
return mapper.deleteStudent(sid);
}
}
dao層
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface StudentMapper {
List<Student> queryStudentList();
Student queryStudentById(@Param("id")int sid);
int addStudent(Student student);
int updateStudent(Student student);
int deleteStudent(int sid);
}
mapper層
<?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.ryx.demo.dao.StudentMapper">
<resultMap id="BaseResultMap" type="com.ryx.demo.po.Student">
<id column="sid" property="sid" />
<result column="sname" property="sname" />
<result column="adress" property="adress" />
</resultMap>
<!-- 查詢所有用戶 -->
<select id="queryStudentList" resultMap="BaseResultMap">
select * from student
</select>
<!-- 通過id查詢用戶 -->
<select id="queryStudentById" parameterType="int" resultType="com.ryx.demo.po.Student">
select * from student where sid = #{id}
</select>
<!-- 添加用戶 -->
<insert id="addStudent" parameterType="com.ryx.demo.po.Student">
insert into student
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="sname!=null and sname!=''">sname,</if>
<if test="adress!=null and adress!=''">adress,</if>
<if test="createtime!=null and createtime!=''">createtime,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="sname!=null and sname!=''">#{sname},</if>
<if test="adress!=null and adress!=''">#{adress},</if>
<if test="createtime!=null and createtime!=''">#{createtime},</if>
</trim>
</insert>
<!-- 修改用戶信息 -->
<update id="updateStudent" parameterType="com.ryx.demo.po.Student">
update student
<trim prefix="SET" suffixOverrides=",">
<if test="sname!=null and sname!=''">sname=#{sname},</if>
<if test="adress!=null and adress!=''">adress=#{adress},</if>
<if test="updatetime!=null and updatetime!=''">updatetime=#{updatetime},</if>
</trim>
where sid=#{sid}
</update>
<!-- 刪除用戶 -->
<delete id="deleteStudent" parameterType="int">
delete from student where sid = #{value}
</delete>
</mapper>
jdk1.8.0_201百度雲盤鏈接:https://pan.baidu.com/s/1fQnmCpLjSZi6Ir9Pqg2JeQ 提取碼:ow66
apache-maven-3.6.0百度雲盤鏈接:https://pan.baidu.com/s/1R5CEsKbZYdd66Nnbhmp74g 提取碼:jcu1
apache-tomcat-8.5.24百度雲盤鏈接:https://pan.baidu.com/s/1pelgNMbnjFfOzjQezQpoBA 提取碼:sm45
項目Github下載:https://github.com/Ryx123/Demo_SSM_Maven.git
項目創建完成!
此文章分享只供參考,有問題可以提出共同研究解決
只有不斷解決問題,纔會有所提升!!
-—— 心白白,小白白,小白心