SSH框架的整合
1.创建实体类,配置web.xml
package com.ch.entity; public class User { private int id; //用户编号 private String username; // 用户名 private String password; //密码 private String email; //邮箱 private String realname; //真实姓名 private int my_count; //发帖数 private int reply_count; //回帖数 public int getId() { return id; } public void setId(int 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 String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getRealname() { return realname; } public void setRealname(String realname) { this.realname = realname; } public int getMy_count() { return my_count; } public void setMy_count(int my_count) { this.my_count = my_count; } public int getReply_count() { return reply_count; } public void setReply_count(int reply_count) { this.reply_count = reply_count; } }
<?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"> <!-- struts2配置 --> <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:bean.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
2.创建实体类的映射文件------命名规则:类名.hbm.xml--------User.hbm.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.ch.entity"> <!-- name:类名 table:对应的表 --> <class name="User" table="user"> <!-- id:主键 name:主键名 column:对应的列名 --> <id name="id" column="userid"> <generator class="native"></generator> </id> <!-- property:其他列 name:属性名 column:对应的列名 --> <property name="username"></property> <property name="realname"></property> <property name="password"></property> <property name="email"></property> <property name="my_count"></property> <property name="reply_count"></property> </class> </hibernate-mapping>
3.配置spring的配置文件bean.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: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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 所有配置的公共部门 --> <!-- 1. 连接池实例 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql:///chenlong1"></property> <property name="user" value="root"></property> <property name="password" value="root"></property> <property name="initialPoolSize" value="3"></property> <property name="maxPoolSize" value="6"></property> </bean> <!-- 2. SessionFactory实例创建 --> <!-- 所有的配置都由spring维护(项目中不再需要hibernate.cfg.xml啦) --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- a. 连接池 --> <property name="dataSource" ref="dataSource"></property> <!-- b. hibernate常用配置: 方言、显示sql、自动建表等 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> <!-- c. 映射配置 --> <property name="mappingLocations"> <list> <value>classpath:com/ch/entity/*.hbm.xml</value> </list> </property> </bean> <!-- 3. 事务配置 --> <!-- a. 事务管理器 --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- b. 事务增强 --> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="*" read-only="false"/> </tx:attributes> </tx:advice> <!-- c. AOP配置 --> <aop:config> <aop:pointcut expression="execution(* com.ch.service.*.*(..))" id="pt"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/> </aop:config> <!-- 4.开启注解扫描 --> <context:component-scan base-package="com.ch"></context:component-scan> </beans>
4.dao层
package com.ch.dao; import java.io.Serializable; import javax.annotation.Resource; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.springframework.stereotype.Repository; import com.ch.entity.User; @Repository public class UserDao { @Resource private SessionFactory sessionFactory; /** * 保存 * @param user */ public void save(User user) { //创建session Session session = sessionFactory.openSession(); //开启手动提交事务 Transaction tx=session.beginTransaction(); try { //保存数据 session.save(user); //提交事务 tx.commit(); } catch (Exception e) { //提交失败,回滚 tx.rollback(); e.printStackTrace(); }finally{ //关闭session session.close(); } } /** * 登录验证 * @param user * @return */ public User login(User user) { return (User)sessionFactory.openSession().createQuery("from User where username=? and password=?") .setString(0, user.getUsername()) .setString(1, user.getPassword()) .uniqueResult(); } /** * id查找 * @param id * @return */ public User findById(Serializable id) { Session session = sessionFactory.openSession(); Transaction tx=session.beginTransaction(); User user = (User) session.get(User.class, id); tx.commit(); session.close(); return user; } }
5.service层
package com.ch.service; import java.io.Serializable; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.ch.dao.UserDao; import com.ch.entity.User; @Service public class UserService { @Resource private UserDao userDao; public User findById(Serializable id){ return userDao.findById(id); } public boolean login(User user){ if(userDao.login(user)!=null){ System.out.println("登陆成功!"); return true; }else{ System.out.println(user.getUsername()); System.out.println("用户名不存在"); return false; } } public boolean register(User user){ if(userDao.login(user)!=null){ System.out.println("用户名已经重复!"); return false; }else{ user.setMy_count(0); user.setReply_count(0); userDao.save(user); System.out.println("注册成功"); return true; } } }
6.action控制层
package com.ch.action; import java.sql.Driver; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Component; import org.springframework.stereotype.Controller; import com.ch.dao.UserDao; import com.ch.entity.User; import com.ch.service.UserService; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; @Component public class UserAction extends ActionSupport{ private User user=new User(); public void setUser(User user) { this.user = user; } public User getUser() { return user; } @Resource private UserService userService; @Override public String execute() throws Exception { //获取数据 User user=userService.findById(1); ActionContext ac=ActionContext.getContext(); //获取request Map<String, Object> request=ac.getContextMap(); //将数据放入 request.put("user", user); return "success"; } public String login(){ ActionContext ac=ActionContext.getContext(); Map<String, Object> session=ac.getSession(); //获取request Map<String, Object> request=ac.getContextMap(); System.out.println(user.getUsername()); if(userService.login(user)){ session.put("username", user.getUsername()); if(session.get("login")!=null){ session.remove("login"); } return "loginSuccess"; }else { session.put("login", "1"); return "login"; } } public String register(){ System.out.println(user.getUsername()); System.out.println(user.getEmail()); if(userService.register(user)){ return "registerSuccess"; }else{ ActionContext ac=ActionContext.getContext(); //获取request Map<String, Object> request=ac.getContextMap(); //将数据放入 request.put("user", user); return "register"; } } public String list(){ return "success"; } }
6.配置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.i18n.encoding" value="UTF-8"/> <package name="userConfig" extends="struts-default"> <!-- action实例交给spring容器创建 --> <action name="user_*" class="userAction" method="{1}"> <result name="loginSuccess" type="redirectAction">dictionary_list</result> <result name="registerSuccess">/jsp/login.jsp</result> <result name="register">/jsp/register.jsp</result> <result name="login">/jsp/login.jsp</result> </action> </package> </struts>
8.jsp的创建
略;
<?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"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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 所有配置的公共部门 --><!-- 1. 连接池实例 --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="com.mysql.jdbc.Driver"></property><property name="jdbcUrl" value="jdbc:mysql:///chenlong1"></property><property name="user" value="root"></property><property name="password" value="root"></property><property name="initialPoolSize" value="3"></property><property name="maxPoolSize" value="6"></property></bean>
<!-- 2. SessionFactory实例创建 --><!-- 所有的配置都由spring维护(项目中不再需要hibernate.cfg.xml啦) --><bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><!-- a. 连接池 --><property name="dataSource" ref="dataSource"></property><!-- b. hibernate常用配置: 方言、显示sql、自动建表等 --><property name="hibernateProperties"><props><prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop><prop key="hibernate.show_sql">true</prop><prop key="hibernate.hbm2ddl.auto">update</prop></props></property><!-- c. 映射配置 --><property name="mappingLocations"><list><value>classpath:com/ch/entity/*.hbm.xml</value></list></property></bean><!-- 3. 事务配置 --><!-- a. 事务管理器 --><bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"></property></bean><!-- b. 事务增强 --><tx:advice id="txAdvice" transaction-manager="txManager"><tx:attributes><tx:method name="*" read-only="false"/></tx:attributes></tx:advice><!-- c. AOP配置 --><aop:config><aop:pointcut expression="execution(* com.ch.service.*.*(..))" id="pt"/><aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/></aop:config><!-- 4.开启注解扫描 --><context:component-scan base-package="com.ch"></context:component-scan></beans>