Struts2主要來源於webwork框架,與Struts1相比,在數據傳遞方面,Struts2提供了更加強大OGNL標簽功能,使其能夠通過在action中定義變量來直接與jsp頁面中的數據進行相互傳值,省去了Struts1中的formbean;而在跳轉控制方面,Struts2簡化了配置文件的信息量,使頁面和action之間的交換更加的簡潔和直觀,便於開發人員的管理。
Spring功能非常的強大,比如它的控制反轉/依賴注入機制,省去了我們自己書寫工廠模式的工作,實現類對我們將要用到控制類、業務邏輯類、數據訪問類、以及JNDI或者JDBC數據源的托管;Spring對AOP支持使我們在用戶chmod.html' target='_blank'>權限控制、事務處理方面節省了很多工作量;
iBatis則是一種輕量級的OR Mapping框架,與Hibernate相比,iBatis提供了半自動化對象關系 映射的實現,開發人員需要編寫具體的sql語句,為系統設計提供了更大的自由空間,為sql語句優化提供了便利。
下面這張圖就是我們所用到的這三種框架的結合體,下面對其作以簡單介紹。
在控制層,利用Strtus2標簽功能,在Action中直接與jsp頁面上的數據進行交互。在調用業務邏輯層應用時,Struts2提供了對Sping的支持。開發人員需要完成對struts.xml的配置工作和對各個Action類的編寫。
在業務邏輯層,利用Spring框架的依賴注入實現對業務邏輯類和DAO類的實例托管;在事務處理方面,利用Spring提供的面向切面的事務處理功能,使對數據的事務控制脫離於數據訪問接口實現;在對象關系映射方面,利用Spring對數據庫連接池的托管和對iBatis框架的支持。開發人員需要完成對數據源的配置、對不同模塊所對應的application*.xml文件的配置,以及對業務邏輯接口的定義和業務邏輯實現的編寫。
在持久層,利用iBatis提供的半自動化對象關系映射的實現,開發人員需要編寫具體的sql語句,為系統設計提供了更大的自由空間。另外,開發人員需要完成對SqlMapConfig.xml和*SqlMap.xml的配置,以及對DAO接口的定義和DAO接口的實現。
在各層之間進行交換的過程中,利用數據傳輸類進行數據的傳遞和交互。其中,數據傳輸類與數據庫表一一對應。
SSI框架能夠降低我們代碼的耦合度,增強了代碼的健壯性和可重用性,加快了開發速度,但是也有一些不足之處,比如由於三種框架的配置文件較多,也給我們帶來了一些不便,特別是對於較小的應用來說更是如此。
一:首先引入struts2 spring ibatis 各自的jar包 在此就不一一羅列了。
二:添加配置文件
我們首先從web.xml文件說起
web.xml加載過程:
1 啟動WEB項目的時候,容器(如:Tomcat)會讀他的配置文件web.xml讀兩個節點
<listener></listener>和<context-param></context-param>
2 緊接着,容器創建一個ServletContext(上下文) 這個WEB項目所有部分都將共享這個上下文
3 容器將<context-param></context-param>轉化為鍵值對並交給ServletContext
4 容器創建<listener></listener>中的類的實例,即創建監聽
5 在監聽中會有contextInitialized(ServletContextEvent args)初始化方法,在這個方法中獲得:
ServletContext = ServletContextEvent.getServletContext();
context-param的值 = ServletContext.getInitParameter("context-param的鍵");
web.xml節點加載順序
節點的加載順序與它們在web.xml文件中的先后順序無關。即不會因為filter寫在listener的前面而會先加載filter最終得出的結論是:listener->filter->servlet
同時還存在着這樣一種配置節點:context-param,它用於向 ServletContext 提供鍵值對,即應用程序上下文信息。我們的 listener, filter 等在初始化時會用到這些上下文 的信息,那么context-param 配置節是不是應該寫在 listener 配置節前呢?實際上 context-param 配置節可寫在任意位置,因此真正的加載順序為:
context-param -> listener -> filter -> servlet
加載spring
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
最終結論:
web.xml 的加載順序是:[context-param -> listener -> filter -> servlet -> spring] ,而同類型節點之間的實際程序調用的時候的順序是根據對應的 mapping 的順序進行調 用的。
打開web.xml文件,根據實際需要添加如下內容
<!--上下文參數用於log4j以及spring中使用--> <context-param> <param-name>webAppRootKey</param-name> <param-value>/WEB-INF/log4j.properties</param-value> </context-param> <!--應用程序上下文參數,指定spring配置文件位置--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/beans.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener -class> </listener> <!--監聽器 用於初始化spring框架--> <listener> <listener- class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
在這說說SSI整合時的一些配置文件:
1.contextConfigLocation:Spring容器啟動時需要加載Spring的配置文件。默認是/WEB-INF目錄下的applicationContext.xml文件
當然也可以放在classpath下,可以包括多個spring配置文件,這就得依靠contextConfigLocation
<!-- 加載spring的配置文件 如果文件名為applicationContext.xml並且是在WEB-INF目錄下 則無需此配置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/beans.xml</param-value> </context-param>
如果web.xml中沒有配置context-param,spring的配置就像如上這段代碼示例一下,自動去WEB-INF目錄下尋找applicationContext.xml。此時,如果你修改applicationContext.xml的名稱,或者移除它,再啟動服務器,你會得到如下異常信息:
1.nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml]
這證實了其默認配置。默認配置情況下spring只會去WEB-INF目錄下尋找配置文件,而不會去classpath下尋找。
如果我們不想將配置文件放在WEB-INF目錄下呢?開發中經常在src下面創建一個config目錄,用於存放配置文件。此時,對應的param-value改為:classpath:config/applicationContext.xml。
一定要加上classpath,這告訴spring去classes目錄下的config目錄下面尋找配置文件。
2.如何啟動Spring容器
兩種方法,一種以listener啟動 一種以load-on-startup Servlet。
<!-- 配置spring監聽器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
第二種
<servlet> <servlet-name>context</servlet-name> <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet>
3.整合Struts2
<filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
4.Spring整合ibatis配置文件
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="configLocation"> <value>classpath:SqlMapConfig.xml</value> </property> </bean>
5.Struts.xml
<?xml version="1.0"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<package name="surveyParkPkg" namespace="/" extends="struts-default">
<!-- logAction -->
<action name="UserAction_*" class="userAction" method="{1}">
<result name="userList">/userList.jsp</result>
<result name="showUsers" type="redirectAction">UserAction_findAllUser</result>
<result name="updateUser">/updateUser.jsp</result>
</action>
</package>
</struts>
constant配置struts的常量(也可在struts.properties)文件中配置,將struts的對象工廠托由spring管理。
6.beans.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: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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!-- 數據源 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost/mybatis"/> <property name="username" value="root"/> <property name="password" value="123456f"/> </bean> <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:sqlMapConfig.xml"/> </bean> <!-- ================================事務相關控制================================================= --> <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <tx:advice id="userTxAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="find*" read-only="true" /> <tx:method name="get*" read-only="true" /> <tx:method name="select*" read-only="true" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="pc" expression="execution(* cn.itcast.mybatis.service.*.*(..))" /> <!--把事務控制在Service層--> <aop:advisor pointcut-ref="pc" advice-ref="userTxAdvice" /> </aop:config> <bean id="userDao" class="cn.itcast.mybatis.dao.UserDaoImpl"> <property name="sqlSessionFactory" ref="sessionFactory"/> </bean> <bean id="userService" class="cn.itcast.mybatis.service.UserServiceImpl"> <property name="userDao" ref="userDao"/> </bean> <bean id="userAction" class="cn.itcast.mybatis.action.UserAction" scope="prototype"> <property name="userService" ref="userService"/> </bean> </beans>
7User.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="cn.itcast.mybatis.domain.User"> <select id="selectUserById" parameterType="string" resultType="User"> select * from user where id = #{uid} </select> <select id="selectUserByIdForMap" parameterType="string" resultType="hashmap"> select * from user where id = #{uid} </select> <select id="selectAllUser" resultType="User"> select * from user </select> <select id="selectAllUserForMap" resultType="hashmap"> select * from user </select> <delete id="deleteUserById" parameterType="string"> delete from user where id = #{uid} </delete> <insert id="saveUser" parameterType="User"> insert into user (id,name,age,address) values(#{id},#{name},#{age},#{address}) </insert> <insert id="saveUserForMap" parameterType="hashmap"> insert into user (id,name,age,address) values(#{id},#{name},#{age},#{address}) </insert> <update id="updateUserById" parameterType="User"> update user set name = #{name} ,age = #{age},address = #{address} where id = #{id} </update> <update id="updateUserByIdForMap" parameterType="hashmap"> update user set name = #{name} ,age = #{age},address = #{address} where id = #{id} </update> <!-- 動態sql --> <select id="selectUserByCondition" parameterType="User" resultType="User"> select * from user where 1=1 <if test="id != null"> and id = #{id} </if> <if test="name != null"> and name = #{name} </if> <if test="age != null"> and age = #{age} </if> <if test="address != null"> and address = #{address} </if> </select> <!-- 動態sql --> <select id="selectUserByConditionForMap" parameterType="hashmap" resultType="User"> select * from user where 1=1 <if test="id != null"> and id = #{id} </if> <if test="name != null"> and name = #{name} </if> <if test="age != null"> and age = #{age} </if> <if test="address != null"> and address = #{address} </if> </select> <!-- 動態sql --> <select id="selectUserByCondition2" parameterType="User" resultType="User"> select * from user <where> <if test="id != null"> id = #{id} </if> <if test="name != null"> and name = #{name} </if> <if test="age != null"> and age = #{age} </if> <if test="address != null"> and address = #{address} </if> </where> </select> <!-- 動態sql 更新 --> <update id="updateUserByCondition" parameterType="User"> update user <set> <if test="name != null"> name = #{name}, </if> <if test="age != null"> age = #{age}, </if> <if test="address != null"> address = #{address} </if> </set> where id = #{id} </update> </mapper>
8.UserAction
package cn.itcast.mybatis.action; import java.util.List; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import cn.itcast.mybatis.domain.User; import cn.itcast.mybatis.service.IUserService; import com.opensymphony.xwork2.ActionSupport; public class UserAction extends ActionSupport { private static final long serialVersionUID = 1L; public UserAction() {} private IUserService userService; private String id; /* * 查詢所有數據 */ public String findAllUser(){ HttpServletRequest req = ServletActionContext.getRequest(); //User u = userService.findUserById(id); List<User> users = userService.selectUserByCondition(new User()); req.setAttribute("users", users); return "userList"; } /* * 根據選擇的id進行刪除 然后回顯到 顯示所有.jsp處 */ public String deleteUserById(){ userService.deleteUserById(id); return "showUsers"; } /* * 插入數據 並 保存數據庫 然后回顯到 顯示所有.jsp處 */ public String saveUser(){ HttpServletRequest req = ServletActionContext.getRequest(); String id = UUID.randomUUID().toString();//javaJDK提供的一個自動生成主鍵的方法-16位 String name = req.getParameter("name"); String address = req.getParameter("address"); String ageStr = req.getParameter("age"); User u = new User(); u.setId(id); u.setName(name); u.setAddress(address); u.setAge(new Integer(ageStr)); userService.insertUser(u); return "showUsers"; } /* * 點擊修改鏈接 根據id進入一個編輯界面updateUser.jsp 里面存放的是根據點擊的id查詢到的數據信息 * 修改完成后 <form action="<%=path %>/UserAction_updateUser" method="POST"> * 把修改后的數據全部獲取 然后封裝到user中 通過updateUserByCondition(u)保到數據庫 * 然后回顯 顯示所有.jsp處 */ public String updateUserUI(){ HttpServletRequest req = ServletActionContext.getRequest(); String id = req.getParameter("id"); User u = userService.findUserById(id); req.setAttribute("user", u); return "updateUser"; } /* * 點擊修改鏈接 根據id先回顯到 本次數據 然后進行修改 修改完成后回顯到顯示所有.jsp處 */ public String updateUser(){ HttpServletRequest req = ServletActionContext.getRequest(); String id = req.getParameter("id"); String name = req.getParameter("name"); String address = req.getParameter("address"); String ageStr = req.getParameter("age"); User u = new User(); u.setId(id); u.setName(name); u.setAddress(address); u.setAge(new Integer(ageStr)); userService.updateUserByCondition(u); return "showUsers"; } public String getId() { return id; } public void setId(String id) { this.id = id; } public void setUserService(IUserService userService) { this.userService = userService; } }
9.最后的頁面顯示部分 三個
UserList.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <% 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> <title>My JSP 'userList.jsp' starting page</title> </head> <body> <h3>UserList</h3> <a href="addUser.jsp">添加User</a> <table border="1" width="70%"> <tr> <td>id</td> <td>name</td> <td>age</td> <td>address</td> <td>刪除</td> <td>修改</td> </tr> <c:forEach items="${requestScope.users}" var="user"> <tr> <td>${user.id }</td> <td>${user.name }</td> <td>${user.age }</td> <td>${user.address }</td> <td><a href="<%=path %>/UserAction_deleteUserById?id=${user.id }">刪除</a></td> <td><a href="<%=path %>/UserAction_updateUserUI?id=${user.id }">修改</a></td> </tr> </c:forEach> </table> </body> </html>
addUser.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <% 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> <title>My JSP 'userList.jsp' starting page</title> </head> <body> <h3>UserList</h3> <a href="addUser.jsp">添加User</a> <table border="1" width="70%"> <tr> <td>id</td> <td>name</td> <td>age</td> <td>address</td> <td>刪除</td> <td>修改</td> </tr> <c:forEach items="${requestScope.users}" var="user"> <tr> <td>${user.id }</td> <td>${user.name }</td> <td>${user.age }</td> <td>${user.address }</td> <td><a href="<%=path %>/UserAction_deleteUserById?id=${user.id }">刪除</a></td> <td><a href="<%=path %>/UserAction_updateUserUI?id=${user.id }">修改</a></td> </tr> </c:forEach> </table> </body> </html>
updateUser.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <html> <head> <title>My JSP 'addUser.jsp' starting page</title> </head> <body> <form action="<%=path %>/UserAction_updateUser" method="POST"> <input type="hidden" name="id" value="${user.id }"> <table> <tr> <td> name: </td> <td> <input type="text" name="name" value="${user.name }"> </td> </tr> <tr> <td> age: </td> <td> <input type="text" name="age" value="${user.age }"> </td> </tr> <tr> <td> address: </td> <td> <input type="text" name="address" value="${user.address }"> </td> </tr> <tr> <td> <input type="submit" value="保存"> </td> <td> <input type="reset" value="重置"> </td> </tr> </table> </form> </body> </html>
項目搭建到 這基本完成 .......有些類就省略了 比較簡單 最重要的還是思路吧 順便截個屏 方便有心的人繼續補全項目