您的位置:首页 > 编程语言 > Java开发

Struts2.1.8+Spring2.5.6+ibatis开发框架整合

2010-07-19 00:17 519 查看
Step1:数据库设计

use ibatisstudy;
drop table if exists sbook;
create table if not exists sbook
(
id int primary key auto_increment,
title varchar(50),
author varchar(20),
total int,
price float,
isbn varchar(20),
publisher varchar(50)
);

Step2:搭建框架,创建web项目,导入jar包:

Struts2支持:
commons-collections.jar
commons-dbcp.jar
commons-logging-1.0.4.jar
commons-pool.jar
freemarker-2.3.8.jar
ognl-2.6.11.jar
struts2-core-2.0.11.2.jar
xwork-2.0.5.jar

Spring支持

spring.jar

aspectjweaver.jar

antlr-2.7.2.jar

Struts2和Spring整合:

struts2-spring-plugin-2.0.11.2.jar

ibatis支持
ibatis-2.3.4.726.jar

数据库驱动:
mysql-connector-java-5.1.7-bin.jar
(仅仅需要导入这些就足矣)
Step3:配置SSI2三部分各部分需要的配置文件:

1、Web.xml部分

<?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">
<!-- 配置Spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
WEB-INF/classes/com/us/jack/config/applicationContext.xml
WEB-INF/classes/com/us/jack/config/applicationContext-services.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- 配置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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

2、Struts2部分:

struts.properties部分:

struts.i18n.encoding=utf-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>
<include file="com/us/jack/action/sbookAction.xml"></include>
</struts>

sbookAction.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="sbook" extends="struts-default" namespace="/sbook">
<!-- 添加图书信息 -->
<action name="addSBook" class="sbookAction" method="addSBook">
<result name="success">/addBook.jsp</result>
<result name="error">/addBook.jsp</result>
</action>
<!-- 查看全部图书信息 -->
<action name="viewSBook" class="sbookAction" method="viewSBook">
<result name="success">/viewBook.jsp</result>
<result name="error">/viewBook.jsp</result>
</action>
<!-- 通过ID查找图书 -->
<action name="modifySBook" class="sbookAction" method="modifySBook">
<result name="success">/bookMsg.jsp</result>
<result name="error">/bookMsg.jsp</result>
</action>
<!-- 更新图书 -->
<action name="updateSBook" class="sbookAction" method="updateSBook">
<result name="success" type="redirect-action">viewSBook</result>
<result name="error">/bookMsg.jsp</result>
</action>
<!-- 删除图书 -->
<action name="removeSBook" class="sbookAction" method="removeSBook">
<result name="success" type="redirect-action">viewSBook</result>
<result name="error" type="redirect-action">viewSBook</result>
</action>
</package>
</struts>

3、Spring部分:

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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.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://127.0.0.1:3306/test" />
<property name="username" value="root" />
<property name="password" value="123456" />
</bean>

<!-- SqlMap setup for iBATIS Database Layer -->
<bean id="sqlMapClient"
class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="configLocation"
value="WEB-INF/classes/com/us/jack/config/sqlMapConfig.xml" />
<property name="dataSource" ref="dataSource" />
</bean>

<!-- 注入BookDAO层 -->
<bean id="sbookDAO" class="com.us.jack.dao.impl.SBookDAO">
<property name="sqlMapClient" ref="sqlMapClient" />
</bean>
</beans>

applicationContext-services.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/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="sbookServices" class="com.us.jack.services.impl.SBookServices">
<property name="sbookDAO" ref="sbookDAO"/>
</bean>
<!-- 将BookAction交给Spring控制 -->
<bean id="sbookAction" class="com.us.jack.action.SBookAction">
<property name="sbookServices" ref="sbookServices"/>
</bean>
<!-- Transaction manager for a single JDBC DataSource -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>

<aop:config>
<!-- 管理事务操作 -->
<aop:pointcut id="servicesPointcut"
expression="execution(* com.us.jack.services.*.*(..))" />
<aop:advisor advice-ref="txAdvice"
pointcut-ref="servicesPointcut" />
</aop:config>
<!-- 事务控制 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="get*" read-only="true" />
</tx:attributes>
</tx:advice>
</beans>

dataAccessContext.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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- SqlMap setup for iBATIS Database Layer -->
<bean id="sqlMapClient"
class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="configLocation"
value="com/us/jack/config/sqlMapConfig.xml" />
<property name="dataSource" ref="dataSource" />
</bean>

<!-- 注入BookDAO层 -->
<bean id="bookDAO" class="com.us.jack.dao.impl.BookDAO">
<property name="sqlMapClient" ref="sqlMapClient" />
</bean>
</beans>

4、IBatis部分:

