1. 程式人生 > >SpringMVC+Ibatis框架搭建

SpringMVC+Ibatis框架搭建

 這是一個很簡單的SpringMVC+Spring+Ibatis框架 ,下圖是檔案的基本配置

web.xml

在web.xml中配置兩個氫氣,一個是SpringMVC的DispacherServlet,一個是Spring的ContextLoaderListener。

DispacherServlet負責初始化的上下文是和SpringMVC有關的bean,比如handlerMapping,handlerAdapter,viewResolve,ContextLoaderListener負責初始化的上下文是Spring有關的bean,比如dao,service

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<display-name></display-name>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	
	<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*:com/springmvcibatis/config/ControllerApplicationContext.xml</param-value>
		</init-param>
	</servlet>
	
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
                      classpath*:com/springmvcibatis/config/IbatisApplicationContext.xml
                      classpath*:com/springmvcibatis/config/ServiceApplicationContext.xml
            </param-value>
	</context-param>
	
	<servlet-mapping>
		<servlet-name>SpringMVC</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
</web-app>

ControllerApplicationContext.xml

SpringMVC的相關配置和controller層的配置在這個檔案中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     
    xmlns="http://www.springframework.org/schema/beans"    
    xmlns:mvc="http://www.springframework.org/schema/mvc"    
    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-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/context  
        http://www.springframework.org/schema/context/spring-context-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/tx   
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> 
        
        <!-- HandlerMapping 解析url,找到執行該url的action-->
        <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
               <property name="mappings">
                              <props>
                                     <prop key="/login.do">loginAction</prop>
                              </props>
               </property>
        </bean>
        
       
         <bean id="loginAction" class="com.springmvcibatis.controller.UserAction">
                   <property name="methodNameResolver">
	                           <ref local="methodNameResolver"/>
	             </property>
         </bean>     
         
          <!--檢視解析器-->  
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
            <!-- webroot到一指定資料夾檔案路徑 -->  
            <property name="prefix" value="/user/"/>  
            <!-- 檢視名稱字尾  -->  
            <property name="suffix" value=".jsp"/>  
        </bean>  
        <!-- 在url中對應具體的方法,通過m後面帶的引數來確定方法 -->
	<bean id="methodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">	
	            <property name="paramName"><value>m</value></property>   
		        <property name="defaultMethodName"><value>execute</value></property>
	</bean>
</beans>

ServiceApplicationContext.xml

Service層的配置,向Service層中注入DAO

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
          <bean  id="userService" class="com.springmvcibatis.service.UserService">
                   <property name="userDAO" ref="userDAO"></property>
          </bean>
</beans>

IbatisApplicationContext.xml

Ibatis配置和DAO的配置,這個ibatis層配置知道怎麼配置,但裡面的具體原理還是不太清楚,有時間弄弄吧

<?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"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">  
<!--資料來源配置 這塊用 mysql資料庫 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/test" />
		<property name="username" value="root" />
		<property name="password" value="123456" />
	</bean>
	
	<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
		  	   <property name="dataSource" ref="dataSource" />  
		       <property name="configLocation">
		           <value>classpath:com/springmvcibatis/config/SqlMapConfig.xml</value>
		       </property>
    </bean>
    
    <bean id="sqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate">  
        <property name="sqlMapClient" ref="sqlMapClient"></property> 
    </bean>
    
    <bean id="userDAO" class="com.springmvcibatis.dao.UserDAOImp">
              <property name="sqlMapClientTemplate" ref="sqlMapClientTemplate"></property>
    </bean>

</beans>

SqlMapConfig.xml
每個dao對應的sql配置檔案就在這裡面集合,我這裡只有一個dao,所以也就一個這個檔案裡面只配置了一個sql檔案
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig      
    PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"      
    "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
 <sqlMapConfig>
        <sqlMap resource="com/springmvcibatis/pojo/UserSql.xml"/>
 </sqlMapConfig>

UserSql.xml

