ssm---(springMvc+spring+mybatis)
阿新 • • 發佈:2019-01-01
一、搭建Spring開發環境
一、搭建spring開發環境
第一步:下載spring所需要的jar包,如下
第二步:在src下新建【source folder】檔案config,然後在其下建立applicationContext.xml檔案,如下圖所示:
applicationContext.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"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/context
-
http://www.springframework.org/schema/context/spring-context.xsd" >
- <!-- 1、自動掃描dao和service包(自動注入) -->
- <context:component-scanbase-package="com.cn.dao,com.cn.service"/>
- </beans>
第三步:在src下新建包com.cn.service,在包下編寫一個介面IUserService
- package com.cn.service;
- public interface IUserService {
- /**
- * 測試方法
- * */
-
public void test();
- }
第四步:在src下新建包com.cn.service.impl,在包下編寫介面的實現類UserServiceImpl
- package com.cn.service.impl;
- import org.springframework.stereotype.Service;
- import com.cn.service.IUserService;
- @Service("userService") //將UserServiceImpl標註為一個service
- public class UserServiceImpl implements IUserService{
- @Override
- public void test() {
- System.out.println("hello Spring!");
- }
- }
第五步:在web.xml中配置spring的監聽器
- <!-- 1、spring配置檔案位置 -->
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:applicationContext.xml</param-value>
- </context-param>
- <!-- 2、spring監聽器 -->
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- package com.cn.test;
- import org.junit.Test;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import com.cn.service.IUserService;
- publicclass SpringTest {
- @Test
- publicvoid test(){
- //通過applicationContext.xml配置檔案建立spring的應用程式上下文環境
- ApplicationContext context=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
- //從spring的IOC容器中獲取bean
- IUserService userService=(IUserService) context.getBean("userService");
- //執行測試方法
- userService.test();
- }
- }
將專案部署在tomcat伺服器上,然後啟動tomcat伺服器,沒有出錯。然後在瀏覽器位址列輸入
http://localhost:18080/s2shDemo,能夠正常訪問,則說明spring的開發環境搭建成功
二、搭建springMvc開發環境,並整合spring
springMvc屬於spring部分,所有spring整合springMvc無需藉助第三方jar包
第一步:在config下新建springMvc配置檔案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:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd ">
<!-- 1、開啟註解 -->
<context:annotation-config />
<!-- 2、自動掃描包 ,相當於配置處理器和處理器對映器-->
<context:component-scan base-package="com.cn.controller" />
<!-- 3、配置檢視解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
第二步:在src下新建包com.cn.controller,並在該包下建立控制器類TestController,程式碼如下:
package com.cn.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller(value="testController")
public class TestController {
@RequestMapping(value="test")
public ModelAndView test(){
ModelAndView mv=new ModelAndView();
mv.addObject("message", "springMvc helloWorld!");
mv.setViewName("test/test");
return mv;
}
}
第三步:在web.xml中配置springMvc的配置檔案
<!-- 2、配置springMvc -->
<servlet>
<servlet-name>springMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 指定springMvc的配置路徑 -->
<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>springMvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
第四步:在WEB-INF下新建檔案jsp,然後在jsp檔案下新建test檔案,然後在其下新建test.jsp檢視層
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'test.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
${message}
</body>
</html>
第五步:測試
啟動tomcat伺服器,在瀏覽器位址列輸入:http://localhost:8080/SSMDemo/test.do
三、搭建mybatis開發環境,並整合spring
1、匯入mybatis所需的jar包,mybatis和spring整合的外掛包、oracle資料庫驅動包、資料庫連線池包
2、在config下新建資料庫配置檔案jdbc.properties
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
jdbc.username=scott
jdbc.password=tiger
3、在applicationContext.xml中配置資料來源、session工廠、事務等<?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:context="http://www.springframework.org/schema/context"
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 1、自動掃描該包下面的bean -->
<context:component-scan base-package="com.cn.service,com.cn.dao" />
<!-- 2、載入配置檔案jdbc.properties -->
<!-- <context:property-placeholder location="classpath:jdbc.properties" /> -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
<value>classpath:log4j.properties</value>
</list>
</property>
</bean>
<!-- 3、配置資料來源dataSource -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 4、配置mybatis的sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 4.1 引入資料來源dataSource -->
<property name="dataSource" ref="dataSource" />
<!-- 4.2 引入mybatis.cfg.xml配置檔案 -->
<property name="configLocation" value="classpath:mybatis.cfg.xml" />
<!-- 4.3 引入*Mapper.xml配置檔案 -->
<property name="mapperLocations">
<list>
<value>classpath:com/cn/mapper/*.xml</value>
</list>
</property>
</bean>
<!-- 5、Mapper介面所在的包名,spring會自動查詢其下的Mapper -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.cn.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
<!-- 6、配置事務管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 7、配置事務通知屬性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 定義事務傳播屬性 -->
<tx:attributes>
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="edit*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="find*" propagation="REQUIRED" read-only="true" />
<tx:method name="select*" propagation="REQUIRED" read-only="true" />
<tx:method name="get*" propagation="REQUIRED" read-only="true" />
<tx:method name="load*" propagation="REQUIRED" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 8、配置事務切面 -->
<aop:config>
<aop:pointcut expression="execution(* com.cn.service.*.*(..))"
id="mypointcut" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="mypointcut" />
</aop:config>
</beans>
4、在config下新建日誌配置log4j.properties
log4j.rootLogger=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=[%c] - %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
5、新建實體類UserVO
package com.cn.vo;
/**
* 使用者實體
* **/
public class UserVO {
private Integer id; //使用者id
private String userName; //使用者名稱
private String password; //密碼
private String trueName; //真實名
private String email; //郵箱
private String phone; //電話
private String roleName; //角色名稱:普通使用者、系統管理員、超級管理員
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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 getTrueName() {
return trueName;
}
public void setTrueName(String trueName) {
this.trueName = trueName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
}
6、新建資料層介面UserDao
package com.cn.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.cn.vo.UserVO;
public interface UserDao {
//使用者登入
public UserVO login(UserVO userVO);
//新增使用者
public void insertUser(UserVO userVO);
//刪除使用者
public void deleteUser(Integer id);
//修改使用者
public void updateUser(UserVO userVO);
//通過id查詢使用者
public UserVO selectUserById(Integer id);
//查詢所有使用者
public List<UserVO> selectAllUser();
//獲取總記錄數
public int getUserCount();
//分頁查詢
public List<UserVO> findUserByPage(@Param(value="startPos")Integer startPos,@Param(value="pageSize")Integer pageSize);
//校驗使用者是否存在
public int checkUserExits(UserVO userVO);
}
7、新建介面UserDao實現類UserMapper.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">
<!-- namespace為userDao介面 -->
<mapper namespace="com.cn.dao.UserDao">
<!-- -->
<resultMap type="UserVO" id="userResultMap">
<result property="id" column="ID" />
<result property="userName" column="USERNAME" />
<result property="password" column="PASSWORD" />
<result property="trueName" column="TRUENAME" />
<result property="email" column="EMAIL" />
<result property="phone" column="PHONE" />
<result property="roleName" column="ROLENAME" />
</resultMap>
<!-- 新增使用者 -->
<insert id="insertUser" parameterType="UserVO">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
select seq_user_id.nextval from dual
</selectKey>
insert into t_user(
ID,
USERNAME,
PASSWORD,
TRUENAME,
EMAIL,
PHONE,
ROLENAME
)values(
#{id},
#{userName},
#{password},
#{trueName},
#{email},
#{phone},
#{roleName}
)
</insert>
<!-- 刪除 -->
<delete id="deleteUser" parameterType="Integer">
delete from t_user t where t.id=#{id}
</delete>
<!-- 修改使用者 -->
<update id="updateUser" parameterType="UserVO">
update t_user t
<set>
<if test="userName!=null and userName!=''">
t.USERNAME=#{userName},
</if>
<if test="password!=null and password!=''">
t.PASSWORD=#{password},
</if>
<if test="trueName!=null and trueName!=''">
t.TRUENAME=#{trueName},
</if>
<if test="email!=null and email!=''">
t.EMAIL=#{email},
</if>
<if test="phone!=null and phone!=''">
t.PHONE=#{phone},
</if>
<if test="roleName!=null and roleName!=''">
t.ROLENAME=#{roleName},
</if>
</set>
where t.id=#{id}
</update>
<!-- 通過id查詢使用者 -->
<select id="selectUserById" parameterType="Integer" resultMap="userResultMap">
select t.* from t_user t where t.id=#{id}
</select>
<!-- 查詢所有使用者 -->
<select id="selectAllUser" resultMap="userResultMap">
select t.* from t_user t
</select>
<!-- 使用者登入 -->
<select id="login" parameterType="UserVO" resultMap="userResultMap">
select t.* from t_user t where t.USERNAME=#{userName}
and t.PASSWORD=#{password}
</select>
<!-- 校驗使用者是否存在 -->
<select id="checkUserExits" parameterType="UserVO" resultType="int">
<![CDATA[
select count(*) from t_user t where
t.USERNAME=#{userName} and
t.PASSWORD=#{password}
]]>
</select>
</mapper>
8、新建服務層介面IUserService
package com.cn.service;
import java.util.List;
import com.cn.vo.UserVO;
public interface UserService {
// 使用者登入
public UserVO login(UserVO userVO);
// 新增使用者
public void insertUser(UserVO userVO);
// 刪除使用者
public void deleteUser(Integer id);
// 修改使用者
public void updateUser(UserVO userVO);
// 通過id查詢使用者
public UserVO selectUserById(Integer id);
// 查詢所有使用者
public List<UserVO> selectAllUser();
// 校驗使用者是否存在
public int checkUserExits(UserVO userVO);
// 獲取總記錄數
public int getUserCount();
}
9、新建服務層介面UserService介面實現類UserServiceImpl
package com.cn.service.impl;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.cn.dao.UserDao;
import com.cn.service.UserService;
import com.cn.vo.UserVO;
@Service("userService")
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
public UserVO login(UserVO userVO) {
return userDao.login(userVO);
}
public void insertUser(UserVO userVO) {
userDao.insertUser(userVO);
}
public void deleteUser(Integer id) {
userDao.deleteUser(id);
}
public void updateUser(UserVO userVO) {
userDao.updateUser(userVO);
}
public UserVO selectUserById(Integer id) {
return userDao.selectUserById(id);
}
public List<UserVO> selectAllUser() {
return userDao.selectAllUser();
}
public Long getTotal(Map<String, Object> map) {
return null;
}
public List<UserVO> findUserByPage(Map<String, Object> map) {
return null;
}
public int checkUserExits(UserVO userVO) {
int result= this.userDao.checkUserExits(userVO);
if(result<1){
//不存在
return 0;
}else{
return 1;
}
}
public int getUserCount() {
return this.userDao.getUserCount();
}
}
10、在WEB-INF下新建檢視層資料夾jsp,然後在jsp下新建檔案user,然後在其下新建三個jsp資料夾
userList.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'userList.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<a href="${pageContext.request.contextPath}/user/addUser">新增</a>
<table width="60%" border="1" class="table table-striped">
<tr>
<th>使用者名稱</th>
<th>密碼</th>
<th>暱稱</th>
<th>郵箱</th>
<th>電話</th>
<th>角色</th>
<th>操作</th>
</tr>
<c:forEach items="${userList}" var="us">
<tr>
<td>${us.userName}</td>
<td>${us.password}</td>
<td>${us.trueName}</td>
<td>${us.email}</td>
<td>${us.phone}</td>
<td>${us.roleName}</td>
<td>
<a href="${pageContext.request.contextPath}/user/updateUser?id=${us.id}">編輯</a>
<a href="${pageContext.request.contextPath}/user/toDeleteUser?id=${us.id}">刪除</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
addUser.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'updateUser.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="${pageContext.request.contextPath}/user/toAddUser" method="post">
<input type="hidden" name="id" value="${id}"/>
<table width="50%" border="1">
<tr>
<td width="10%">使用者名稱:</td>
<td>
<input type="text" name="userName" />
</td>
</tr>
<tr>
<td>密碼:</td>
<td>
<input type="text" name="password" />
</td>
</tr>
<tr>
<td>暱稱</td>
<td>
<input type="text" name="trueName" />
</td>
</tr>
<tr>
<td>郵箱:</td>
<td>
<input type="text" name="email" />
</td>
</tr>
<tr>
<td>電話:</td>
<td>
<input type="text" name="phone" />
</td>
</tr>
<tr>
<td>角色:</td>
<td>
<input type="text" name="roleName" />
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="提交" />
</td>
</tr>
</table>
</form>
</body>
</html>
updateUser.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'updateUser.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="${pageContext.request.contextPath}/user/toUpdateUser" method="post">
<input type="hidden" name="id" value="${updateUser.id}" />
<table width="60%" border="1">
<tr>
<td width="10%">使用者名稱:</td>
<td>
<input type="text" name="userName" value="${updateUser.userName}"/>
</td>
</tr>
<tr>
<td>密碼:</td>
<td>
<input type="text" name="password" value="${updateUser.password}"/>
</td>
</tr>
<tr>
<td>暱稱</td>
<td>
<input type="text" name="trueName" value="${updateUser.trueName}"/>
</td>
</tr>
<tr>
<td>郵箱:</td>
<td>
<input type="text" name="email" value="${updateUser.email}"/>
</td>
</tr>
<tr>
<td>電話:</td>
<td>
<input type="text" name="phone" value="${updateUser.phone}"/>
</td>
</tr>
<tr>
<td>角色:</td>
<td>
<input type="text" name="roleName" value="${updateUser.roleName}"/>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="提交" />
</td>
</tr>
</table>
</form>
</body>
</html>
11、測試