Struts2+Ibatis+Spring.30(完整例子,含3.0事务配置,OSCache缓

 

1.新建表

create table

(

id int  identity(1,1) primary key,

loginid varchar(10),

username varchar(20),

loginpassword varchar(20),

roleid varchar(10)

)

2.新建WEB项目,导入jar包,如下:

3.WEB-INF下,建立5个配置文件,结构如下

web.xml,

struts2-service.xml(配置Service类使用,可再拆分成多个配置文件)

struts2-action.xml(配置Action类使用,可再拆分成多个配置文件)

SqlMapConfig.xml(Ibatis映射文件)

applicationContext.xml,(数据源配置,事务配置,DAO配置)

内容如下:

web.xml完整内容:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
 xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  
  <!--  struts2配置 -->
  <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!-- JfreeChart配置 -->
    <servlet>
     <servlet-name>display</servlet-name>
     <servlet-class>org.jfree.chart.servlet.DisplayChart</servlet-class>
     
    </servlet>
    <servlet-mapping>
     <servlet-name>display</servlet-name>
     <url-pattern>/servlet/displaychart</url-pattern>
    </servlet-mapping>
    
    <!-- 指定Session过期后,自动删除tomcat目录下的temp文件夹内的图片 -->
    <listener>
     <listener-class>org.jfree.chart.servlet.ChartDeleter</listener-class>
     
    </listener>
    
    <!-- Spring配置 -->
     <listener>
     
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>/WEB-INF/applicationContext.xml
     ,/WEB-INF/struts2-action.xml
     ,/WEB-INF/struts2-service.xml
     </param-value>
    </context-param>
  
</web-app>

 

applicationContext.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.0.xsd
       http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.0.xsd
       http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-2.0.xsd">

    <!-- 利用AOP,实现对Service的声明式事务管理 -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
    
     <tx:attributes>
       <tx:method name="get*" read-only="true"/>
       <!-- 删除,更新,添加事务配置 -->
       <tx:method name="delete*" propagation="REQUIRED" 
       isolation="READ_COMMITTED"
       timeout="-1"
       read-only="false"
       />
       <tx:method name="update*" propagation="REQUIRED" 
       isolation="READ_COMMITTED"
       timeout="-1"
       read-only="false"
       />
       <tx:method name="add*" propagation="REQUIRED" 
       isolation="READ_COMMITTED"
       timeout="-1"
       read-only="false"
       />
       <!-- 其他默认 -->
       <tx:method name="*" />
     </tx:attributes>
    </tx:advice>

  <aop:config>
    <aop:pointcut id="servicepointcut" expression="execution(* com.ibatis.service.*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="servicepointcut"/>
  </aop:config>

  <!-- 配置数据源 -->
  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
    <property name="url" value="jdbc:sqlserver://localhost:1433; DatabaseName=DfcpMes"/>
    <property name="username" value="sa"/>
    <property name="password" value="sa"/>
  </bean>

  
  <!-- 配置事务管理 -->
  <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
  </bean>
  
  <!-- 配置DAO -->
  <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
    <property name="configLocation" value="WEB-INF/SqlMapConfig.xml"/>
    <property name="dataSource" ref="dataSource"/>
  </bean>

   <bean id="baseDAO" class="com.ibatis.dao.BaseDAOImp">
    <property name="sqlMapClient" ref="sqlMapClient"/>
  </bean>

  


</beans>

 

 

struts2-action.xml配置完整内容:

<?xml version="1.0" encoding="gb2312"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
    "http://www.springframework.org/dtd/spring-beans-2.0.dtd">


<!-- spring管理struts的bean的配置文件-->
<beans>
  <bean id ="baseAction" class ="com.ibatis.action.BaseAction" scope ="singleton" >
        <property name ="userservice" > 
            <ref bean ="usersServiceImpl" /> 
        </property> 
        <!-- 可添加多个Service注入 -->
     </bean> 
 
 <!-- 其他Action类,都继承基Action -->
 <bean id ="userAction" parent="baseAction" class ="com.ibatis.action.UserAction" scope ="prototype" >
        
     </bean> 
 
</beans>

 

struts2-service.xml配置完整内容:

<?xml version="1.0" encoding="gb2312"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
    "http://www.springframework.org/dtd/spring-beans-2.0.dtd">


<!-- spring管理struts的bean的配置文件-->
<beans>
 <bean id="baseService" scope="singleton"
  class="com.ibatis.service.impl.BaseServiceImpl">
  <property name="dao">
   <ref bean="baseDAO"/>
  </property>
  
 </bean>

 <bean name="usersServiceImpl" parent="baseService"
  class="com.ibatis.service.impl.UserServiceImpl">
 </bean>
 
</beans>

 

SqlMapConfig.xml配置完整内容:

<?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>

 <settings 
    cacheModelsEnabled="true"      
    enhancementEnabled="true"      
    lazyLoadingEnabled="true"      
    errorTracingEnabled="true"      
    maxRequests="32"          
    maxSessions="10"          
    maxTransactions="5"          
    useStatementNamespaces="true"   
    />


  <sqlMap resource="com/ibatis/bean/config/Users.xml"/>

</sqlMapConfig>

 

4.在src下建立POJO类,DAO类,Service类,Action类,log4j.properties,oscache.properties,struts.properties,struts.xml,结构如下

 

 

对每个类列出源码如下:

BaseAction.java源码

package com.ibatis.action;

import com.ibatis.service.IUserService;
import com.opensymphony.xwork2.ActionSupport;

public class BaseAction extends ActionSupport {

 protected IUserService userservice;

 public IUserService getUserservice() {
  return userservice;
 }

 public void setUserservice(IUserService userservice) {
  this.userservice = userservice;
 }
}

UserAction.java源码

package com.ibatis.action;

import java.util.List;

import com.ibatis.bean.Users;

public class UserAction extends BaseAction {

 private List<String> deleteLoginIdList;//批量删除用户(根据loginid字段)
 private Users user;//添加用户,更新用户,删除用户(只给loginid赋值)时,使用
 
 private List<Users> userList;//在页面中显示用户列表,批量添加时使用
 
 public List<Users> getUserList() {
  return userList;
 }


 public void setUserList(List<Users> userList) {
  this.userList = userList;
 }


 public Users getUser() {
  return user;
 }


 public void setUser(Users user) {
  this.user = user;
 }


 


 public List<String> getDeleteLoginIdList() {
  return deleteLoginIdList;
 }


 public void setDeleteLoginIdList(List<String> deleteLoginIdList) {
  this.deleteLoginIdList = deleteLoginIdList;
 }
 
 /**
  * 添加一个用户
  * @return
  */
 public String addUser()
 {
  userservice.addUser(user);//调用service执行添加
  return "AddOrEdit";
 }
 
 /**
  * 获取用户列表
  * @return
  */
 public String userList()
 {
  setUserList(userservice.getAllUsers());//调用service获取所有用户
  
  return "ShowUserList";
 }
 
 /**
  * 删除一个用户
  * @return
  */
 public String deleteOneUser()
 {
  userservice.deleteUser(user.getLoginid());
  return "AddOrEdit";
 }
 
 /**
  * 批量删除用户(根据LoginId字段)
  * @return
  */
 public String deleteBectchUser()
 {
  userservice.deleteBatchUser(deleteLoginIdList);
  return "AddOrEdit";
 }
 
 /**
  * 当点击编辑时,获取一个对象,再跳转到编辑页面
  * @return
  */
 public String fowardUpdateUser()
 {
  user=userservice.getOneUser(user.getLoginid());
  return "ShowOneUser";
 }
 
 
 /**
  * 更新一个用户
  * @return
  */
 public String updateUser()
 {
  userservice.updateUser(user);//调用service执行添加
  return "AddOrEdit";
 }
}

 

Users.java源码

package com.ibatis.bean;

public class Users {

 private int id;
 private String username;
 private String loginid;
 private String loginpassword;
 private String roleid;
 public String getRoleid() {
  return roleid;
 }
 public void setRoleid(String roleid) {
  this.roleid = roleid;
 }
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
 public String getLoginid() {
  return loginid;
 }
 public void setLoginid(String loginid) {
  this.loginid = loginid;
 }
 public String getLoginpassword() {
  return loginpassword;
 }
 public void setLoginpassword(String loginpassword) {
  this.loginpassword = loginpassword;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
}

 

Users.xml配置文件完整内容

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE sqlMap      
    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"      
    "http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap namespace="user_space">

  
  <!-- 配置缓存LRU表示当缓存达到最大值后,先清除最少使用的记录,再在缓存中加入新记录 -->
  <cacheModel id="userCache" type="OSCACHE"> 
   <flushInterval hours="24"/> 
   <flushOnExecute statement="user_space.insertUsers"/> 
   <flushOnExecute statement="user_space.updateUsers"/> 
   <flushOnExecute statement="user_space.deleteUsersByLoginId"/> 
   <property name="size" value="1000" /> 
  </cacheModel> 
  
  <typeAlias alias="user" type="com.ibatis.bean.Users"/>


  <resultMap id="userResult" class="user">
    <result property="username" column="username"/>
    <result property="loginid" column="loginid"/>
    <result property="loginpassword" column="loginpassword"/>
    <result property="roleid" column="roleid"/>
  </resultMap>

  
  <!-- 返回结果为List -->
  <select id="selectAllUsers" resultMap="userResult" cacheModel="userCache">
    select * from Users
  </select>


  <!-- 根据loginid查询一个用户 -->
  <select id="selectUsersByLoginId" parameterClass="String" resultClass="user">
   <![CDATA[ 
    select
     loginid,
     username,
     loginpassword,
     roleid
    from users
    where loginId = #loginid#
    ]]>
  </select>
  
  
  
  
   
  
  <insert id="insertUsers" parameterClass="user">
  <!-- 生成主键的方式(post表示添加后生成,pre表示添加前生成如Oracle) -->
  <selectKey resultClass="int" type="post" keyProperty="id" >   
        select @@IDENTITY as id
    </selectKey>   
    
    <!--  oracle用序列生成主键的配置
   <selectKey resultClass="int" type="pre" keyProperty="id" >   
        SELECT STOCKIDSEQUENCE.NEXTVAL AS VALUE FROM DUAL   
    </selectKey>   
  -->
  <![CDATA[ 
    insert into users(
      username,
      loginid,
      loginpassword,
      roleid )
    values(
      #username#,#loginid#,#loginpassword#,#roleid#
    )
    ]]>
  </insert>

  
  <update id="updateUsers" parameterClass="user">
  <![CDATA[ 
    update users set
      username=#username#,
      loginid=#loginid#,
      loginpassword=#loginpassword#,
      roleid=#roleid#
    where
      loginId = #loginid#
      ]]>
  </update>

  
  <delete id="deleteUsersByLoginId" parameterClass="String">
    delete from users where loginId = #loginId#
  </delete>

</sqlMap>

 

IBaseDAO.java源码:

package com.ibatis.dao;

import java.io.Serializable;
import java.util.List;

public interface IBaseDAO {

 
 /**
  * 插入一个实体(在数据库INSERT一条记录)
  * @param <T>
  * @param sqlStr
  * @param entity
  */
    public abstract <T> T insert(String sqlStr,T entity);

 

   
    /**
     * 修改一个实体对象(UPDATE一条记录) 
     * @param <T>
     * @param sqlStr
     * @param entity
     * @return
     */
    public abstract <T> int update(String sqlStr,T entity); 

 

    /**
     * 根据指定的唯一列值,删除一行
     * @param <T>
     * @param sqlStr
     * @param primaryKey
     * @return
     */
    public abstract <T> int delete(String sqlStr,T primaryKey); 

 

    /**
     * 查询指定的sql语句的行数
     * @param sqlStr
     * @return
     */
   public abstract int count(String sqlStr); 

 

    /**
     * 按指定的唯一键,取一行
     * @param <T>
     * @param <PK>
     * @param sqlStr
     * @param primaryKey
     * @return
     */
    public abstract <T extends Object,PK> T getOne(String sqlStr,PK primaryKey); 

 

    /**
     *  取全部记录 
     * @param <T>
     * @param sqlStr
     * @return
     */
    public abstract <T> List<T> selectAll(String sqlStr); 

 

    /**
     * 批量添加
     * @param <T>
     * @param sqlStr
     * @param list
     */
    public abstract <T> void batchInsert(String sqlStr,final List<T> list); 

 

    /**
     * 批量修改 
     * @param <T>
     * @param sqlStrs
     * @param list
     */
    public abstract <T> void batchUpdate(String sqlStrs,final List<T> list); 

 

   /**
    * 批量删除 
    * @param <T>
    * @param sqlStr
    * @param list
    */
   public abstract <T> void batchDelete(String sqlStr,final List<T> list); 

 


 
}


BaseDAOImp.java源码:

package com.ibatis.dao;


import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.orm.ibatis.SqlMapClientCallback;

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

 


import com.ibatis.sqlmap.client.SqlMapExecutor;

 

 


public class BaseDAOImp extends SqlMapClientDaoSupport  implements IBaseDAO {

 

 public int count(String strSql)
 {
  Integer result=0;
  try {
   result=(Integer)getSqlMapClient().queryForObject(strSql);
   //return result;
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }   
  return result;
 }

 


 public <T> void batchDelete(final String sqlStr, final List<T> list) {
  // TODO Auto-generated method stub
  
        this.getSqlMapClientTemplate().execute( new SqlMapClientCallback() {         

            public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {             

                executor.startBatch();             

                for (T member : list) {                 

                    executor.delete(sqlStr, member);             

                }             

                executor.executeBatch();             

                return null;         

            }     

        });     
 }

 

 

 public <T> void batchInsert(final String sqlStr,final List<T> list) {
  // TODO Auto-generated method stub
  SqlMapClientCallback callback = new SqlMapClientCallback() {         

            public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {             

                executor.startBatch();             

                for (T member : list) {                 

                    executor.insert(sqlStr, member);             

                }             

                executor.executeBatch();             

                return null;         

            }     

        };     

        this.getSqlMapClientTemplate().execute(callback);      
 }

 

 

 public <T> void batchUpdate(final String sqlStr, final List<T> list) {
  // TODO Auto-generated method stub
   SqlMapClientCallback callback = new SqlMapClientCallback() {         

             public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {             

                 executor.startBatch();             

                 for (T member : list) {                 

                     executor.update(sqlStr, member);             

                 }             

                 executor.executeBatch();             

                 return null;         

             }     

         };     

         this.getSqlMapClientTemplate().execute(callback);     
 }

 

 

 

 


 public <T> int delete(String sqlStr, T primaryKey) {
  // TODO Auto-generated method stub
  
  
   int rows=-1;
  try {
   rows = getSqlMapClient().delete( 

      sqlStr, primaryKey);
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }  

     return rows;  
 }

 

 

 @SuppressWarnings("unchecked")
 public <T extends Object, PK> T getOne(String sqlStr, PK primaryKey) {
  // TODO Auto-generated method stub
  T reuslt=null;
  try {
   reuslt=(T) getSqlMapClient().queryForObject(sqlStr, primaryKey);
   
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return  reuslt;
 }

 

 

 public <T> T insert(String sqlStr, T entity) {
  // TODO Auto-generated method stub
  T result=null;
  try {
   result=(T) getSqlMapClient().insert(sqlStr, entity);
   
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return  result;
 }

 

 

 public <T> List<T> selectAll(String sqlStr) {
  // TODO Auto-generated method stub
  List<T> list=new ArrayList<T>();
  try {
   list=  getSqlMapClient().queryForList(sqlStr);
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return list;
 }

 

 

 public <T> int update(String sqlStr, T entity) {
  // TODO Auto-generated method stub
   int rows=-1;
  try {
   rows = getSqlMapClient().update( 

      sqlStr, entity);
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }  

         return rows;  
 } 

 

}

 

IBaseService.java是一个空接口,其他Service类都要继承此接口的实现类

package com.ibatis.service;

public interface IBaseService {

}


BaseServiceImpl.java实现IBaseService接口

package com.ibatis.service.impl;

import com.ibatis.dao.IBaseDAO;
import com.ibatis.service.IBaseService;

public class BaseServiceImpl implements IBaseService {

 protected IBaseDAO dao;

 public IBaseDAO getDao() {
  return dao;
 }

 public void setDao(IBaseDAO dao) {
  this.dao = dao;
 }
}

 

IUserService.java,业务类接口

package com.ibatis.service;

import java.util.List;

import com.ibatis.bean.Users;

public interface IUserService {

 
 
 /**
  * 添加一个用户
  * @param user
  */
 public abstract void addUser(Users user);
 
 /**
  * 更新一个用户(根据loginId字段)
  * @param user
  */
 public abstract void updateUser(Users user);
 
 /**
  * 根据账号,获取一个用户
  * @param loginId
  * @return
  */
 public abstract Users getOneUser(String loginId);
 
 /**
  * 根据一个登陆账号删除一个用户
  * @param loginId
  */
 public abstract void deleteUser(String loginId);
 
 /**
  * 根据loginid列表批量删除用户
  * @param loginIdList
  */
 public abstract void deleteBatchUser(List<String> loginIdList);
 
 /**
  *  批量添加用户
  * @param userList
  */
 public abstract void addBatchUsers(List<Users> userList);
 
 /**
  * 获取所有用户
  * @return
  */
 public abstract List<Users> getAllUsers();
}

 

UserServiceImpl.java实现IUserService定义的所有方法

package com.ibatis.service.impl;

import java.util.List;

import com.ibatis.bean.Users;
import com.ibatis.service.IUserService;

public class UserServiceImpl extends BaseServiceImpl implements IUserService {

 public void addBatchUsers(List<Users> userList) {
  // TODO Auto-generated method stub

  dao.batchInsert("user_space.insertUsers", userList);
 }

 public void addUser(Users user) {
  // TODO Auto-generated method stub

  dao.insert("user_space.insertUsers", user);
 }

 public void deleteUser(String loginId) {
  // TODO Auto-generated method stub

  
  dao.delete("user_space.deleteUsersByLoginId", loginId);
 }

 

 public List<Users> getAllUsers() {
  // TODO Auto-generated method stub
  return dao.selectAll("user_space.selectAllUsers");
 }

 public void deleteBatchUser(List<String> loginIdList) {
  // TODO Auto-generated method stub
  dao.batchDelete("user_space.deleteUsersByLoginId", loginIdList);
 }

 public void updateUser(Users user) {
  // TODO Auto-generated method stub
  dao.update("user_space.updateUsers", user);
 }

 public Users getOneUser(String loginId) {
  // TODO Auto-generated method stub
  return dao.getOne("user_space.selectUsersByLoginId", loginId);
 }

}

 

log4j.properties内容:

#--------------------------------    
#   stdout表示控制台,fileout表示输出到文件
log4j.rootLogger=error, stdout
#log4j.logger.test=info  
#log4j.logger.org.apache.jasper = DEBUG  
#log4j.logger.org.apache.catalina.startup.TldConfig = DEBUG  
#log4j.logger.org.apache.catalina.session.ManagerBase = DEBUG  
  
log4j.logger.com.fiscal = DEBUG  
log4j.logger.com.system = DEBUG  
  
log4j.logger.com.ibatis = DEBUG  
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource = DEBUG  
log4j.logger.com.ibatis.common.jdbc.ScriptRunner = DEBUG  
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate = DEBUG  
log4j.logger.java.sql.Connection = DEBUG  
#log4j.logger.java.sql.Statement = DEBUG  
#log4j.logger.java.sql.PreparedStatement = DEBUG  
log4j.logger.java.sql.ResultSet = DEBUG  
  
log4j.appender.stdout=org.apache.log4j.ConsoleAppender    
  
log4j.appender.fileout=org.apache.log4j.RollingFileAppender   
log4j.appender.fileout.File=C\:\\ibatis.log    
log4j.appender.fileout.MaxFileSize=10000KB    
  
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout    
log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH\:mm\:ss} \:%m%n   
log4j.appender.fileout.layout=org.apache.log4j.PatternLayout    
log4j.appender.fileout.layout.ConversionPattern=[%-5p]_%d{yyyy-MM-dd HH\:mm\:ss} \:%m%n  
  
#log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout    
  
# log4j.logger.org=info  
#--------------------------------

oscache.properties内容

#是否使用内存作为缓存空间 
cache.memory=true
 
#缓存管理事件监听器,通过这个监听器可以获知当前Cache的运行情况  
#cache.event.listeners=com.opensymphony.oscache.plugins.clustersupport.JavaGroupsBroadcastingListener

#如果使用磁盘缓存(cache.memory=false),则需要指定磁盘存储接口实现 
#cache.persistence.class=com.opensymphony.oscache.plugins.diskpersistence.DiskPersistenceListener
 
# 磁盘缓存所使用的文件存储路径 
# cache.path=c:\\myapp\\cache 
 
# 缓存调度算法,可选的有LRU,FIFO和无限缓存(UnlimitedCache)

# cache.algorithm=com.opensymphony.oscache.base.algorithm.FIFOCache 
# cache.algorithm=com.opensymphony.oscache.base.algorithm.UnlimitedCache 
cache.algorithm=com.opensymphony.oscache.base.algorithm.LRUCache
 
#内存缓存的最大容量 
cache.capacity=1000
 
# 是否限制磁盘缓存的容量 
# cache.unlimited.disk=false 
 
# 基于JMS的集群缓存同步配置 
#cache.cluster.jms.topic.factory=java:comp/env/jms/TopicConnectionFactory 
#cache.cluster.jms.topic.name=java:comp/env/jms/OSCacheTopic 
#cache.cluster.jms.node.name=node1

struts.properies内容:
struts.configuration.xml.reload=true
struts.i18n.encoding=utf-8
struts.objectFactory=spring
struts.devMode=true

 

struts.xml配置内容:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>

 
 <package name="userPackage" extends="struts-default" namespace="/sis">
 
 
  <action name="userAc" class="userAction">
   <result name="ShowUserList">/User/UserList.jsp</result>
   <result name="ShowOneUser">/User/AddOrEditUser.jsp</result>
   <!-- 指定添加或修改成功后,跳转到列表页面(要先经过Action重新加载一次) -->
   <result name="AddOrEdit" type="redirect">sis/userAc!userList.action</result>
  </action>
 </package>
</struts>

6.创建两个Jsp文件,一个列表文件(包含批量删除),一个对用户进行添加或更新

UserList.jsp,源码:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
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 'List.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">
 <style type="text/css">
        table {
            border: 1px solid black;
            border-collapse: collapse;
        }
        
        table thead tr th {
            border: 1px solid black;
            padding: 3px;
            background-color: #cccccc;
        }
        
        table tbody tr td {
            border: 1px solid black;
            padding: 3px;
        }
    </style>


  </head>
  
  <body>
      <h2>用户列表</h2>
       <form action="sis/userAc!deleteBectchUser.action" method="post">
   
        <table cellspacing="0">
            <thead>
                <tr>
                 <th></th>
                    <th>登陆账号</th>
                    <th>用户名</th>
                    <th>密码</th>
                    <th>角色</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <s:iterator value="userList" status="st">
                    <tr>
                        <td>
                        <input type="checkbox" name="deleteLoginIdList" value='<s:property value="loginid" />' />
                        <s:property value="#st.count"/>
                        </td>
                        <td><s:property value="loginid" /></td>
                        <td><s:property value="username" /></td>
                        <td><s:property value="loginpassword" /></td>
                        <td><s:property value="roleid" /></td>
                        <td>
                            <a href='<s:url action="sis/userAc!fowardUpdateUser.action"><s:param name="user.loginid" value="loginid" /></s:url>'>
                                编辑
                            </a>
                            &nbsp;
                            <a href='<s:url action="sis/userAc!deleteOneUser.action"><s:param name="user.loginid" value="loginid" /></s:url>'>
                                删除
                            </a>
                        </td>
                    </tr>
                </s:iterator>
                
                 <tr>
           <td colspan="3">
           <input type="submit" value="批量删除">
           
           </td>
           <td colspan="3">
           
           <a href="User/AddOrEditUser.jsp">添加一个用户</a>
           </td>
          </tr>
            </tbody>
            
            
        </table>
       
        
    </form>   

  </body>
</html>

 

AddOrEditUser.jsp,源码

 

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
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 'Edit.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>
    <h2>
    
        <s:if test="null == user">
            添加用户
             <form action="sis/userAc!addUser.action" method="post">
            
        </s:if>
        <s:else>
            编辑用户
            <form action="sis/userAc!updateUser.action" method="post">
        </s:else>
    </h2>
    
   
        <s:textfield name="user.loginid" label="登陆账号" />
        <br>
        <s:textfield name="user.username" label="用户名称" />
        <br>
        <s:textfield name="user.loginpassword" label="登陆密码" />
        <br>
        <s:textfield name="user.roleid" label="角色编号" />
        <br>
        <span style="float:left">
         <s:submit value="提交" />
        </span>
        
    </form>

  </body>
</html>

 

 7.在Tomcat下发布,输入地址:http://localhost:8989/Struts2IbatisSpring/sis/sis/userAc!userList.action

效果如下,可批量删除,单个删除,更新,添加

 

你可能感兴趣的:(struts2)