JavaEE---------SSH使用实例
今天讲的是整合SSH框架,用一个图书信息小系统来实现,快速帮你构建网站后台
首先我们应该把相应的Struts 2,Hibernate,Spring导入到你的工程中去,下面给出我用的库集合
把库添加到Build path中去,
先改web.xml,它是整个web应用的核心,不要说不知道在哪里,指明使用Struts2 拦截请求,Spring监听
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" 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_3_0.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <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> <!-- 指明spring配置文件在何处 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 加载spring配置文件applicationContext.xml --> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> </web-app>
在src目录下创建applicationContext.xml,在连接数据库的时候不要再创建hibernate.cfg.xml,直接用Spring提供的连接方法就好,要不然可能出错(本人经验)
<?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="myDataSource" /> </property> <property name="mappingResources"> <list> <value>com/bq/Book.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> <bean id="myDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"> </property> <property name="url" value="jdbc:mysql://127.0.0.1:3306/booksale?useUnicode=true&characterEncoding=UTF-8"> </property> <property name="username" value="root"></property> <property name="password" value=""></property> </bean> <bean id="userDao" class="com.bq.DAOImplement"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <bean id="service" class="com.bq.BookService"> <property name="bookDao"> <ref bean="userDao" /> </property> </bean> <bean id="query" class="com.bq.QueryBook"> <property name="service"> <ref bean="service" /> </property> </bean> </beans>
创建Struts 2核心配置文件,不要喷我,我喜欢一个个类那样写,你也可以在一个类中指定不同的方法来处理不同的请求
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <constant name="struts.i18n.encoding" value="GB2312" /> <package name="default" namespace="/" extends="struts-default"> <action name="query" class="com.bq.QueryBook"> <result name="success">/show.jsp</result> <result name="input">/index.jsp</result> </action> <action name="getBook" class="com.bq.GetBook"> <result name="success">/book.jsp</result> <result name="input">/index.jsp</result> </action> <action name="changeBook" class="com.bq.ChangeBook"> <result name="success" type="redirectAction">query</result> <result name="input">/book.jsp</result> </action> <action name="delBook" class="com.bq.DelBook"> <result name="success" type="redirectAction">query</result> <result name="input">/show.jsp</result> </action> <action name="addBook" class="com.bq.AddBook"> <result name="success" type="redirectAction">query</result> <result name="input">/show.jsp</result> </action> </package> </struts>
整体框架就有了,下来就是各个类了
先看实体类及其Hibernate映射文件
Book.java
package com.bq; /** * @author 白强 * */ public class Book { private int id; private String name; private String detail; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } @Override public String toString() { return "Book [id=" + id + ", name=" + name + ", detail=" + detail + "]"; } }
Book.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.bq"> <class name="com.bq.Book" table="book"> <id name="id"> <generator class="increment"/> </id> <property name="name"/> <property name="detail"/> </class> </hibernate-mapping>
然后是写DAO层
接口BookDAO.java
package com.bq; import java.util.List; public interface BookDAO { List getAll();//获得所有记录 List getBook(int pageSize, int startRow);//获得所有记录 List queryBook(String fieldname,String value);//根据条件查询 Book getBook(int id);//根据ID获得记录 void addBook(Book book);//添加记录 void updateBook(Book book);//修改记录 void deleteBook(Book book);//删除记录 }
DAO实现类
DAOImplement.java,里面用到
this.getHibernateTemplate()的方法来自Spring
可以利用它来完成数据库操作
package com.bq; import java.util.List; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; /** * @author 白强 * */ public class DAOImplement extends HibernateDaoSupport implements BookDAO{ public DAOImplement() { } @Override public List getAll() { String sql="from Book"; return this.getHibernateTemplate().find(sql); } @Override public List getBook(int pageSize, int startRow) { return null; } @Override public List queryBook(String fieldname, String value) { System.out.println("value: "+value); String sql="FROM Book where "+fieldname+" like '%"+value+"%'"; return this.getHibernateTemplate().find(sql); } @Override public Book getBook(int id) { return (Book)this.getHibernateTemplate().get(Book.class,id); } @Override public void addBook(Book book) { this.getHibernateTemplate().save(book); } @Override public void updateBook(Book book) { this.getHibernateTemplate().update(book); } @Override public void deleteBook(Book book) { this.getHibernateTemplate().delete(book); } }
写Service层
BookService.java
package com.bq; import java.util.List; /** * @author 白强 * */ public class BookService { private BookDAO bookDao; public BookDAO getBookDao() { return bookDao; } public void setBookDao(BookDAO bookDao) { this.bookDao = bookDao; } /** * 函数说明:获得一条的信息 参数说明: ID 返回值:对象 */ public Book getBook(int bookId) { return bookDao.getBook(bookId); } /** * 函数说明:修改信息 参数说明: 对象 返回值: */ public void updateBook(Book book) { bookDao.updateBook(book); } /** * 函数说明:查询信息 参数说明: 集合 返回值: */ public List queryBook(String fieldname, String value) { return bookDao.queryBook(fieldname, value); } public List queryBook() { return bookDao.getAll(); } public void addBook(Book book) { bookDao.addBook(book); } public void delBook(Book book) { bookDao.deleteBook(book); } }
这个时候我们的Service就写好了,然后再在控制Action中调用Service的方法就可以了
QueryBook.java 查询得到List
package com.bq; import java.util.List; import com.opensymphony.xwork2.ActionSupport; /** * @author 白强 * */ public class QueryBook extends ActionSupport { private Book book; private BookService service; private List<Book> list; public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } public BookService getService() { return service; } public void setService(BookService service) { this.service = service; } public List<Book> getList() { return list; } public void setList(List<Book> list) { this.list = list; } @Override public String execute() throws Exception { if(service.queryBook()!=null){ list=service.queryBook(); return SUCCESS; } else{ return INPUT; } } }
添加Book
AddBook.java
package com.bq; import com.opensymphony.xwork2.ActionSupport; /** * @author 白强 * */ public class AddBook extends ActionSupport{ private Book book; private BookService service; public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } public BookService getService() { return service; } public void setService(BookService service) { this.service = service; } @Override public String execute() throws Exception { System.out.println(book.toString()); service.addBook(book); return SUCCESS; } }
根据id得到Book
GetBook.java
package com.bq; import com.opensymphony.xwork2.ActionSupport; public class GetBook extends ActionSupport { private int id; private Book book; private BookService service; public int getId() { return id; } public void setId(int id) { this.id = id; } public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } public BookService getService() { return service; } public void setService(BookService service) { this.service = service; } @Override public String execute() throws Exception { if(service.getBook(getId())!=null){ book=service.getBook(getId()); //service.updateBook(b); return SUCCESS; } else{ return INPUT; } } }
根据id更新Book
ChangeBook.java
package com.bq; import com.opensymphony.xwork2.ActionSupport; /** * @author 白强 * */ public class ChangeBook extends ActionSupport{ private Book book; private BookService service; public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } public BookService getService() { return service; } public void setService(BookService service) { this.service = service; } @Override public String execute() throws Exception { System.out.println(book.toString()); if(service.getBook(book.getId())!=null){ Book b=service.getBook(book.getId()); service.updateBook(book); return SUCCESS; } else{ return INPUT; } } }
根据id删除Book
DelBook.java
package com.bq; import com.opensymphony.xwork2.ActionSupport; /** * @author 白强 * */ public class DelBook extends ActionSupport { private int id; private Book book; private BookService service; public int getId() { return id; } public void setId(int id) { this.id = id; } public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } public BookService getService() { return service; } public void setService(BookService service) { this.service = service; } @Override public String execute() throws Exception { if(service.getBook(getId())!=null){ service.delBook(service.getBook(getId())); return SUCCESS; } else{ return INPUT; } } }
实现数据库的基本操作 增删改查 即可
最后附上所有的jsp文件
index.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>欢迎</title> </head> <body> <h1 align="center"> 欢迎来到SSH整合测试页面</h1> <br> <div align="center"> <a href="query">点击进入</a> <a href="add.jsp">增加书</a> </div> </body> </html>
add.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> <%@ 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%>"> <META name="viewport" content="width=device-width, initial-scale=1"> <TITLE>添加</TITLE> <BODY> <DIV data-role="header" data-position="inline"> <H1>增加书</H1></DIV> <DIV data-role="content"> <FORM action="addBook" method="POST"> <s:hidden name="book.id" ></s:hidden> <label>书名:</label> <input name="book.name" class="ui-input-text ui-body-null ui-corner-all ui-shadow-inset ui-body-c" /> <br> <label>详情:</label> <input name="book.detail" class="ui-input-text ui-body-null ui-corner-all ui-shadow-inset ui-body-c" /> <BUTTON type="submit" data-theme="b" data-inline="true">保存</BUTTON> <HR> </FORM> </DIV> <DIV class="footer-docs" data-role="footer" data-theme="c"> <P> 2012~2013 白强</P> </DIV> </BODY> </HTML>
show.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> <%@ 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>展示页面</title> <link href="css/style.css" rel="stylesheet" type="text/css" /> </head> <body> <h1 align="center"> 这里是展示页面</h1> <br> <div align="center"> <table id="show" align="center" style="text-align: center"> <tr> <td> ID </td> <td > 名称 </td> <td> 描述 </td> <td> 操作 </td> </tr> <s:iterator value="list"> <tr> <td> ${id} </td> <td > ${name} </td> <td> ${detail} </td> <td> <s:url id="get" action="getBook"> <s:param name="id">${id}</s:param> </s:url> <s:a href="%{get}">修改</s:a> <s:url id="del" action="delBook"> <s:param name="id">${id}</s:param> </s:url> <s:a href="%{del}">删除</s:a> </td> </tr> </s:iterator> </table> </div> </body> </html>
book.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> <%@ 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%>"> <META name="viewport" content="width=device-width, initial-scale=1"> <TITLE>更改</TITLE> <BODY> <DIV data-role="header" data-position="inline"> <H1>更改书</H1></DIV> <DIV data-role="content"> <FORM action="changeBook" method="POST"> <s:hidden name="book.id" ></s:hidden> <s:textfield name="book.name" class="ui-input-text ui-body-null ui-corner-all ui-shadow-inset ui-body-c" theme="simple" label="详情"></s:textfield> <br> <s:textfield name="book.detail" class="ui-input-text ui-body-null ui-corner-all ui-shadow-inset ui-body-c" theme="simple" label="详情"></s:textfield> <BUTTON type="submit" data-theme="b" data-inline="true">保存</BUTTON> <HR> </FORM> </DIV> <DIV class="footer-docs" data-role="footer" data-theme="c"> <P> 2012~2013 白强</P> </DIV> </BODY> </HTML>
还有一个简单的style
style.css
@charset "UTF-8"; /* CSS Document */ table { border: solid 1px #D5D5D5; border-collapse: collapse; width:100%; } table td { border:1px solid #D5D5D5; font-size:12px; padding:7px 5px; } table th { background-color:#EEE; border-right:1px solid #D5D5D5; font-size:13.5px; line-height:120%; font-weight:bold; padding:8px 5px; text-align:left; } .ui-resizable { position:relative; } .ui-resizable-handle { display:block; font-size:0.1px; position:absolute; z-index:99999; } .ui-resizable-s { background:#EEEEEE url(../images/grippie.png) no-repeat scroll center 2px; border-top:1px solid #CCCCCC; bottom:-5px; cursor:s-resize; height:14px; left:0;width:100%; }
最后再附上下载地址
就这样吧,不清楚的还可以问我。。。