sqlMapConfig.xml部分:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<sqlMap resource="com/us/jack/dao/impl/maps/SBook.xml"/>
</sqlMapConfig>

SBook.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>
<typeAlias alias="sbook" type="com.us.jack.pojo.SBook" />
<!-- 添加一本新书 -->
<insert id="saveBook" parameterClass="sbook">
<selectKey keyProperty="id" resultClass="int">
<![CDATA[
SELECT LAST_INSERT_ID() AS VALUE
]]>
</selectKey>
<![CDATA[
INSERT INTO sbook(title,author,total,price,isbn,publisher)
VALUES(#title#,#author#,#total#,#price#,#isbn#,#publisher#)
]]>
</insert>

<!-- 删除图书 -->
<delete id="deleteBook" parameterClass="int">
<![CDATA[
DELETE FROM SBOOK WHERE ID=#id#
]]>
</delete>

<!-- 通过出版社名称查找此出版社出版的图书 -->
<select id="findBookByPublisher" parameterClass="string"
resultClass="sbook">
<![CDATA[
SELECT * FROM sbook WHERE publisher=#publisher#
]]>
</select>
<!-- 通过图书唯一的ISBN号码查找图书 -->
<select id="findBookByISBN" parameterClass="string"
resultClass="sbook">
<![CDATA[
SELECT * FROM sbook WHERE isbn=#isbn#
]]>
</select>
<!-- 查找所有的图书 -->
<select id="findAllBook" resultClass="sbook">
<![CDATA[
SELECT * FROM sbook
]]>
</select>
<!-- 更新图书信息 -->
<update id="updateBook" parameterClass="sbook">
<![CDATA[
UPDATE SBOOK SET
title=#title#,author=#author#,price=#price#,total=#total#,isbn=#isbn#,publisher=#publisher#
WHERE id=#id#
]]>
</update>
<!-- 查找特定图书 -->
<select id="findBookById" parameterClass="int" resultClass="sbook">
<![CDATA[
SELECT * FROM sbook WHERE ID=#id#
]]>
</select>
</sqlMap>

Step4:后台代码部分:

1、pojo实体类部分:SBook.java

package com.us.jack.pojo;
/**
* 图书类
* @author jack
*
*/
public class SBook {
private int id;
private String title;
private String author;
private int total;
private float price;
private String isbn;
private String publisher;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getAuthor() {
return author;
}

public void setAuthor(String author) {
this.author = author;
}

public String getIsbn() {
return isbn;
}

public void setIsbn(String isbn) {
this.isbn = isbn;
}

public String getPublisher() {
return publisher;
}

public void setPublisher(String publisher) {
this.publisher = publisher;
}

public int getTotal() {
return total;
}

public void setTotal(int total) {
this.total = total;
}

public void setPrice(float price) {
this.price = price;
}

public float getPrice(){
return price;
}
}
2、DAO层:

ISBookDAO.java文件:

package com.us.jack.dao;

import java.util.List;

import com.us.jack.pojo.SBook;

public interface ISBookDAO {
/**
* 添加一本图书至数据库中
*
* @param book
* 图书对象
* @throws RuntimeException
*/
public void saveBook(SBook book) throws RuntimeException;

/**
* 删除图书信息
*
* @param id
* ID编码
* @throws RuntimeException
*/
public void deleteBook(int id) throws RuntimeException;

/**
* 通过出版社查找此出版社出版的所有图书列表
*
* @param publisher
* 出版社名称
* @return 返回特定出版社下的所有图书列表
* @throws RuntimeException
*/
public List<SBook> findBooksByPublisher(String publisher)
throws RuntimeException;

/**
* 通过图书对应的唯一的ISBN号查找图书
*
* @param isbn
* 图书唯一的ISBN号码
* @return 返回此ISBN号对应的图书
* @throws RuntimeException
*/
public SBook findBookByISBN(String isbn) throws RuntimeException;

/**
* 更新一本图书的信息
*
* @param book
* 图书对象
* @throws RuntimeException
*/
public void updateBook(SBook book) throws RuntimeException;

/**
* 查找库中所有的图书
*
* @return 返回图书列表
* @throws RuntimeException
*/
public List findAllBook() throws RuntimeException;

/**
* 通过ID查找特定的图书
*
* @param id
* 图书的ID号
* @return 返回此ID对应的图书信息
* @throws RuntimeException
*/
public SBook findBookById(int id) throws RuntimeException;
}
SBookDAO.java文件:

package com.us.jack.dao.impl;

import java.util.List;

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

import com.us.jack.dao.ISBookDAO;
import com.us.jack.pojo.SBook;

public class SBookDAO extends SqlMapClientDaoSupport implements ISBookDAO {
public SBook findBookByISBN(String isbn) throws RuntimeException {
return (SBook) this.getSqlMapClientTemplate().queryForObject(
"findBookByISBN", isbn);
}

@SuppressWarnings("unchecked")
public List<SBook> findBooksByPublisher(String publisher)
throws RuntimeException {
return this.getSqlMapClientTemplate().queryForList(
"findBookByPublisher", publisher);
}

public void saveBook(SBook book) throws RuntimeException {
this.getSqlMapClientTemplate().insert("saveBook", book);
}

public void deleteBook(int id) throws RuntimeException {
this.getSqlMapClientTemplate().delete("deleteBook", id);
}

public void updateBook(SBook book) throws RuntimeException {
this.getSqlMapClientTemplate().update("updateBook", book);
}

@SuppressWarnings("unchecked")
public List findAllBook() throws RuntimeException {
return this.getSqlMapClientTemplate().queryForList("findAllBook");
}

public SBook findBookById(int id) throws RuntimeException {
return (SBook) this.getSqlMapClientTemplate().queryForObject(
"findBookById", id);
}
}
3、业务逻辑层部分

ISBookServices.java文件:

package com.us.jack.services;

import java.util.List;

import com.us.jack.pojo.SBook;

public interface ISBookServices {
/**
* 添加一本图书至数据库中
*
* @param book
* 图书对象
* @throws RuntimeException
*/
public void saveBook(SBook book) throws RuntimeException;

/**
* 删除图书信息
*
* @param id
* ID编码
* @throws RuntimeException
*/
public void removeBook(int id) throws RuntimeException;

/**
* 通过出版社查找此出版社出版的所有图书列表
*
* @param publisher
* 出版社名称
* @return 返回特定出版社下的所有图书列表
* @throws RuntimeException
*/
public List<SBook> getBooksByPublisher(String publisher)
throws RuntimeException;

/**
* 通过图书对应的唯一的ISBN号查找图书
*
* @param isbn
* 图书唯一的ISBN号码
* @return 返回此ISBN号对应的图书
* @throws RuntimeException
*/
public SBook getBookByISBN(String isbn) throws RuntimeException;

/**
* 更新一本图书的信息
*
* @param book
* 图书对象
* @throws RuntimeException
*/
public void updateBook(SBook book) throws RuntimeException;

/**
* 查找库中所有的图书
*
* @return 返回图书列表
* @throws RuntimeException
*/
public List getAllBook() throws RuntimeException;

/**
* 通过图书ID号得到图书对象
*
* @param id
* 图书ID号码
* @return 返回此ID对应的图书信息
* @throws RuntimeException
*/
public SBook getBookById(int id) throws RuntimeException;
}
SBookServices.java文件:

package com.us.jack.services.impl;

import java.util.List;

import com.us.jack.dao.ISBookDAO;
import com.us.jack.pojo.SBook;
import com.us.jack.services.ISBookServices;

public class SBookServices implements ISBookServices {
private ISBookDAO sbookDAO;

@SuppressWarnings("unchecked")
public List getAllBook() throws RuntimeException {
return sbookDAO.findAllBook();
}

public SBook getBookByISBN(String isbn) throws RuntimeException {
return sbookDAO.findBookByISBN(isbn);
}

public List<SBook> getBooksByPublisher(String publisher)
throws RuntimeException {
return sbookDAO.findBooksByPublisher(publisher);
}

public void removeBook(int id) throws RuntimeException {
sbookDAO.deleteBook(id);
}

public void saveBook(SBook book) throws RuntimeException {
sbookDAO.saveBook(book);
}

public void updateBook(SBook book) throws RuntimeException {
sbookDAO.updateBook(book);
}

public SBook getBookById(int id) throws RuntimeException {
return sbookDAO.findBookById(id);
}

public void setSbookDAO(ISBookDAO sbookDAO) {
this.sbookDAO = sbookDAO;
}

}
4、控制层

SBookAction.JAVA文件:

package com.us.jack.action;

import java.util.List;

import com.us.jack.pojo.SBook;
import com.us.jack.services.ISBookServices;

public class SBookAction {
private ISBookServices sbookServices;
private SBook sbook;
private String tips;
private String bookId;
@SuppressWarnings("unchecked")
private List bookList;

/**
* 添加图书信息
*
* @return 返回添加是否成功
*/
public String addSBook() {
String result = "error";
try {
sbookServices.saveBook(sbook);
this.setTips("添加成功");
result = "success";
} catch (Exception e) {
e.printStackTrace();
this.setTips("系统出现问题");
}
return result;
}

/**
* 查看所有图书
*
* @return
*/
public String viewSBook() {
String result = "error";
try {
bookList = sbookServices.getAllBook();
result = "success";
} catch (Exception e) {
e.printStackTrace();
this.setTips("系统出现问题,请稍后访问");
}
return result;
}

/**
* 修改图书信息
*
* @return
*/
public String modifySBook() {
String result = "error";
try {
sbook = sbookServices.getBookById(Integer.parseInt(this.getBookId()));
result = "success";
} catch (Exception e) {
e.printStackTrace();
this.setTips("系统出现问题");
}
return result;
}

public String updateSBook(){
String result = "error";
try{
sbookServices.updateBook(sbook);
result = "success";
}catch(Exception e){
e.printStackTrace();
this.setTips("更新操作失败");
}
return result;
}

/**
* 删除图书
* @return
*/
public String removeSBook(){
String result = "error";
try{
sbookServices.removeBook(Integer.parseInt(this.getBookId()));
result = "success";
}catch(Exception e){
e.printStackTrace();
this.setTips("删除操作失败");
}
return result;
}

public SBook getSbook() {
return sbook;
}

public void setSbook(SBook sbook) {
this.sbook = sbook;
}

public void setSbookServices(ISBookServices sbookServices) {
this.sbookServices = sbookServices;
}

@SuppressWarnings("unchecked")
public List getBookList() {
return bookList;
}

@SuppressWarnings("unchecked")
public void setBookList(List bookList) {
this.bookList = bookList;
}

public String getTips() {
return tips;
}

public void setTips(String tips) {
this.tips = tips;
}

public String getBookId() {
return bookId;
}

public void setBookId(String bookId) {
this.bookId = bookId;
}
}
Step5:前台页面的开发:

1、增加页面文件addBook.jsp

<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>添加图书</title>
</head>

<body>
<s:property value="tips"/>
<s:form action="/sbook/addSBook.action" >
<s:textfield name="sbook.title" label="书名"/>
<s:textfield name="sbook.author" label="作者"/>
<s:textfield name="sbook.price" label="价格"/>
<s:textfield name="sbook.total" label="数量"/>
<s:textfield name="sbook.isbn" label="ISBN号"/>
<s:textfield name="sbook.publisher" label="出版社"/>
<s:submit value="添加"/>
</s:form>
<a href="<%=request.getContextPath() %>/sbook/viewSBook.action">查看现有图书</a>
</body>
</html>
2、修改页面文件bookMsg.jsp

<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>修改图书信息</title>
</head>

<body>
<s:form action="/sbook/updateSBook.action">
<s:hidden name="sbook.id">${id}</s:hidden>
<s:textfield name="sbook.title" label="书名" readonly="true">${title}</s:textfield>
<s:textfield name="sbook.author" label="作者">${author}</s:textfield>
<s:textfield name="sbook.price" label="价格">${price}</s:textfield>
<s:textfield name="sbook.total" label="总量">${total}</s:textfield>
<s:textfield name="sbook.isbn" label="ISBN">${isbn}</s:textfield>
<s:textfield name="sbook.publisher" label="出版社">${publisher}</s:textfield>
<s:submit/>
</s:form>
<s:property value="tips" />
</body>
</html>
3、登录页面文件index.jsp

<%@ page language="java" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>图书管理页面</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">
</head>
<body>
<a href="addBook.jsp">添加图书</a>
<a href="sbook/viewSBook.action">浏览图书</a>
</body>
</html>
4、登录页面文件viewBook.jsp

<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>浏览图书</title>
</head>

<body>
<table align="center" border="1" style="width:80%;">
<tr>
<th colspan="7" align="center">库存图书</th>
</tr>
<tr>
<td align="left" colspan="7"><a href="<%=request.getContextPath()%>/addBook.jsp">添加新书</a></td>
</tr>
<tr>
<td>书名</td>
<td>作者</td>
<td>价格</td>
<td>库存量</td>
<td>ISBN号</td>
<td>出版社</td>
<td>操作</td>
</tr>
<s:iterator value="bookList">
<tr>
<td>
<s:property value="title"/>
</td>
<td>
<s:property value="author"/>
</td>
<td>
<s:property value="price"/>
</td>
<td>
<s:property value="total"/>
</td>
<td>
<s:property value="isbn"/>
</td>
<td>
<s:property value="publisher"/>
</td>
<td>
<a href="<%=request.getContextPath()%>/sbook/modifySBook.action?bookId=${id}">修改信息</a>
<a href="<%=request.getContextPath()%>/sbook/removeSBook.action?bookId=${id}">删除</a>
</td>
</tr>
</s:iterator>
<s:property value="tips"/>
</table>
</body>
</html>

到此为止用Struts2.1.8+Spring2.5.6+ibatis整合开发框架来实现一个图书管理模块的增删查改功能已经完整地实现了......
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: