spring、springmvc、mybatis整合配置(註解)
阿新 • • 發佈:2018-12-25
最近整合ssm框架費了不少功夫,所以,把詳細配置過程列出來,不足的地方望大俠們指正!
專案目錄:
1.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>ssm</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 配置檔案 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </context-param> <!-- 配置spring監聽器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置分發請求的前端控制器 --> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 配置編碼過濾器 --> <filter> <filter-name>encode</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>forceEncoding</param-name> <param-value>True</param-value> </init-param> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encode</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
2.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: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:component-scan base-package="com.cn.su.controller"></context:component-scan> <!-- 配置檢視層跳轉 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 靜態資源配置 --> <mvc:annotation-driven /><!-- 啟動註解,配置靜態資源必須 --> <mvc:resources location="/" mapping="/*.html" /> <mvc:resources location="/css/" mapping="/css/*" /> <mvc:resources location="/js/" mapping="/js/*" /> <mvc:resources location="/images/" mapping="/images/*" /> </beans>
3.spring-mybatis.xml配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" 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" 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-3.1.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 "> <!-- 自動掃描包 --> <context:component-scan base-package="com.cn.su"></context:component-scan> <!-- 引入配置檔案 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <!-- dataSource資料來源配置 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <!-- 初始化連線大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 連線池最大數量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 連線池最大空閒 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 連線池最小空閒 --> <property name="minIdle" value="${minIdle}"></property> <!-- 獲取連線最大等待時間 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- sessionFactory工廠配置 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- mybatis和spring完美配置,不需要配置mapper對映檔案 --> <property name="mapperLocations" value="classpath*:com/cn/su/mapper/*.xml"></property> </bean> <!-- dao層配置 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- spring會自動查詢該包下的類 --> <property name="basePackage" value="com.cn.su.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 配置事物的傳播性 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 傳播行為 --> <!-- REQUIRED:支援當前事務,如果當前沒有事務,就新建一個事務; SUPPORTS:支援當前事務,如果當前沒有事務,就以非事務的方式執行 --> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="insert*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="find*" propagation="SUPPORTS" read-only="true"/> <tx:method name="select*" propagation="SUPPORTS" read-only="true"/> <tx:method name="query*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice> <!-- 配置aop切面 --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.cn.su.service.impl.*.*(..))"/> </aop:config> </beans>
4.測試:
<1>login.jsp(登入頁面)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登入</title>
</head>
<body>
<h2>Login</h2>
<form action="user/checkLogin" method="post">
username:<input type="text" name="username" value="" placeholder="please enter your username!"/><br>
password:<input type="password" name="password" value="" placeholder="please enter your password!" /><br>
<input type="submit" value="登入" />
</form>
<div>
<span style="color:red">${errorMessage}</span>
</div>
</body>
</html>
<2>UserController控制層(userController注入的是IUserService介面,這裡不能是實體類UserServiceImpl哦,
這是spring的代理模式決定的,具體看,http://blog.csdn.net/jyp360/article/details/70215002):
package com.cn.su.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.cn.su.entity.User;
import com.cn.su.service.IUserService;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService iUserService;
@RequestMapping("/checkLogin")
public String login(User user,Model model){
System.out.println("username:"+user.getUsername()+",password:"+user.getPassword());
boolean flag = iUserService.selectSingleUser(user.getUsername(), user.getPassword());
if(flag){
return "success";
}else{
model.addAttribute("errorMessage", "使用者名稱或者密碼不正確");
return "login";
}
}
}
<3>IUserService
package com.cn.su.service;
public interface IUserService {
public boolean selectSingleUser(String username,String password);
}
<4>UserServiceImpl
package com.cn.su.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cn.su.dao.IUserDao;
import com.cn.su.service.IUserService;
@Service
public class UserServiceImpl implements IUserService{
@Autowired
private IUserDao iUserDao;
@Override
public boolean selectSingleUser(String username,String password) {
return iUserDao.selectSingleUser(username,password) == 1 ? true : false;
}
}
<5>IUserDao
package com.cn.su.dao;
import org.apache.ibatis.annotations.Param;
public interface IUserDao {
public int selectSingleUser(@Param("username") String username,@Param("password") String password);
}
<6>UserMapper.xml(值得注意的是,這裡的namespace="com.cn.su.dao.IUserDao"注意哦,是以dao介面檔案
包取值的,如果不這樣寫,會報錯,詳情見:http://blog.csdn.net/u010504064/article/details/47337307)
<?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.cn.su.dao.IUserDao">
<select id="selectSingleUser" resultType="int" parameterType="com.cn.su.entity.User">
select EXISTS(select * from tb_user where username = #{username} and password = #{password});
</select>
</mapper>
最後跳轉成功後頁面:success.jsp配置在WEB-INF/pages/succes.jsp,路徑不要寫錯了。整合jar包我分享下,
這裡有些jar包不需要用到,用到的都在裡面。附加上鍊接地址:
http://download.csdn.net/download/qq_25313187/10032339