SSM框架搭建,新手學習中,歡迎指教
阿新 • • 發佈:2019-02-18
1、前言
最近專案中用到了spring+mybatis框架,閒暇之餘,自己就想搭一套SSM(spring+springMVC+mybatis)的框架,結果發現並沒有自己想象的那麼簡單,看了網上的很多教程,最多的就是那個用maven搭建的SSM,起初自己也想用maven搭建,後來出現種種問題,就沒用,直接用jar包,下次熟練了再用maven搭一個。廢話不說,直接開始。
2、版本介紹
3、新建一個web專案SSM
4、引入jar包,附錄會有jar包下載地址,這裡我的jar包比較多,裡面很多是原始碼包,因為有時自己要看,就導進來了。
5、構建專案包框架,養成好習慣。
6、引入jdbc和log4j屬性檔案到properties下
jdbc.properties
#################################### # Database ConnectivityProperties #################################### driver=com.mysql.jdbc.Driver url=jdbc\:mysql\://127.0.0.1\:3306/ssm?useUnicode\=true&characterEncoding\=UTF-8 username=root password=123456 #定義初始連線數 initialSize=0 #定義最大連線數 maxActive=20 #定義最大空閒 maxIdle=20 #定義最小空閒 minIdle=1 #定義最長等待時間 maxWait=60000
log4j.properties
#定義LOG輸出級別 log4j.rootLogger=DEBUG,INFO,Console,File #定義日誌輸出目的地為控制檯 log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.Target=System.out #可以靈活地指定日誌輸出格式,下面一行是指定具體的格式 log4j.appender.Console.layout =org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=[%-5p]%d{yyyy-MM-dd HH\:mm\:ss}\:%m%n #檔案大小到達指定尺寸的時候產生一個新的檔案 log4j.appender.File = org.apache.log4j.RollingFileAppender #指定輸出目錄 log4j.appender.File.File = logs/ssm.log #定義檔案最大大小 log4j.appender.File.MaxFileSize= 10MB #輸出所以日誌,如果換成DEBUG表示輸出DEBUG以上級別日誌 log4j.appender.File.Threshold =ALL log4j.appender.File.layout = org.apache.log4j.PatternLayout log4j.appender.File.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.Target=System.out log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=%d{ABSOLUTE}%5p %c{1}:%L- %m%n log4j.logger.com.ibatis = DEBUG log4j.logger.com.ibatis.common.jdbc.SimpleDataSource= DEBUG log4j.logger.com.ibatis.common.jdbc.ScriptRunner= DEBUG log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate= DEBUG log4j.logger.java.sql.ResultSet= INFO log4j.logger.org.apache = INFO log4j.logger.java.sql.Connection= DEBUG log4j.logger.java.sql.Statement= DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
7、建立spring-mybatis.xml配置檔案
這個檔案就是用來完成spring和mybatis的整合的。這裡面也沒多少行配置,主要的就是 自動掃描,自動注入,配置資料庫 。
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
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-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:annotation-config/>
<!-- 自動掃描 -->
<context:component-scanbase-package="com.ws"/>
<!-- 引入配置檔案 -->
<beanid="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<!-- <propertyname="location" value="classpath:jdbc.properties" />-->
<propertyname="locations">
<list>
<value>classpath:log4j.properties</value>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<beanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<propertyname="driverClassName"value="${driver}"/>
<propertyname="url"value="${url}"/>
<propertyname="username"value="${username}"/>
<propertyname="password"value="${password}"/>
<!-- 初始化連線大小 -->
<propertyname="initialSize"value="${initialSize}"></property>
<!-- 連線池最大數量 -->
<propertyname="maxActive"value="${maxActive}"></property>
<!-- 連線池最大空閒 -->
<propertyname="maxIdle"value="${maxIdle}"></property>
<!-- 連線池最小空閒 -->
<propertyname="minIdle"value="${minIdle}"></property>
<!-- 獲取連線最大等待時間 -->
<propertyname="maxWait"value="${maxWait}"></property>
</bean>
<!-- spring和MyBatis完美整合,不需要mybatis的配置對映檔案 -->
<beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
<propertyname="dataSource"ref="dataSource"/>
<propertyname="configLocation"value="classpath:sqlMapConfig.xml"/>
<propertyname="typeAliasesPackage"value="com.ws.poi"/>
<!-- mapper配置路徑 -->
<!-- 自動掃描mapper.xml檔案 -->
<!-- mapper配置路徑 -->
<propertyname="mapperLocations">
<list>
<!-- 表示在com.ws.map包或以下所有目錄中,以-mapper.xml結尾所有檔案 -->
<value>classpath:com/ws/mapper/**/*.xml</value>
</list>
</property>
</bean>
<!-- 掃描Mapper中的抽象類 ,例項化之後會自動裝配-->
<beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer">
<propertyname="basePackage"value="com.ws.mapper"/>
<propertyname="markerInterface"value="com.ws.mapper.SqlMapper"/>
</bean>
<!-- (事務管理)transaction manager, use JtaTransactionManager forglobaltx -->
<beanid="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<propertyname="dataSource"ref="dataSource"/>
</bean>
</beans>
8、建立資料庫ssm,建立表user,再往資料庫新增一條記錄
CREATE TABLE `user` (
`id` int NULL AUTO_INCREMENT ,
`name` varchar(30) NULL ,
`password` varchar(20) NULL ,
`age` int NULL ,
PRIMARY KEY (`id`)
)
;
9、編寫實體類user
package com.ws.poi.user;
import java.io.Serializable;
/**
*@descriptionTODO
*@time 2015-8-18下午2:26:30
*@authorweis
*@version 1.0
**/
public class User implements Serializable{
private static final long serialVersionUID = 704975107463848089L;
private Integerid;
private Stringname;
private Stringpassword;
private Integerage;
public Integer getId() {
returnid;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
returnname;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
returnpassword;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
returnage;
}
public void setAge(Integer age) {
this.age = age;
}
}
10、編寫service和service實現類userServiceImpl
UserService:
package com.ws.service.user;
import java.util.List;
import com.ws.poi.user.User;
/**
*@description TODO
*@time 2015-8-18 下午2:29:02
*@author weis
*@version 1.0
**/
public interface UserService<T> {
publicUser getUserById(Integer id);
publicList<User> getUserList();
}
UserServiceImpl:
package com.ws.service.user.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.ws.dao.user.UserDao;
import com.ws.poi.user.User;
import com.ws.service.user.UserService;
/**
*@description TODO
*@time 2015-8-18 下午2:29:50
*@author weis
*@version 1.0
**/
@Service
public class UserServiceImpl<T extends User>implements UserService<T> {
@Resource
privateUserDao<User> dao;
publicUser getUserById(Integer id) {
//TODO Auto-generated method stub
returndao.getUserById(id);
}
publicList<User> getUserList() {
//TODO Auto-generated method stub
returndao.getUserList();
}
}
11、編寫dao和對應的實現類
UserDao:
package com.ws.dao.user;
import java.util.List;
import com.ws.poi.user.User;
/**
*@description TODO
*@time 2015-8-18 下午2:31:15
*@author weis
*@version 1.0
**/
public interface UserDao<T> {
/**
*
* @Description:
* @param id
* @return
* @return User
* @author weis
* @date 2015-8-18下午2:31:33
*/
publicUser getUserById(Integer id);
publicList<User> getUserList();
}
UserDaoImpl:
package com.ws.dao.user.impl;
import java.util.List;
import javax.annotation.Resource;
importorg.springframework.stereotype.Repository;
import com.ws.dao.user.UserDao;
import com.ws.mapper.user.UserMapper;
import com.ws.poi.user.User;
/**
*@description TODO
*@time 2015-8-18 下午2:31:58
*@author weis
*@version 1.0
**/
@Repository
public class UserDaoImpl<T extendsUser> implements UserDao<T> {
@Resource
privateUserMapper<User> mapper;
publicUser getUserById(Integer id) {
//TODO Auto-generated method stub
returnmapper.getUserById(id);
}
publicList<User> getUserList() {
//TODO Auto-generated method stub
returnmapper.getUserList();
}
}
12、編寫對應的Mapper和mapper.xml檔案
UserMapper:
package com.ws.mapper.user;
import java.util.List;
import com.ws.mapper.SqlMapper;
import com.ws.poi.user.User;
/**
*@description TODO
*@time 2015-8-18 下午2:33:46
*@author weis
*@version 1.0
**/
public interface UserMapper<T>extends SqlMapper{
/**
*
* @Description:
* @param id
* @return
* @return User
* @author weis
* @date 2015-8-18下午2:33:57
*/
publicUser getUserById(Integer id);
publicList<User> getUserList();
}
user-mapper.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEmapperPUBLIC"-//mybatis.org//DTDMapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace和定義的Mapper介面對應,並實現其中的方法 -->
<mappernamespace="com.ws.mapper.user.UserMapper">
<resultMapid="UserResultMap"type="com.ws.poi.user.User">
<resultproperty="id"column="id"/>
<resultproperty="name"column="name"/>
<resultproperty="password"column="password"/>
<resultproperty="age"column="age"/>
</resultMap>
<selectid="getUserById"parameterType="int"resultType="User"resultMap="UserResultMap">
select * from user where id = #{id}
</select>
<selectid="getUserList"resultMap="UserResultMap"resultType="User">
select * from user
</select>
</mapper>
13、所有的mapper繼承SqlMapper
package com.ws.mapper;
public interface SqlMapper{
}
14、引入sqlMapConfig.xml,主要是為了設定別名,在spring-mybatis.xml中也要配置sqlMapConfig.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTDConfig 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 配置設定 -->
<settings>
<!-- 配置全域性性 cache的 (開 / 關) default:true -->
<settingname="cacheEnabled"value="true"/>
<!-- 是否使用懶載入關聯物件 同hibernate中的延遲載入一樣 default:true -->
<settingname="lazyLoadingEnabled"value="true"/>
<!-- [當物件使用延遲載入時屬性的載入取決於能被引用到的那些延遲屬性,否則,按需載入(需要的是時候才去載入)] -->
<settingname="aggressiveLazyLoading"value="true"/>
<!-- 是否允許單條sql返回多個數據集 (取決於驅動的相容性) default:true -->
<settingname="multipleResultSetsEnabled"value="true"/>
<!-- 是否可以使用列的別名 (取決於驅動的相容性) default:true-->
<settingname="useColumnLabel"value="true"/>
<!--允許JDBC生成主鍵。需要驅動器支援。如果設為了true,這個設定將強制使用被生成的主鍵,有一些驅動器不相容不過仍然可以執行。 default:false-->
<settingname="useGeneratedKeys"value="false"/>
<!--指定 MyBatis如何自動對映資料基表的列 NONE:不隱射 PARTIAL:部分 FULL:全部-->
<settingname="autoMappingBehavior"value="PARTIAL"/>
<!-- 這是預設的執行型別
SIMPLE :簡單
REUSE:執行器可能重複使用prepared statements語句
BATCH:執行器可以重複執行語句和批量更新
-->
<settingname="defaultExecutorType"value="SIMPLE"/>
<!-- 設定驅動等待資料響應的超時數 預設沒有設定-->
<settingname="defaultStatementTimeout"value="25000"/>
<!-- [是否啟用行內巢狀語句 defaut:false]-->
<settingname="safeRowBoundsEnabled"value="false"/>
<!-- [是否啟用 資料中 A_column自動對映到 java類中駝峰命名的屬性 default:fasle] -->
<settingname="mapUnderscoreToCamelCase"value="false"/>
<!-- 設定本地快取範圍 session:就會有資料的共享 statement:語句範圍 (這樣就不會有資料的共享 ) defalut:session -->
<settingname="localCacheScope"value="SESSION"/>
<!-- 設定但JDBC型別為空時,某些驅動程式要指定值,default:other -->
<settingname="jdbcTypeForNull"value="OTHER"/>
<!-- 設定觸發延遲載入的方法 -->
<settingname="lazyLoadTriggerMethods"value="equals,clone,hashCode,toString"/>
</settings>
<!-- 別名 -->
<typeAliases>
<typeAliastype="com.ws.poi.user.User"alias="User"/>
</typeAliases>
</configuration>
15、建立測試類:
package com.junit.test;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
import com.ws.poi.user.User;
import com.ws.service.user.UserService;
/**
*@descriptionTODO
*@time 2015-8-18下午2:42:51
*@authorweis
*@version 1.0
**/
public class TestMybatis {
private static Logger logger = Logger.getLogger(TestMybatis.class);
private ApplicationContextac =null;
privateUserService<User>userService =null;
@SuppressWarnings("unchecked")
@Before
public void before() {
ac = newClassPathXmlApplicationContext("spring-mybatis.xml");
userService = ac.getBean(UserService.class);
}
@Test
public void test1() {
User user = userService.getUserById(1);
System.out.println(user.getName());
logger.info("值:"+user.getName());
}}
16、測試結果,成功
17、配置spring-mvc.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"
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-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 自動掃描該包,使SpringMVC認為包下用了@controller註解的類是控制器 -->
<context:component-scanbase-package="com.ws.controller"/>
<!--避免IE執行AJAX時,返回JSON出現下載檔案 -->
<beanid="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<propertyname="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 啟動SpringMVC的註解功能,完成請求和註解POJO的對映 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<propertyname="messageConverters">
<list>
<refbean="mappingJacksonHttpMessageConverter"/> <!--JSON轉換器 -->
</list>
</property>
</bean>
<!-- 定義跳轉的檔案的前後綴,檢視模式配置-->
<beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 這裡的配置我的理解是自動給後面action的方法return的字串加上字首和字尾,變成一個可用的url地址 -->
<propertyname="prefix"value="/WEB-INF/jsp/"/>
<propertyname="suffix"value=".jsp"/>
</bean>
<!-- 配置檔案上傳,如果沒有使用檔案上傳可以不用配置,當然如果不配,那麼配置檔案中也不必引入上傳元件包 -->
<beanid="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 預設編碼 -->
<propertyname="defaultEncoding"value="utf-8"/>
<!-- 檔案大小最大值 -->
<propertyname="maxUploadSize"value="10485760000"/>
<!-- 記憶體中的最大值 -->
<propertyname="maxInMemorySize"value="40960"/>
</bean>
</beans>
18、配置web.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype CreatedWeb Application</display-name>
<!-- Spring和mybatis的配置檔案 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml</param-value>
</context-param>
<!-- 編碼過濾器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring監聽器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 防止Spring記憶體溢位監聽器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- Spring MVC servlet -->
<servlet>
<servlet-name>SpringMVC</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>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<!-- 此處可以可以配置成*.do,對應struts的字尾習慣 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
19、建UserController
package com.ws.controller.user;
import java.util.List;
import javax.annotation.Resource;
importjavax.servlet.http.HttpServletRequest;
importorg.springframework.stereotype.Controller;
import org.springframework.ui.Model;
importorg.springframework.web.bind.annotation.RequestMapping;
import com.ws.poi.user.User;
import com.ws.service.user.UserService;
/**
*@description TODO
*@time 2015-8-24 下午5:46:55
*@author weis
*@version 1.0
**/
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
privateUserService<User> service;
@RequestMapping("/showUser")
public String toIndex(HttpServletRequest request,Model model){
User user = this.service.getUserById(1);
model.addAttribute("user", user);
return "user";
}
@RequestMapping("/showUser1")
public String getUserList(HttpServletRequest request,Model model){
List<User> users = this.service.getUserList();
if(users.size()>0){
User user = users.get(0);
model.addAttribute("user",user);
}
return "user";
}
}
20、建立測試頁面user.jsp。
<%@ page language="java"import="java.util.*"pageEncoding="ISO-8859-1"%>
<%
String path =request.getContextPath();
String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML 4.01 Transitional//EN">
<html>
<head>
<basehref="<%=basePath%>">
<title>My JSP 'user.jsp' starting page</title>
<metahttp-equiv="pragma"content="no-cache">
<metahttp-equiv="cache-control"content="no-cache">
<metahttp-equiv="expires"content="0">
<metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
<metahttp-equiv="description"content="This is my page">
<!--
<link rel="stylesheet"type="text/css"href="styles.css">
-->
</head>
<body>
${user.name}
</body>
</html>
21、釋出專案,訪問。
至此簡易專案環境搭建完成。