一、引入Struts的jar包,spring的jar包,hibernate的jar包,Apache的一些jar包,还有加入struts2-spring-plugin-2.3.28.jar这个插件jar包,截图如下:
当然现在的Java开发都流行maven管理了,我这里只是找点从前的感觉,嫌烦的话就用maven,配置相关的jar包即可
二、web.xml的配置
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>ssh_01000</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- spring配置 --> <context-param> <param-name>contextConfigLocation</param-name> <!-- <param-value>/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value> --> <param-value>classpath:beans.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 打开全局session --> <filter> <filter-name>openSessionInView</filter-name> <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>sessionFactoryBeanName</param-name> <param-value>sessionFactory</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInView</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Struts的配置项 --> <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> <!-- 字符集设置,防止乱码 --> <filter> <filter-name>Spring character encoding filter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>Spring character encoding filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
三、Struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <constant name="struts.devMode" value="true" /> <constant name="struts.custom.i18n.resources" value="global"></constant> <!-- 设置action属性的配置方式 --> <!-- <constant name="struts.objectFactory.spring.autoWire" value="name"></constant> --> <package name="test" namespace="/test" extends="struts-default"> <interceptors> <interceptor-stack name="myInterceptor"> <interceptor-ref name="defaultStack">
<!-- 配置不需要进行表单校验的方法 --> <param name="validation.excludeMethods">fineUser</param> </interceptor-ref> </interceptor-stack> </interceptors> <!-- 注释开始 <default-action-ref name="index" /> <global-results>
<!-- 配置的全局result,出错时会跳转到此页面 --> <result name="error">/WEB-INF/jsp/error.jsp</result> </global-results> <!-- 出错时跳转到error的result指定的那个页面 --> <global-exception-mappings> <exception-mapping exception="java.lang.Exception" result="error"/> </global-exception-mappings> 注释结束--> <!-- <default-action-ref name="register"></default-action-ref> --> <!-- class中不写类名,表示叫spring来负责创建action,如果你用的是全类名的话,那么action的创建仍然有Struts创建,
如果设置的Struts.ObjectFactroy.spring.autoWire为name,那么这个action的内部用到的service名称必须与spring中bean id一样,如果为type,那么相同的类型只能一个 --> <action name="register" class="register"> <interceptor-ref name="myInterceptor"> </interceptor-ref> <result> <!-- <param name="location">/success.jsp</param>与下面那样写是一个意思 --> /success.jsp </result> <result name="input">/register.jsp</result> </action> <action name="show" class="show"> <result> <!-- <param name="location">/success.jsp</param> --> /showusers.jsp </result> <result name="input">/register.jsp</result> </action> </package> </struts>
四、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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <bean id="show" class="youth.hong.ShowUsers"> <property name="userService" ref="userService"></property> </bean> <bean id="register" class="youth.hong.Check" scope="prototype"> <property name="userService" ref="userService"></property> </bean> <!-- 用于注入sessionFactory --> <bean id="superDao" class="youth.hong.SuperDao"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <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://localhost:3306/spring" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- <property name="mappingResources">注解扫描的方式 -->
<!-- <property name="packagesToScan">
<list>
<value>youth.hong..User</value>
</list>
</property> -->
<property name="annotatedClasses"> <list> <value>youth.hong.User</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> </bean> <!-- parent="superDao"表示继承superDao的配置 --> <bean id="userDao" class="youth.hong.UserDaoImpl" parent="superDao"> </bean> <bean id="userService" class="youth.hong.UserServiceImpl"> <property name="userDao" ref="userDao"></property> </bean> <tx:annotation-driven transaction-manager="txManager" /> <!-- 注释开始<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> 注释结束--> <bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!--aop的方式配置事物 <aop:config> <aop:pointcut expression="execution(* youth.hong.UserServiceImpl.*(..))" id="cut"/> <aop:advisor advice-ref="advice" pointcut-ref="cut"/> </aop:config> <tx:advice id="advice" transaction-manager="txManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> --> <tx:annotation-driven transaction-manager="txManager"/> </beans>
五、Java类,这里就做个登录注册的来说明ssh的整合
1、JavaBean类User.java
package youth.hong; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; //hibernate注解 @Entity public class User { private int id; private int pid; public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } @Id @GeneratedValue(strategy=GenerationType.IDENTITY) public int getId() { return id; } public void setId(int id) { this.id = id; } private String username; private String password; 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; } }
2、Action类
package youth.hong; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; @SuppressWarnings("serial") public class Check extends ActionSupport implements ModelDriven<User> { private User user = new User(); /*private String username; private String password; //private ClassPathXmlApplicationContext applicationContext; 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; } */ private UserServiceDao userService; public UserServiceDao getUserService() { return userService; } public void setUserService(UserServiceDao userService) { this.userService = userService; } public String fineUser() { int id = user.getId(); System.out.println(id); user = userService.loadById(id); return "showoneuser"; } public void setUser(User user) { this.user = user; } @Override public String execute() throws Exception { // applicationContext = new ClassPathXmlApplicationContext("beans.xml"); // UserServiceDao userService = (UserServiceDao)applicationContext.getBean("userService"); System.out.println(userService); System.out.println(user.getPid()); System.out.println(user.getUsername()); boolean t = userService.save(user); if(t) { this.addFieldError("usererror", "用户名冲突,注册失败!"); return INPUT; } return SUCCESS; } public User getUser() { return user; } @Override public User getModel() { return user; } }
3、UserService接口类
package youth.hong; import java.util.List; public interface UserServiceDao { public UserDao getUserDao(); public void setUserDao(UserDao userDao); public boolean save(User user); public boolean isExists(User user); public List<User> getUsers(); public User loadById(int id); }
4、UserServiceImpl类
package youth.hong; import java.util.List; import org.springframework.transaction.annotation.Transactional; public class UserServiceImpl implements UserServiceDao { private UserDao userDao; public UserDao getUserDao() { return userDao; } public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Transactional public boolean save(User user) { boolean t = isExists(user); if(t) { return t; } userDao.save(user); return false; } @Override public boolean isExists(User user) { return userDao.isExists(user); } @Override public List<User> getUsers() { return userDao.getUsers(); } @Override @Transactional public User loadById(int id) { return userDao.loadById(id); } }
5、UserDao类
package youth.hong; import java.util.List; public interface UserDao { public void save(User user); public boolean isExists(User user); public List<User> getUsers(); public User loadById(int id); }
6、UserDaoImpl类
package youth.hong; import java.util.List; public class UserDaoImpl extends SuperDao implements UserDao { @Override public void save(User user) { this.getHibernateTemplate().save(user); } @Override public boolean isExists(User user) { String sql = "from User u where u.username=?"; @SuppressWarnings("unchecked") List<User> users = (List<User>) this.getHibernateTemplate().find(sql, user.getUsername()); if(users.size() > 0) { return true; } return false; } @SuppressWarnings("unchecked") @Override public List<User> getUsers() { String sql = "from User"; return (List<User>) this.getHibernateTemplate().find(sql); } @Override public User loadById(int id) { User user = (User)this.getHibernateTemplate().load(User.class,id); //System.out.println(user); return user; } }
7、SuperDao
package youth.hong; import org.hibernate.SessionFactory; /** * 给其他的Dao类继承,使用它注入sessionFactory,省去重复注入的麻烦 * @author may * */ public class SuperDao extends org.springframework.orm.hibernate5.support.HibernateDaoSupport { public void setSuperSessionFactory(SessionFactory sessionFactory) { super.setSessionFactory(sessionFactory); } }
8、列出数据库中存在的User信息
package youth.hong; import java.util.List; import com.opensymphony.xwork2.ActionSupport; @SuppressWarnings("serial") public class ShowUsers extends ActionSupport { private List<User> users = null; private UserServiceDao userService; public UserServiceDao getUserService() { return userService; } public void setUserService(UserServiceDao userService) { this.userService = userService; } public List<User> getUsers() { return users; } public void setUsers(List<User> users) { this.users = users; } @Override public String execute() throws Exception { users = userService.getUsers(); System.out.println(users.size()); return SUCCESS; } }
六、字段校验,跟action同目录
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd"> <validators> <validator type="requiredstring"> <param name="fieldName">username</param> <param name="trim">true</param>
<!-- 从全局国际化配置文件中获取错误提示 --> <message key="requiredstringusername" /> </validator> <validator type="regex"> <param name="fieldName">username</param> <param name="regex"><![CDATA[(w{1,})]]></param> <message>error</message> </validator> <field name="password"> <field-validator type="requiredstring"> <param name="trim">true</param> <message key="requiredstringpassword" /> </field-validator> </field> </validators>
七、全局i18n国际化配置信息文件,放在src下
global_en_US.properties
user.username=username
user.password=password
global_zh_CN.properties
user.username=u7528u6237u540D user.password=u5BC6 u7801 requiredstringusername=u7528u6237u540Du4E0Du80FDu4E3Au7A7A requiredstringpassword=u5BC6u7801u4E0Du80FDu4E3Au7A7A
八、视图界面
Register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<%System.out.println(request.getContextPath()); %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<s:property value="fieldErrors.usererror[0]" />
<s:form method="post" action="test/register">
<s:textfield name="username" key="user.username"></s:textfield>
<s:textfield name="password" key="user.password"></s:textfield>
<s:textfield name="pid"></s:textfield>
<s:submit value="submit"></s:submit>
</s:form>
<s:property value="get{'user.username'}"/>
<s:debug></s:debug>
</body>
</html>
用户列表界面
<%@page import="youth.hong.ShowUsers"%> <%@ 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" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <table> <tr><td>用户列表</td></tr> <s:iterator value="users" var="user"> <tr><td> <s:property value="#user.username"/> </td> </tr> </s:iterator> </table> <s:debug></s:debug> </body> </html>