這段時間上一個項目剛作完,下一個項目還沒開始,趁這個時候來認真總結一下上個項目使用的ssm開發框架。因爲,項目中關於使用ssm這部分的代碼和配置是咱們項目的總體架構師一個獨立完成的,咱們只負責業務部分的代碼,調用他寫好的後臺,因此涉及到ssm具體使用的我都沒參與,以前簡單的作過s(struts)sh,對於ssm不是很熟悉,因此,這段時間從頭至尾獨立搭建一個ssm框架的web應用。html
首先,spring、springmvc、mybatis所須要的jar包準備好,導入到新建web項目的lib中,而後開始搭建java源代碼(src)下的結構,我在這裏用到的是相似ssh的結構mapper.java、mapper.xml、dao、daoImpl、service、serviceImpl、controller。項目目錄結構以下。java
接下來,寫配置文件。mysql
web.xmlweb
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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> <!-- spring配置文件加載 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:resources/spring-config.xml</param-value> </context-param> <!-- Spring ApplicationContext 載入 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- mvc控制器 --> <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:resources/mvc-config.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- 默認顯示的首頁面 --> <welcome-file-list> <welcome-file>login.html</welcome-file> <welcome-file>login.jsp</welcome-file> </welcome-file-list> </web-app>
-----------------------------------------------spring.xml--------------------------------------ajax
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 掃描DAO和SERVICE包,controller包在springmvc中掃描 --> <context:component-scan base-package="com.liusk.serviceImpl,com.liusk.daoImpl" /> <!-- 數據源 --> <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:3306/ssm?characterEncoding=utf-8"></property> <property name="user" value="root"></property> <property name="password" value="java"></property> <property name="minPoolSize" value="5"></property> <property name="maxPoolSize" value="100"></property> </bean> <!-- 會話工廠 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:resources/mybatis-config.xml"></property> <property name="mapperLocations" value="classpath:com/liusk/mapper/*.xml"></property> </bean> <!-- 事務處理 --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="insert*" propagation="REQUIRED"></tx:method> <tx:method name="delete*" propagation="REQUIRED"></tx:method> <tx:method name="update*" propagation="REQUIRED"></tx:method> <tx:method name="select*" propagation="SUPPORTS"></tx:method> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="serviceCut" expression="execution(public * com.liusk.service.*.*(..))" /> <aop:advisor pointcut-ref="serviceCut" advice-ref="txAdvice" /> </aop:config> <!-- spring和mybatis的整合 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.liusk.mapper"/> </bean> </beans>
關於spring和mybatis整合的方法有不少種,上面xml中是最基礎的配置,還能夠加入其它的限制條件,這個能夠單獨到百度上搜更詳細的解釋。spring
-------------------------------------------------------mvc-config.xml------------------------------------------------sql
<?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" 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"> <!-- 掃描controller包 --> <context:component-scan base-package="com.liusk.controller"></context:component-scan> <!-- 完成請求和註解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> <!-- 頁面轉向解析 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 支持文件上傳 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> </bean> </beans>
在mvcconfig中,最重要的工做是控制轉發,這個配置文件中作了最簡單的轉發操做,只能轉發頁面,若是想要經過ajax實現轉發數據,那麼須要重寫ViewResolver來實現這個功能。數據庫
--------------------------------------------------------mybatis-config.xml-------------------------------------express
<?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> <!-- 定義別名 --> <typeAliases> <typeAlias type="com.liusk.entity.User" alias="User"/> </typeAliases> </configuration>
至此,配置文件部分完畢。session
下面是src源碼
----------------------------------------------------------User.java------------------------------------------------------
package com.liusk.entity; public class User { private String userId; private String username; private String password; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } 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; } }
mybatis的實體類和hibernate實體類的不一樣是mybatis的實體類不須要加載到spring的beanFactory中,而是經過操做數據庫的mapper來持久化數據。
-----------------------------------------------------------UserMapper.java------------------------------------------
package com.liusk.mapper; import java.util.List; import com.liusk.entity.User; public interface UserMapper { public List<User> selectUser(User user); public void insertUser(User user); public List<User> selectUserByUserName(String username); }
UserMapper.java這個文件是在什麼時候被加載到spring中的呢?咱們知道它是在daoImpl中使用到的,並且是註解到daoImpl中的,因此它必定在以前已經被加載到beanFactory中了,我在第一次配置的時候也不是太清楚它是何時進入beanFactory由於它身上沒有任何註解,因此,根據spring配置文件中spring和mybatis的整合,推測UserMapper.java就是在
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.liusk.mapper"/></bean>
這個地方被加載的。這個下面有詳細解答。
----------------------------------------------------------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"> <mapper namespace="com.liusk.mapper.UserMapper"> <resultMap type="com.liusk.entity.User" id="userMap"> <id column="user_id" property="userId" ></id> <result column="user_name" property="username"/> <result column="password" property="password"/> </resultMap> <select id="selectUser" parameterType="User" resultType="java.util.List" resultMap="userMap"> select * from user where user_name = #{username} and password = #{password} </select> <select id="selectUserByUserName" parameterType="java.lang.String" resultType="java.util.List" resultMap="userMap"> select * from user where user_name = #{username} </select> <insert id="insertUser" parameterType="User"> insert into user values (#{userId},#{username},#{password}) </insert> </mapper>
該配置文件中namespace對應接口的路徑,也就是mapper.java的路徑,不然拋出異常。因此這裏牽涉到一個問題:UserMapper.java究竟是什麼時候加載到beanFactory的?爲何會用這個問題呢,應爲UserMapper.xml在spring的sessionFactory初始化的時候被掃描並加載到spring,那麼這個時候會不會根據這個命名空間同時把UserMapper.java加載到beanFactory中呢,其實我沒有看過spring和mybatis的源碼,因此不太瞭解。根據猜想和驗證,UserMapper.java不是在這個時候被加載的。
------------------------------------------------------UserDAO--------------------------------------------
package com.liusk.dao; import java.util.List; import com.liusk.entity.User; public interface UserDAO { public List<User> selectUser(User user); public void insertUser(User user); public List<User> selectUserByUserName(String username); }
這個UserDAO的存在就是在向個人第一個項目使用ssh致敬的,其實這個UserDAO他就是個接口,能夠不存在,下面的UserService也是這個道理。
------------------------------------------------------UserDAOImpl----------------------------------------
package com.liusk.daoImpl; import java.util.List; import org.safehaus.uuid.UUIDGenerator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.liusk.dao.UserDAO; import com.liusk.entity.User; import com.liusk.mapper.UserMapper; @Repository public class UserDAOImpl implements UserDAO { @Autowired private UserMapper userMapper; private UUIDGenerator uuidGen = UUIDGenerator.getInstance(); @Override public List<User> selectUser(User user) { return userMapper.selectUser(user); } @Override public void insertUser(User user) { String userId = uuidGen.generateTimeBasedUUID().toString(); if(user.getUserId()==null||user.getUserId()=="") user.setUserId(userId.replace("-", "")); System.out.println(user.getUserId()); userMapper.insertUser(user); } @Override public List<User> selectUserByUserName(String username) { return userMapper.selectUserByUserName(username); } }
UserDAOImpl和UserServiceImpl相似,都是實現類,作具體的數據持久化操做。
--------------------------------------------------------UserService-----------------------------------------
package com.liusk.service; import java.util.List; import com.liusk.entity.User; public interface UserService { public void insertUser(User user); public List<User> selectUser(User user); public boolean existUser(String username); }
--------------------------------------------------------UserServiceImpl--------------------------------------
package com.liusk.serviceImpl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.liusk.dao.UserDAO; import com.liusk.entity.User; import com.liusk.service.UserService; @Service public class UserServiceImpl implements UserService{ @Autowired private UserDAO userDAO; @Override public void insertUser(User user) { userDAO.insertUser(user); } @Override public List<User> selectUser(User user) { return userDAO.selectUser(user); } @Override public boolean existUser(String username) { List<User> userList = userDAO.selectUserByUserName(username); if(userList.size()>0) return true; else return false; } }
-------------------------------------------------------UserController-------------------------------------
package com.liusk.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.liusk.base.UserCounts; import com.liusk.entity.User; import com.liusk.service.UserService; @Controller @RequestMapping("user") public class UserController { @Autowired private UserService userService; @SuppressWarnings("rawtypes") @RequestMapping("login.do") public ModelAndView login(String username,String password,HttpServletRequest request){ User user = new User(); user.setUsername(username); user.setPassword(password); List<User> userList = userService.selectUser(user); if(userList.size()>0){ request.setAttribute("userList", userList);return new ModelAndView("index"); }else return new ModelAndView("login"); } @RequestMapping("regist.do") public ModelAndView regist(String username,String password,HttpServletRequest request){ User user = new User(); user.setUsername(username); user.setPassword(password); boolean flag = true; flag = userService.existUser(username); if(!flag) userService.insertUser(user); return new ModelAndView("login"); } }
至此,src下的java源碼完畢。
下面是jsp頁面部分。
-----------------------------------------------------login.jsp--------------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8" 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" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <base href=" <%=basePath%>"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登陸頁面</title> </head> <body> <div> <div> <form action="user/login.do" method="post"> <label>用戶名:</label> <input type="text" name="username" /> <label>密碼:</label> <input type="password" name="password"/> <button type="submit">登陸</button> <button type="reset" >重置</button> </form> </div> </div> </body> </html>
-----------------------------------------------------index.jsp--------------------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="com.liusk.entity.User" %> <%@ page import="java.util.List" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <% List<User> userList = (List<User>)request.getAttribute("userList");%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <base href=" <%=basePath%>"/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>index</title> </head> <body> <div> <p>歡迎<%=userList.get(0).getUsername() %>!</p> </div> <div align="center" style="width:200;height:200"> <form action="user/regist.do" method="post"> <input type="text" name="username"/> <input type="text" name="password"/> <button type="submit">提交</button> <button type="reset">重置</button> </form> </div> </body> </html>
jsp你懂得,這些頁面就不作多解釋。
總結,會用框架不難,難的是寫一個框架出來,有夢就要勇敢飛。