仅作为个人笔记,供日后回顾用。
首先要感谢博主eson_15,博主的文章帮助了我很多,附上该博主ssh框架搭建的博客链接:http://blog.csdn.net/eson_15/article/details/51277324。
本次使用的框架是Struts2+Hibernate4.3+Spring4.2 ,使用的IDE是Eclipse,使用的数据库是MySQL。
**
先部署Struts2,再Spring,最后Hibernate。其实,这三个框架的部署顺序并没有什么规定,谁先谁后并没有多大影响,我按照这样的顺序部署,只是个人喜好。
这里先稍微总结一下搭建s2sh框架所必需的jar包(如下图),jar包分类存放是一个好习惯,但是要注意,在导入到web项目中时,一定要将jar包统一放在WEB-INF/lib下,否则会有奇怪的错误,我被坑了整整一个下午。
(一)导入jar包
导入struts2.3.41中的jar包即可,过程不赘述。
(二)配置web.xml文件
web.xml文件的作用为设置过滤器,决定了从jsp页面传过来的请求被哪个action处理。代码如下:
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>mys2shdisplay-name>
<welcome-file-list>
<welcome-file>index.jspwelcome-file>
welcome-file-list>
<filter>
<filter-name>struts2filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilterfilter-class>
filter>
<filter-mapping>
<filter-name>struts2filter-name>
<url-pattern>/*url-pattern>
filter-mapping>
web-app>
(三)测试
测试的思路是:新建一个简单的action类和一个简单的jsp页面,测试从jsp页面发送请求,看是否在控制台正确的打印了相关信息。action类的代码如下:
package com.mys2sh.action;
import java.util.Map;
import com.mys2sh.dao.BookDao;
public class QueryAction {
private String name;
private BookDao book;
public BookDao getBook() {
return book;
}
public void setBook(BookDao book) {
this.book = book;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
private Map result;
public Map getResult() {
return result;
}
public void setResult(Map result) {
this.result = result;
}
public String execute() throws Exception{
try {
System.out.println("name=" + name);
Map books = book.getBooks(name);
if(books.isEmpty()){
System.out.println("%%%%%%%No item!%%%%%%%%%%%%%");
}
else{
setResult(books);
System.out.println("%%%%%%%success!%%%%%%%%%%%%%");
}
return "success";
}
catch(Exception e){
System.out.println("%%%%%%%error!%%%%%%%%%%%%%");
e.printStackTrace();
return "error";
}
}
}
上面的action类依赖了BookDao类,如下:
package com.mys2sh.dao;
import java.util.*;
public class BookDao {
private static Map<String, Integer> books = new LinkedHashMap<String, Integer>();
static{
books.put("book1", 79);
books.put("book2", 20);
books.put("book3", 34);
books.put("book4", 65);
books.put("book5", 55);
books.put("book6", 77);
books.put("book7", 17);
}
public static Map<String, Integer> getBooks() {
return books;
}
public static void setBooks(Map<String, Integer> books) {
BookDao.books = books;
}
public Map<String,Integer> getBooks(String name){
Map<String,Integer> books = new LinkedHashMap<String, Integer>();
for(Map.Entry<String, Integer> entry:BookDao.books.entrySet() ){
if(entry.getKey().toLowerCase().contains(name.toLowerCase())){
books.put(entry.getKey(), entry.getValue());
}
}
return books;
}
}
配置struts.xml文件,要为每一个action配置:
<struts>
<package name="default" extends="struts-default">
<action name = "query" class = "com.mys2sh.action.queryAction">
<result name = "success">/success.jspresult>
<result name = "error">/error.jspresult>
action>
package>
struts>
jsp页面的代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title heretitle>
head>
<body>
<a href="query.action?name="book1">querya>
body>
html>
(一)导入jar包
因为只和Struts2整合,所以只需导入spring4.2.4-core和spring4.2.4-web中的jar包,导包过程不赘述。
(二)配置applicationContext.xml
Spring框架的作用,就是通过依赖注入的方式为web项目中的各种类创建实例对象,而applicationContext.xml文件指定了实例对象的属性,如下:
<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"
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-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="bookdao" class="com.mys2sh.dao.BookDao">bean>
<bean id="queryAction" class="com.mys2sh.action.QueryAction">
<property name="book" ref="bookdao">property>
bean>
beans>
(三)修改配置文件
需要修改两个配置文件:web.xml和struts.xml文件。
修改web.xml文件是在其中添加Spring的监听器,修改后的web.xml如下:
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>mys2shdisplay-name>
<welcome-file-list>
<welcome-file>index.jspwelcome-file>
welcome-file-list>
<filter>
<filter-name>struts2filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilterfilter-class>
filter>
<filter-mapping>
<filter-name>struts2filter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>/WEB-INF/applicationContext*.xml,classpath*:applicationContext*.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
web-app>
修改struts.xml文件是修改action标签的class属性,修改后的struts.xml如下:
<struts>
<package name="default" extends="struts-default">
<action name = "query" class = "queryAction">
<result name = "success">/success.jspresult>
<result name = "error">/error.jspresult>
action>
package>
struts>
(四)测试
测试和单独测试struts时一样,因为只是换了一种方式获取BookDao对象,不再赘述。
(一)导入jar包
将剩下的jar包全部导入即可,导包过程不赘述。
(二)配置文件
需要配置的文件有两个,一个用于和数据库中的表建立对应关系,我在这个练习中使用的是User.hbm.xml;另一个用于和数据库建立连接,这里交给Spring框架,修改applicationContext.xml文件即可。
配置User.hbm.xml文件,如下:
<hibernate-mapping>
<class name="com.mys2sh.vo.UserVo" table="t_user">
<id name="userid" column="userid" type="int" />
<property name="name" column="name" type="text" />
<property name="password" column="password" type="text" />
<property name="email" column="email" type="text" />
<property name="mobile" column="mobile" type="text" />
class>
hibernate-mapping>
修改applicationContext.xml文件是增加了对数据库的配置和利用aop进行数据库事务的管理,修改后的applicationContext.xml文件如下:
<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"
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-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mys2sh" />
<property name="user" value="root" />
<property name="password" value="Urie_308" />
bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialectprop>
<prop key="hibernate.hbm2ddl.auto">updateprop>
<prop key="hibernate.connection.autocommit">true prop>
<prop key="hibernate.show_sql">trueprop>
<prop key="sql_format">trueprop>
props>
property>
<property name="mappingResources">
<list>
<value>/User.hbm.xmlvalue>
list>
property>
bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
bean>
<tx:advice id="advice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="create*" propagation="REQUIRED"/>
<tx:method name="query*" read-only="true"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.mys2sh.dao.impl.*.*(..))" />
<aop:advisor advice-ref="advice" pointcut-ref="pointcut"/>
aop:config>
<bean id="user" class="com.mys2sh.vo.UserVo">
<property name="sessionFactory" ref="sessionFactory">property>
bean>
<bean id="userDao" class="com.mys2sh.dao.impl.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory">property>
<property name="user" ref="user">property>
bean>
<bean id="userAction" class="com.mys2sh.action.UserAction">
<property name="userDao" ref="userDao">property>
bean>
<bean id="bookdao" class="com.mys2sh.dao.BookDao">bean>
<bean id="queryAction" class="com.mys2sh.action.QueryAction">
<property name="book" ref="bookdao">property>
bean>
beans>
(三)测试
为了测试,修改了struts.xml文件的内容,最后的struts.xml文件如下:
<struts>
<package name="default" extends="struts-default">
<action name = "query" class = "queryAction">
<result name = "success">/success.jspresult>
<result name = "error">/error.jspresult>
action>
<action name="user" class="userAction" method="createUser">
<result name="SUCCESS">/success.jspresult>
<result name="ERROR">/error.jspresult>
action>
<action name="queryuser" class="userAction" method="queryUser">
<result name="SUCCESS">/success.jspresult>
<result name="ERROR">/error.jspresult>
action>
package>
struts>
测试用到的Java类如下:
UserVo类
package com.mys2sh.vo;
import org.hibernate.SessionFactory;
public class UserVo {
private String name;
private String password;
private String email;
private String mobile;
private int userid;
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
}
UserDao接口
package com.mys2sh.dao;
import java.util.List;
import java.util.Set;
import com.mys2sh.vo.UserVo;
public interface UserDao {
public UserVo getUser(String name);
public UserVo createUser(String name,String password);
public List query();
}
UserDaoImpl类
package com.mys2sh.dao.impl;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.mys2sh.dao.UserDao;
import com.mys2sh.vo.UserVo;
public class UserDaoImpl implements UserDao {
private UserVo user;
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Session getSession(){
return sessionFactory.getCurrentSession();
}
public UserVo getUser() {
return user;
}
public void setUser(UserVo user) {
this.user = user;
}
@Override
public UserVo getUser(String name) {
// TODO Auto-generated method stub
return this.user;
}
//这个方法当没看到吧,太久没写Java代码,把事务、session什么的都忘了
@Override
public UserVo createUser(String name, String password) {
// TODO Auto-generated method stub
user.setName(name);
user.setPassword(password);
return user;
}
@Override
public List query() {
// TODO Auto-generated method stub
String hql = "from UserVo";
getSession().createQuery(hql);
Query query = getSession().createQuery(hql);
List userList = query.list();
return userList;
}
}
UserAction类
package com.mys2sh.action;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import com.mys2sh.dao.UserDao;
import com.mys2sh.vo.UserVo;
public class UserAction {
private UserDao userDao;
private String name;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public String createUser(){
UserVo user = userDao.createUser(name, password);
if(user.getName() == name){
return "SUCCESS";
}
return "ERROR";
}
public String queryUser(){
List userList = userDao.query();
Iterator users = userList.iterator();
while(users.hasNext()){
UserVo user1 = users.next();
System.out.println(user1.getName() + "---------" + "password:" + user1.getPassword());
}
if(!userList.isEmpty()){
return "SUCCESS";
}
return "ERROR";
}
}
测试的页面代码如下:
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title heretitle>
head>
<body>
<a href="queryuser.action">querya>
body>
html>
success.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title heretitle>
head>
<body>
<p>Success!p>
body>
html>
error.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title heretitle>
head>
<body>
<p>Error!p>
body>
html>
**