每個dao對應的sql配置檔案,檔案裡面就是和增刪查改有關的

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"
 "http://www.ibatis.com/dtd/sql-map-2.dtd">
 <sqlMap>
          <typeAlias type="com.springmvcibatis.pojo.User" alias="User"/>
          <resultMap class="User" id="user">
                    <result property="id" column="id"></result>
                    <result property="username" column="username"></result>
                    <result property="password" column="password"></result>
          </resultMap>
          
          <select id="selectByName"  parameterClass="java.lang.String" resultMap="user">
                    select * from user where username=#username#;
          </select>
          
          <select id="selectList" resultMap="user">
                    select * from user;
          </select>
          <!-- 插入一條並返回主鍵id -->
          <insert id="insertUser" parameterClass="User" >
                   insert into user(username,password) values(#username#,#password#)
                   <selectKey resultClass="int" keyProperty="id">
                      select LAST_INSERT_ID() AS VALUE
                   </selectKey>
          </insert>
          
          <delete id="deleteUser" parameterClass="int">
                    delete from user where id=#id#;
          </delete>
 </sqlMap>


UserAction.java

contrller層
package com.springmvcibatis.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.springmvcibatis.pojo.User;
import com.springmvcibatis.service.UserService;

public class UserAction extends MultiActionController{
	/**
	 * 登陸
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView login(HttpServletRequest request,HttpServletResponse response){		
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		UserService service = (UserService) this.getApplicationContext().getBean("userService");
		boolean result = service.selectUserByName(userName, password);
		String viewName = null;
		if(result){		
			viewName = "success";
		}else{
			viewName = "fail";
		}
		ModelAndView mv = new ModelAndView(viewName);
		return  mv;		
	}
	
	/**
	 * 註冊
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView resign(HttpServletRequest request,HttpServletResponse response){		
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		UserService service = (UserService) this.getApplicationContext().getBean("userService");
		User user = new User();
		user.setUsername(userName);
		user.setPassword(password);
		int i = service.insertUser(user);
		ModelAndView mv = new ModelAndView("success");
		return mv;
	}

}


UserService.java

service層

package com.springmvcibatis.service;

import java.util.List;

import com.springmvcibatis.dao.UserDAO;
import com.springmvcibatis.pojo.User;

public class UserService {
	 private UserDAO userDAO;

	public UserDAO getUserDAO() {
		return userDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}
	
	public boolean selectUserByName(String userName,String password){
		List<User> list = userDAO.selectByName(userName);
		boolean result = false;
		if(list!=null&&list.size()>0){
			User user = list.get(0);
			if(password.equals(user.getPassword())){
				result = true;
			}
		}
		return result;
	}
	
	public int insertUser(User user){
		int id = userDAO.insertUser(user);
		return id;
	}
	
	public int deleteUser(int id){
		int result = userDAO.deleteUser(id);
		return result;
	}

}
UserDAO.java
dao介面
package com.springmvcibatis.dao;

import java.util.List;

import com.springmvcibatis.pojo.User;

public interface UserDAO {
	public List<User> selectByName(String userName);
	
	public int insertUser(User user);
	
	public List<User> selectList();
	
	public int deleteUser(int id);

}
UserDAOImp.java

dao的實現類,這個繼承了SqlMapClientDaoSupport,還有一個構造方法

package com.springmvcibatis.dao;

import java.util.List;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.springmvcibatis.pojo.User;

public class UserDAOImp extends SqlMapClientDaoSupport implements UserDAO{
    
	public UserDAOImp(){
		super();
	}
	public List<User> selectByName(String userName) {
		List<User> list = (List<User>) getSqlMapClientTemplate().queryForList("selectByName", userName);
		return list;
	}

	public int insertUser(User user) {
		int id = (Integer) getSqlMapClientTemplate().insert("insertUser", user);
		return id;
	}

	public List<User> selectList() {
		List<User> list = getSqlMapClientTemplate().queryForList("selectList");
		return list;
	}

	public int deleteUser(int id) {
		int result = getSqlMapClientTemplate().delete("deleteUser", id);
		return result;
	}

}

User.java

pojo

package com.springmvcibatis.pojo;

public class User {
	private int id;
	private String username;
	private String password;
	public int getId() {
		return id;
	}
	public void setId(int 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;
	}
	

}


      最近找工作找的挺鬱悶的,真的懷疑自己的能力了,工作還沒殺著落,昨天來將這個框架搭好了,已經快工作兩年了還搞大學時候的事情,哎,只怪以前沒有好好學習,現在也沒好好學習,這篇文章沒啥註釋,挺過意不去的,其實ibatis的原始碼自己也沒看,只知道怎麼用,裡面具體怎麼走的還真不知道。主要是給菜鳥看的,也是對自己成長的一個記錄,以後為圍繞這個框架添磚加瓦的,還有AOP,事物管理之類的給加上。何時才能找到工作!!!