`
阳光小菜鸟
  • 浏览: 96846 次
  • 性别: Icon_minigender_2
  • 来自: 郑州
社区版块
存档分类
最新评论

myeclipse6.0下struts2.0+spring2.0+ibatis整合示例

    博客分类:
  • SSI
阅读更多
参考网上的例子,自己做了个简单的struts2.0+ibatis+spring2.0登陆的例子。
链接:http://blog.csdn.net/jinlong0/archive/2008/01/11/2034732.aspx
1. 新建web工程
[img] http://shiningwu.iteye.com/upload/picture/pic/12457/86475e67-51e5-3fba-998c-4e1178dfd578.bmp [/img]
点击“finish”。
2. 加入jar包
将下面的jar包加入WEB-INF/lib下
antlr-2.7.2.jar
aopalliance.jar
cglib-2.1.3.jar
commons-collections.jar
commons-dbcp.jar
commons-logging-1.0.4.jar
commons-pool.jar
freemarker-2.3.8.jar
ibatis-2.3.1.710.jar
mysql-connector-java-5.0.4-bin.jar
ognl-2.6.11.jar
oro-2.0.8.jar
spring.jar
struts2-core-2.0.11.1.jar
struts2-spring-plugin-2.0.11.1.jar
xwork-2.0.4.jar
3. 配置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">
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
  <context-param>  
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/classes/applicationContext.xml</param-value> 
	</context-param> 
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <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>
</web-app>

4. 创建类与类包
结构如下图
[img]http://shiningwu.iteye.com/upload/picture/pic/12455/3668ca76-3bd8-3253-aec6-5d69df169dc8.bmp [/img]
5. 映射数据库表Users.java
package org.login.vo;

public class Users {
	private Integer id;
    private String userName;
    private String password;
        
    public Integer getId() {
        return id;
    }

    public void setId(Integer 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;
    }

    public Users() {
        
    }

    public Users(Integer id, String userName, String password) {
        super();
        this.id = id;
        this.userName = userName;
        this.password = password;
    }

}

6. 映射xml(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">
    <typeAlias alias="user" type="org.login.vo.Users"/>
    
    <select id="recordCount" resultClass="int">
		select count(*) as count from users
	</select>
	<select id="firstPage" resultClass="user" parameterClass="user">
		select top $pagesize$ * from users order by id desc
	</select>

	<!--分页排序-->
	<sql id="paginationStart">
		<![CDATA[
		   select * from (select row_.*, rownum rownum_ from (
		  ]]>
	</sql>
	<sql id="paginationEnd">
		<![CDATA[
		   )row_ where rownum<=#end# ) where rownum_>=#start#
		  ]]>
	</sql>

	<select id="otherPage" resultClass="user" parameterClass="map">
        <include refid="paginationStart"/>
        <![CDATA[
            SELECT 
             * 
            FROM 
             users
        ]]>
        <include refid="paginationEnd"/> 
	</select>
	
    <select id="checkUser" parameterClass="user" resultClass="user">
        <![CDATA[
            SELECT id, username, password FROM users WHERE username = #userName# and password = #password#
        ]]>
    </select>
    
    <select id="getUserById" parameterClass="java.lang.Integer" resultClass="user">
        <![CDATA[
            SELECT id, username, password FROM users WHERE id = #id#
        ]]>
    </select>
    
    <select id="getAllUser" resultClass="user" parameterClass="map">
        <![CDATA[
            SELECT id, username, password FROM users limit #start# ,#end#
        ]]>
    </select>
    
    <insert id="insertUser" parameterClass="user">
        <![CDATA[
            INSERT INTO users (username, password) VALUES (#userName#, #password#)
        ]]>
    </insert>
    
    <update id="updateUser" parameterClass="user">
        <![CDATA[
            UPDATE users SET username=#userName#, password=#password# WHERE id=#id#
        ]]>
    </update>
    
    <delete id="deleteUser" parameterClass="java.lang.Integer">
        <![CDATA[
            DELETE FROM users WHERE id = #id#
        ]]>
    </delete>
</sqlMap>

7. 接口及实现
接口IUserDAO.java
package org.login.dao;

import java.util.List;
import org.login.vo.Users;

public interface IUserDAO {
    List<Users> getAllUser();   
    Users getUserById(Integer id);   
    boolean isLogin(Users user);
    boolean insertUser(Users user);
    boolean updateUser(Users user);  
    boolean deleteUser(Integer id);
}

实现UserDAO
package org.login.dao.Impl;

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

import org.login.dao.IUserDAO;
import org.login.vo.Users;
import com.ibatis.sqlmap.client.SqlMapClient;


public class UserDAO implements IUserDAO {

    private SqlMapClient client = null;

    public SqlMapClient getClient() {
        return client;
    }

    public void setClient(SqlMapClient client) {
        this.client = client;
    }

    
    public boolean deleteUser(Integer id) {
        try {
            client.delete("deleteUser", id);
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

  
    public List<Users> getAllUser() {
        List<Users> list = null;
        try {
            list =  client.queryForList("getAllUser");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

   
    public boolean insertUser(Users user) {
        try {
            client.insert("insertUser", user);
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

  
    public boolean updateUser(Users user) {
        try {
            client.update("updateUser", user);
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

  
    public boolean isLogin(Users user) {
        try {
            Users u = (Users) client.queryForObject("checkUser", user);
            if (u != null) {
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

  
    public Users getUserById(Integer id) {
        Users u = null;
        try {
            u = (Users) client.queryForObject("getUserById", id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return u;
    }

}

服务层接口IUserService.java
package org.login.service;

import java.util.List;

import org.login.vo.Users;

public interface IUserService {
    
    List<Users> getAllUser();
    
    Users getUserById(Integer id);
    
    boolean isLogin(Users user);
    
    boolean insertUser(Users user);
    
    boolean updateUser(Users user);
    
    boolean deleteUser(Integer id);
}

服务层实现UserService.java
package org.login.service.Impl;

import java.util.List;

import org.login.dao.IUserDAO;
import org.login.service.IUserService;
import org.login.vo.Users;



public class UserService implements IUserService {

    private IUserDAO userDAO = null;
    
    public IUserDAO getUserDAO() {
        return userDAO;
    }

    public void setUserDAO(IUserDAO userDAO) {
        this.userDAO = userDAO;
    }

    
    public boolean deleteUser(Integer id) {
        
        return userDAO.deleteUser(id);
    }

  
    public List<Users> getAllUser() {
        
        return userDAO.getAllUser();
    }

  
    public boolean insertUser(Users user) {
        
        return userDAO.insertUser(user);
    }

   
    public boolean isLogin(Users user) {
        
        return userDAO.isLogin(user);
    }

  
    public boolean updateUser(Users user) {
        
        return userDAO.updateUser(user);
    }

   
    public Users getUserById(Integer id) {
        
        return userDAO.getUserById(id);
    }

}

Struts中Action实现Login.java
package org.login.actions;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.xml.registry.infomodel.User;

import org.login.page.PageUtil;
import org.login.service.IUserService;
import org.login.vo.Users;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

public class Login extends ActionSupport implements ModelDriven<Users>, Preparable {
    private IUserService userService ; 
    private String id ;
    private int pageIndex=1 ;
	private String pageBar ;
	private List<Users> list;
	private Users user;
    
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
    
    public IUserService getUserService() {
        return userService;
    }

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

	public int getPageIndex() {
		return pageIndex;
	}

	public void setPageIndex(int pageIndex) {
		this.pageIndex = pageIndex;
	}
	

	public String getPageBar() {
		return pageBar;
	}

	public void setPageBar(String pageBar) {
		this.pageBar = pageBar;
	}
	

	public List<Users> getList() {
		return list;
	}

	public void setList(List<Users> list) {
		this.list = list;
	}
	
	public Users getUser() {
		return user;
	}

	public void setUser(Users user) {
		this.user = user;
	}
    
	public void prepare() throws Exception {
		if (id == null || id.length() == 0)
			user = new Users();
		else
			user = getUserService().getUserById(Integer.parseInt(id));
	}
	
    public String execute() throws Exception {
        if (getUserService().isLogin(user)) {
            return SUCCESS;
        }
        return INPUT;
    }
    
    public String save() throws Exception {
        if (getUserService().insertUser(user)) {
            return SUCCESS;
        }
        return ERROR;
    }

    public String edit() {
		return SUCCESS;
	}
    
    public String update() throws Exception {    
        if (getUserService().updateUser(user)) {
                return SUCCESS;
        }    
        return ERROR;
    }
    
    public String delete() throws Exception {
        if (getUserService().deleteUser(Integer.valueOf(id))) {
            return SUCCESS;
        }
        return ERROR;
    }
    
    
    public String findAllUsers() throws Exception {
    	PageUtil page = new PageUtil();	
		int count = getUserService().getCount();
		page.setCurPage(pageIndex);
		page.setTotalRow(count);
		pageBar = page.getToolsMenu();
		Map<String,Integer> pageMap = new HashMap<String,Integer>();
		pageMap.put("start", page.getStart());
		pageMap.put("end", page.getPageSize());
        list = getUserService().getAllUser(pageMap); 
        return SUCCESS;
    }
    
    public Users getModel() {
		return user;
	}



}

8. 配置文件
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>
    <constant name="struts.objectFactory.spring.autoWire" value="type" />
	<constant name="struts.objectFactory" value="spring" />
    <include file="struts-default.xml"/>
    <package name="struts2" extends="struts-default">
    <default-interceptor-ref name="paramsPrepareParamsStack" />
        <!-- aciton的class为applicationContext.xml中的注册名 -->
        <action name="login" class="LoginAction">
            <result name="success">/success.jsp</result>
            <result name="input">/login.jsp</result>
        </action>
        <action name="save" class="LoginAction" method="save">
            <result name="success" type="redirect-action">show.action</result>
            <result name="error">/error.jsp</result>
        </action>
        <action name="edit" class="LoginAction" method="edit">
			<result name="success">update.jsp</result>
		</action>
        <action name="update" class="LoginAction" method="update">
            <result name="success" type="redirect-action">show.action</result>
            <result name="error">/error.jsp</result>
        </action>
        <action name="delete" class="LoginAction" method="delete">
            <result name="success" type="redirect-action">show.action</result>
            <result name="error">/error.jsp</result>
        </action>
        <action name="show" class="LoginAction" method="findAllUsers">
            <result name="success">/list.jsp</result>
            <result name="error">/error.jsp</result>
        </action>
    </package>
</struts>

struts.properties文件
struts.locale=zh_CN
struts.i18n.encoding=UTF-8  
struts.objectFactory=spring  

ibatis的配置文件config.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>
    <sqlMap resource="org/login/vo/users.xml"/>
</sqlMapConfig>

Spring配置文件applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans default-autowire="byType"
	xmlns="http://www.springframework.org/schema/beans"
	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-2.0.xsd">
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://192.168.151.238:3306/chgl" />
        <property name="username" value="vcom" />
        <property name="password" value="vcom_8968888" />
    </bean>
    
    <bean id="client" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
        <property name="dataSource">
            <ref local="dataSource"/>
        </property>
        <property name="configLocation">
            <value>classpath:config.xml</value>
        </property>
    </bean>
    
    <!-- bean中的class为实现接口的类;property的name为类中引用的属性名称;ref为spring注册的名称,如上面的client-->
    <bean id="userDao"
		class="org.login.dao.Impl.UserDAO">
		<property name="client" ref="client" />
	</bean>

	<bean id="userService"
		class="org.login.service.Impl.UserService">
		<property name="userDAO" ref="userDao"></property>
	</bean>

	<bean id="LoginAction" class="org.login.actions.Login">
		<property name="userService" ref="userService"></property>
	</bean>
</beans>

9. UI层
登陆页面login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>login.jsp</title>
  </head>
  
  <body>
    <s:form action="login" method="post">
    <s:textfield name="userName" label="User Name" />
    <s:password name="password" label="Password" />
    <s:submit value="Submit" />
    </s:form>
  </body>
</html>

添加用户页面adduser.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>addUser.jsp</title>
  </head>
  
  <body>
    <s:form action="save">
    <s:textfield name="userName" label="User Name" />
    <s:password name="password" label="Password" />
    <s:submit value="Save" />
    </s:form>
  </body>
</html>

用户列表页面list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Users list</title>
    <style type="text/css">
        table {
            border-collapse: collapse;
        }
    </style>
  </head>
  
  <body>
      <br /><br /><br /><br />
    <s:form action="show">
    <table border="1" width="50%" align="center">
        <tr bgcolor="#cccc00">
            <td align="center">UserID</td>
            <td align="center">UserName</td>
            <td align="center">Password</td>
            <td colspan="2" align="center">Options</td>
        </tr>
        <s:iterator value="list" id="user" status="st">
        <tr <s:if test="#st.odd">style="background-color:#dddddd"</s:if>
			<s:else>style="background-color:#eeeeee"</s:else>>
            <td align="center"><s:property value="id" /></td>
            <td align="center">&nbsp;<s:property value="userName" /></td>
            <td align="center">&nbsp;<s:property value="password" /></td>
            <td align="center">
            <s:url id="update" action="edit">
			   <s:param name="id">
			   <s:property value="id" /> 
			   </s:param>
			</s:url> 
			<s:a href="%{update}">update</s:a>
			</td>
			
            <td align="center">
            <s:url id="delete" action="delete">
			   <s:param name="id">
			   <s:property value="id" />
			   </s:param>
			</s:url> 
			<s:a href="%{delete}">delete</s:a>
			</td>
        </tr>
        </s:iterator>
        <tr>
				<td colspan="4"> 
					<s:property value="#request.pageBar" escape="false"/>
				</td>
		</tr>
    </table>
    </s:form>
  </body>
</html>

用户更新页面update.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>update.jsp</title>
  </head>
  
  <body>
    <s:form action="update" method="post">
        <s:textfield name="id" label="ID" value="%{id}"  readonly="true"/>
        <s:textfield name="userName" label="User Name" value="%{userName}"  required="true"/>
        <s:textfield name="password" label="Password" value="%{password}"  required="true"/>
        <s:submit value="Update" />
    </s:form>
  </body>
</html>

成功页面success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>success</title>
  </head>
  
  <body>
    This is Success page. <br>
    <br /><br />
    <a href="show.action">显示用户列表</a>  <a href="adduser.jsp">添加用户</a>
  </body>
</html>

失败页面error.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
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 'error.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>
    This is my JSP page. <br>
  </body>
</html>

分享到:
评论
6 楼 qinglong3222664 2013-04-18  
SENSEN1234 写道
pageUtil类呢?急用!!

5 楼 gejiushihuai 2012-07-19  
怎么没有com.ibatis.sqlmap.client.SqlMapClient; 呢?
4 楼 SENSEN1234 2012-04-06  
pageUtil类呢?急用!!
3 楼 Lori_Liu 2012-04-06  
很详细,收益很大...
2 楼 netbuddy 2010-09-01  
pageUtil类呢?
1 楼 wpfwupengfeiwpf 2010-08-24  
写得挺好的,呵呵,不足之处代码没有打包

相关推荐

Global site tag (gtag.js) - Google Analytics