spring+springMvc+struts的SSH框架整合

1.建立一个web项目

2.导入SSH框架所需jar包

 

3.配置web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<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>SSHDemo</display-name><!--直接访问项目时,依次查找下面的jsp进行显示  --><welcome-file-list><welcome-file>login.jsp</welcome-file><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><!--上下文配置名字和路径配置--><context-param><!-- 上下文参数名字 --><param-name>contextConfigLocation</param-name><!--上下文全局配置文件的位置,以根路径作为开始找 --><param-value>classpath:applicationContext.xml</param-value></context-param><!-- 定义监听事件 --><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- 定义过滤的名字及其所在的地方 --><filter><filter-name>OpenSessionInViewFilter</filter-name><filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class></filter><!--定义需要拦截的后缀,只要满足.action就会去查找对应过滤器名字的拦截器实现类--><filter-mapping><filter-name>OpenSessionInViewFilter</filter-name><url-pattern>*.action</url-pattern></filter-mapping><!--定义struts的过滤器名字和实现类--><filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class></filter><!--定义struts满足路径/*条件,就进入到filter-name为struts2的filter-class进行实现 --><filter-mapping><filter-name>struts2</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- 定义会话超时时间 --><session-config><session-timeout>25</session-timeout></session-config></web-app>

4.配置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"xmlns:p="http://www.springframework.org/schema/p"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.1.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.1.xsd"><!-- 加载Hibernate配置 --><!-- <bean id="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><property name="configLocation"><value>classpath:hibernate.cfg.xml</value></property></bean> --><!-- 定义dbcp数据源 --><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"><!-- 指定JDBC驱动类 --><property name="driverClassName" value="com.mysql.jdbc.Driver"></property><!-- 提供连接数据库的URL地址 --><property name="url" value="jdbc:mysql://localhost/spring?useSSL=false&amp;serverTimezone=UTC"></property><!-- 提供连接数据库的用户名和密码 --><property name="username" value="root"></property><property name="password" value="root"></property></bean><!-- 定义SessionFactory Bean --><bean id="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><!-- 为LocalSessionFactoryBean注入定义好的数据源 --><property name="dataSource"><ref bean="dataSource" /></property><!-- 添加Hibernate配置参数 --><property name="hibernateProperties"><props><!-- 定义方言 --><prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop><!-- 定义运行时,是否在控制台进行将sql输出 --><prop key="hibernate.show_sql">true</prop><!-- 定义运行时,是否在控制台输出的sql语句进行格式化  --><prop key="hibernate.format_sql">true</prop></props></property><!-- 添加对象关系映射文件 --><property name="mappingDirectoryLocations"><list><value>classpath:com/sshdemo/entity/</value></list></property></bean><!-- 配置DAO --><bean id="employeeDao" class="com.sshdemo.dao.hibimpl.EmployeeDaoHibImpl"><property name="sessionFactory" ref="sessionFactory" /></bean><!-- 配置业务层 --><bean id="employeeService" class="com.sshdemo.service.impl.EmployeeServiceImpl"><property name="employeeDao" ref="employeeDao"></property></bean><!-- 定义事务管理器 --><bean id="txManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory" /></bean><tx:advice id="txAdvice" transaction-manager="txManager"><tx:attributes><!-- read-only是表示调用这个方法时是否是子读状态,一般只用于查询,涉及更改时不要使用否则操作数据库时会抛出异常并且不能对数据更改 --><tx:method name="find*" read-only="true" /><tx:method name="search*" read-only="true" /><tx:method name="query*" read-only="true" /><tx:method name="add*" propagation="REQUIRED" /><tx:method name="del*" propagation="REQUIRED" /><tx:method name="update*" propagation="REQUIRED" /><tx:method name="do*" propagation="REQUIRED" /><tx:method name="register*" propagation="REQUIRED" /><tx:method name="*" propagation="REQUIRED" read-only="true" /></tx:attributes></tx:advice><aop:config><!-- 定义切入点,表示当执行com.sshdemo.service包下面所有的类的所有方法及其各种参数的方法时切入事务管理 --><aop:pointcut id="serviceMethod"expression="execution(* com.sshdemo.service.*.*(..))" /><!-- 将事务通知与切入点组合 --><aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod" /></aop:config><tx:annotation-driven transaction-manager="txManager"/><!-- 控制层 (id为struts.xml中的class) 以下每个bean必须都要增加scope="prototype"属性 --><bean id="userAction" class="com.sshdemo.action.UserAction"scope="prototype"><property name="employeeService" ref="employeeService"></property></bean></beans>

5.建立实体类及其对应的xml文件

package com.sshdemo.entity;/*** 员工 实体类。 */
public class Employee implements java.io.Serializable {// Fieldsprivate static final long serialVersionUID = 5106663630382037556L;private String sn;private Position position;private Department department;private String password;private String name;private String status;// Constructors/** default constructor */public Employee() {}/** full constructor */public Employee(Position position, Department department, String password,String name, String status) {this.position = position;this.department = department;this.password = password;this.name = name;this.status = status;}// Property accessors/*** @return 工号*/public String getSn() {return this.sn;}public void setSn(String sn) {this.sn = sn;}/*** @return 职务*/public Position getPosition() {return this.position;}public void setPosition(Position position) {this.position = position;}/*** @return 部门*/public Department getDepartment() {return this.department;}public void setDepartment(Department department) {this.department = department;}/*** @return 密码*/public String getPassword() {return this.password;}public void setPassword(String password) {this.password = password;}/*** @return 姓名*/public String getName() {return this.name;}public void setName(String name) {this.name = name;}/*** @return 状态*/public String getStatus() {return this.status;}public void setStatus(String status) {this.status = status;}
}

创建employee对应的xml文件:Employee.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.sshdemo.entity"><class name="Employee" table="sys_employee"><id name="sn" type="string"><column length="20" name="sn" /><generator class="assigned" /></id><many-to-one class="Position" fetch="select" name="position"><column name="position_id" not-null="false"><comment>职务编号</comment></column></many-to-one><many-to-one class="Department" fetch="select" name="department"><column name="department_id" not-null="false"><comment>部门</comment></column></many-to-one><property lazy="false" name="password"type="string"><column length="45" name="password" not-null="true"><comment>密码</comment></column></property><property lazy="false" name="name" type="string"><column length="45" name="name" not-null="true"><comment>姓名</comment></column></property><property lazy="false" name="status" type="string"><column length="20" name="status" not-null="true"><comment>状态</comment></column></property></class>
</hibernate-mapping>

创建部门的实体表和xml文件

package com.sshdemo.entity;/*** 部门 实体类。 */
public class Department implements java.io.Serializable {// Fieldsprivate static final long serialVersionUID = 5073258499319872911L;private Integer id;private Employee manager;private String name;// Constructors/** default constructor */public Department() {}/** minimal constructor */public Department(String name) {this.name = name;}/** full constructor */public Department(Employee manager, String name) {this.manager = manager;this.name = name;}// Property accessors/*** @return 部门编号*/public Integer getId() {return this.id;}public void setId(Integer id) {this.id = id;}/*** @return 部门经理*/public Employee getManager() {return this.manager;}public void setManager(Employee manager) {this.manager = manager;}/*** @return 部门名称*/public String getName() {return this.name;}public void setName(String name) {this.name = name;}
}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><!--package指定的是映射的实体类的位置路径  -->
<hibernate-mapping package="com.sshdemo.entity"><!-- name指定实体类的名字,table定义数据库中建立的表的名字 --><class name="Department" table="sys_department"><id name="id" type="integer"><!-- 这个地方定义的是数据库中对应实体类的列名,可以不定义,它的生成就会和实体类一样 --><column name="id" /><!-- 主键的增长方式,native表示自增长 --><generator class="native" /></id><many-to-one name="manager" class="Employee" fetch="select"><column name="manager_sn" length="20"><comment>部门经理</comment></column></many-to-one><property name="name" type="string"><column name="name" length="45" not-null="true"><comment>部门名称</comment></column></property></class>
</hibernate-mapping>

创建Dictionary

package com.sshdemo.entity;/*** 数据字典 实体类。 */
public class Dictionary implements java.io.Serializable {// Fieldsprivate static final long serialVersionUID = -3482598030856972288L;private long id;private String type;private String item;private String value;// Constructors/** default constructor */public Dictionary() {}/** full constructor */public Dictionary(String type, String item, String value) {this.type = type;this.item = item;this.value = value;}// Property accessors/*** @return 编号*/public long getId() {return this.id;}public void setId(long id) {this.id = id;}/*** @return 类型*/public String getType() {return this.type;}public void setType(String type) {this.type = type;}/*** @return 条目*/public String getItem() {return this.item;}public void setItem(String item) {this.item = item;}/*** @return*/public String getValue() {return this.value;}public void setValue(String value) {this.value = value;}}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping package="com.sshdemo.entity"><class name="Dictionary" table="sys_dictionary"><id name="id" type="long"><column name="id" /><generator class="native" /></id><property name="type" type="string"><column name="type" length="20" not-null="true" /></property><property name="item" type="string"><column name="item" length="20" not-null="true" /></property><property name="value" type="string"><column name="value" length="20" not-null="true" /></property></class>
</hibernate-mapping>

创建positon类和xml

package com.sshdemo.entity;/*** 职务 实体类。 */
public class Position implements java.io.Serializable {// Fieldsprivate static final long serialVersionUID = 4107962667586915867L;private Integer id;private String nameCn;private String nameEn;// Constructors/** default constructor */public Position() {}/** minimal constructor */public Position(String nameCn, String nameEn) {this.nameCn = nameCn;this.nameEn = nameEn;}// Property accessors/*** @return 职务编号*/public Integer getId() {return this.id;}public void setId(Integer id) {this.id = id;}/*** @return 职务名称(中文)*/public String getNameCn() {return this.nameCn;}public void setNameCn(String nameCn) {this.nameCn = nameCn;}/*** @return 职务名称(英文)*/public String getNameEn() {return this.nameEn;}public void setNameEn(String nameEn) {this.nameEn = nameEn;}}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping package="com.sshdemo.entity"><class name="Position" table="sys_position"><id name="id" type="integer"><column name="id" /><generator class="native" /></id><property name="nameCn" type="string"><column name="name_cn" length="45" not-null="true"><comment>职务名称(中文)</comment></column></property><property name="nameEn" type="string"><column name="name_en" length="45" not-null="true"><comment>职务名称(英文)</comment></column></property></class>
</hibernate-mapping>

创建CheckResult类和xml文件

package com.sshdemo.entity;import java.util.Date;/*** 审核结果 实体类。 */
public class CheckResult implements java.io.Serializable {// Fieldsprivate static final long serialVersionUID = 8366759716422180617L;private long id;private String sheetType;private long sheetId;private Date checkTime;private String type;private Employee checker;private String result;private String comment;// Constructors/** default constructor */public CheckResult() {}/** minimal constructor */public CheckResult(String sheetType, long sheetId, Date checkTime,String type, Employee checker, String result) {this.sheetType = sheetType;this.sheetId = sheetId;this.checkTime = checkTime;this.type = type;this.checker = checker;this.result = result;}/** full constructor */public CheckResult(String sheetType, long sheetId, Date checkTime,String type, Employee checker, String result, String comment) {this.sheetType = sheetType;this.sheetId = sheetId;this.checkTime = checkTime;this.type = type;this.checker = checker;this.result = result;this.comment = comment;}// Property accessors/*** @return 编号*/public long getId() {return this.id;}public void setId(long id) {this.id = id;}/*** @return 单据类型*/public String getSheetType() {return this.sheetType;}public void setSheetType(String sheetType) {this.sheetType = sheetType;}/*** @return 单据编号*/public long getSheetId() {return this.sheetId;}public void setSheetId(long sheetId) {this.sheetId = sheetId;}/*** @return 审核时间*/public Date getCheckTime() {return this.checkTime;}public void setCheckTime(Date checkTime) {this.checkTime = checkTime;}/*** @return 审核类别*/public String getType() {return this.type;}public void setType(String type) {this.type = type;}/*** @return 审核人*/public Employee getChecker() {return this.checker;}public void setChecker(Employee checker) {this.checker = checker;}/*** @return 审核结果*/public String getResult() {return this.result;}public void setResult(String result) {this.result = result;}/*** @return 审核意见*/public String getComment() {return this.comment;}public void setComment(String comment) {this.comment = comment;}}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping package="com.sshdemo.entity"><class name="CheckResult" table="biz_check_result"><id name="id" type="long"><column name="id" /><generator class="native" /></id><property name="sheetType" type="string"><column name="sheet_type" length="20" not-null="true"><comment>单据类型</comment></column></property><property name="sheetId" type="long"><column name="sheet_id" not-null="true"><comment>单据编号</comment></column></property><property name="checkTime" type="date"><column name="check_time" length="19" not-null="true"><comment>审核时间</comment></column></property><property name="type" type="string"><column name="type" length="20" not-null="true"><comment>审核类型</comment></column></property><many-to-one name="checker" class="Employee" fetch="select"><column name="checker_sn" length="20" not-null="true"><comment>审核人</comment></column></many-to-one><property name="result" type="string"><column name="result" length="20" not-null="true"><comment>审核结果</comment></column></property><property name="comment" type="string"><column name="comment"><comment>审核意见</comment></column></property></class>
</hibernate-mapping>

创建ClaimVoucher类

package com.sshdemo.entity;import java.util.Date;
import java.util.HashSet;
import java.util.Set;/*** 报销申请单 实体类。 */
public class ClaimVoucher implements java.io.Serializable {// Fieldsprivate static final long serialVersionUID = -1763618295413371212L;private long id;private Employee nextDealBy;private Employee creator;private Date createTime;private String event;private double totalAccount;private String status;private Set<ClaimVoucherDetail> details = new HashSet<ClaimVoucherDetail>(0);// Constructors    /** default constructor */public ClaimVoucher() {}/** minimal constructor */public ClaimVoucher(Employee employeeByCreateSn, Date createTime,String event, double totalAccount, String status) {this.creator = employeeByCreateSn;this.createTime = createTime;this.event = event;this.totalAccount = totalAccount;this.status = status;}/** full constructor */public ClaimVoucher(Employee employeeByNextDealSn,Employee employeeByCreateSn, Date createTime, String event,double totalAccount, String status, Set<ClaimVoucherDetail> claimVoucherDetails) {this.nextDealBy = employeeByNextDealSn;this.creator = employeeByCreateSn;this.createTime = createTime;this.event = event;this.totalAccount = totalAccount;this.status = status;this.details = claimVoucherDetails;}// Property accessors/*** @return 编号*/public long getId() {return this.id;}public void setId(long id) {this.id = id;}/*** @return 待处理人*/public Employee getNextDealBy() {return this.nextDealBy;}public void setNextDealBy(Employee employeeByNextDealSn) {this.nextDealBy = employeeByNextDealSn;}/*** @return 填报人*/public Employee getCreator() {return this.creator;}public void setCreator(Employee employeeByCreateSn) {this.creator = employeeByCreateSn;}/*** @return 填写时间*/public Date getCreateTime() {return this.createTime;}public void setCreateTime(Date createTime) {this.createTime = createTime;}/*** @return 事由*/public String getEvent() {return this.event;}public void setEvent(String event) {this.event = event;}/*** @return 总金额*/public double getTotalAccount() {return this.totalAccount;}public void setTotalAccount(double totalAccount) {this.totalAccount = totalAccount;}/*** @return 状态*/public String getStatus() {return this.status;}public void setStatus(String status) {this.status = status;}/*** @return 明细*/public Set<ClaimVoucherDetail> getDetails() {return this.details;}public void setDetails(Set<ClaimVoucherDetail> claimVoucherDetails) {this.details = claimVoucherDetails;}}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping package="com.sshdemo.entity"><class name="ClaimVoucher" table="biz_claim_voucher"><id name="id" type="long"><column name="id" /><generator class="native" /></id><many-to-one name="nextDealBy" class="Employee" fetch="select"><column name="next_deal_sn" length="20"><comment>待处理人</comment></column></many-to-one><many-to-one name="creator" class="Employee" fetch="select"><column name="create_sn" length="20" not-null="true"><comment>填报人</comment></column></many-to-one><property name="createTime" type="date"><column name="create_time" length="19" not-null="true"><comment>填写时间</comment></column></property><property name="event" type="string"><column name="event" not-null="true"><comment>事由</comment></column></property><property name="totalAccount" type="double"><column name="total_account" precision="10" not-null="true"><comment>总金额</comment></column></property><property name="status" type="string"><column name="status" length="20" not-null="true"><comment>状态</comment></column></property><set name="details" inverse="true"><key><column name="main_id" not-null="true"><comment>明细</comment></column></key><one-to-many class="ClaimVoucherDetail" /></set></class>
</hibernate-mapping>

创建ClaimVoucherDetail类和xml

package com.sshdemo.entity;/*** 报销申请单明细 实体类。 */
public class ClaimVoucherDetail implements java.io.Serializable {// Fieldsprivate static final long serialVersionUID = -5640087904678377183L;private long id;private ClaimVoucher master;private String item;private double account;private String desc;// Constructors/** default constructor */public ClaimVoucherDetail() {}/** full constructor */public ClaimVoucherDetail(ClaimVoucher claimVoucher, String item,double account, String desc) {this.master = claimVoucher;this.item = item;this.account = account;this.desc = desc;}// Property accessors/*** @return 编号*/public long getId() {return this.id;}public void setId(long id) {this.id = id;}/*** @return 主单*/public ClaimVoucher getMaster() {return this.master;}public void setMaster(ClaimVoucher claimVoucher) {this.master = claimVoucher;}/*** @return 项目*/public String getItem() {return this.item;}public void setItem(String item) {this.item = item;}/*** @return 金额*/public double getAccount() {return this.account;}public void setAccount(double account) {this.account = account;}/*** @return 费用说明*/public String getDesc() {return this.desc;}public void setDesc(String desc) {this.desc = desc;}}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping package="com.sshdemo.entity"><class name="ClaimVoucherDetail" table="biz_claim_voucher_detail"><id name="id" type="long"><column name="id" /><generator class="native" /></id><many-to-one name="master" class="ClaimVoucher" fetch="select"><column name="main_id" not-null="true"><comment>报销单(主单)编号</comment></column></many-to-one><property name="item" type="string"><column name="item" length="20" not-null="true"><comment>项目</comment></column></property><property name="account" type="double"><column name="account" precision="10" not-null="true"><comment>金额</comment></column></property><property name="desc" type="string"><column name="desc" length="200" not-null="true"><comment>费用说明</comment></column></property></class>
</hibernate-mapping>

6.创建com.sshdemo.dao的employeeDao接口

package com.sshdemo.dao;import java.io.Serializable;
import java.util.List;import com.sshdemo.entity.Employee;/*** DAO接口。* */
public interface EmployeeDao {/*** 添加用户* * @param employee  用户*/void add(Employee employee);/*** 根据用户Id删除对象* @param id主键*/void deleteById(Serializable id);/*** 修改用户* * @param employee用户*/void update(Employee employee);/*** 根据用户id加载对象* @param id主键* @return 返回用户对象*/Employee get(Serializable id);/*** 根据查询条件查询用户数据。* @param condition查询条件* @return 如果condition为null,返回所有用户数据,否则,使用用户名和密码查询用户数据*/List<Employee> find(Employee condition);
}

7.创建对应的实现类

package com.sshdemo.dao.hibimpl;import java.io.Serializable;
import java.util.List;import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;import com.sshdemo.dao.EmployeeDao;
import com.sshdemo.entity.Employee;/*** 这个是员工类的dao层,继承HibernateDaoSupport,可以按ctrl+F3* 可以看到这个类中包含一个getHibernateTemplate()和setHibernateTemplate()方法* 我们通过上下文配置时就已经将template用spring进行了注入,此时我们就通过* teaplate可以获取到相应的数据源,使用template进行调用对应的增删改查* */
public class EmployeeDaoHibImpl extends HibernateDaoSupport implementsEmployeeDao {/** (non-Javadoc)* * @see com.sshdemo.dao.EmployeeDao#add(com.sshdemo.entity.Employee)*/@Transactionalpublic void add(Employee employee) {HibernateTemplate hibTemp = getHibernateTemplate();// hibTemp.setFlushMode(HibernateTemplate.FLUSH_AUTO);
        hibTemp.save(employee);}/** (non-Javadoc)* * @see com.sshdemo.dao.EmployeeDao#deleteById(java.io.Serializable)*/public void deleteById(Serializable id) {super.getHibernateTemplate().delete(this.get(id));}/** (non-Javadoc)* * @see com.sshdemo.dao.EmployeeDao#update(com.sshdemo.entity.Employee)*/public void update(Employee employee) {super.getHibernateTemplate().update(employee);}/** (non-Javadoc)* * @see com.sshdemo.dao.EmployeeDao#get(java.io.Serializable)*/public Employee get(Serializable id) {return (Employee) super.getHibernateTemplate().get(Employee.class, id);}/** (non-Javadoc)* * @see com.sshdemo.dao.EmployeeDao#find(com.sshdemo.entity.Employee)*/@SuppressWarnings("unchecked")public List<Employee> find(Employee condition) {return getHibernateTemplate().find("from Employee e where e.name=? and e.password=?",new Object[] { condition.getName(), condition.getPassword() });}
}

8.在com.sshdemo.utils下定义一个MD5加密算法的类

package com.sshdemo.utils;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.MessageDigest;public class MD5 {private String inStr;//输入java.security.MessageDigest下面的一个类private MessageDigest md5;/*** 以下是一个带参数的构造函数,创建对象时就将* inStr和MessageDigest赋值* @param 杨超*/public MD5(String inStr) {this.inStr = inStr;try {this.md5 = MessageDigest.getInstance("MD5");} catch (Exception e) {System.out.println(e.toString());e.printStackTrace();}}/* 下面是关键的md5算法 */public String compute() {//将创建对象时的字符串转换成字符数组char[] charArray = this.inStr.toCharArray();//根据字符数组的长度初始化一个Byte数组byte[] byteArray = new byte[charArray.length];//将字符数组转换成byte数组for (int i = 0; i < charArray.length; i++)byteArray[i] = (byte) charArray[i];//将字节数组通过digest 计算存储在byte数组中byte[] md5Bytes = this.md5.digest(byteArray);//用它来保证线程安全StringBuffer hexValue = new StringBuffer();for (int i = 0; i < md5Bytes.length; i++) {//将每个md5Bytes进行一个或的位运算符计算,最终将其转换成二进制数字int val = ((int) md5Bytes[i]) & 0xff;if (val < 16)hexValue.append("0");hexValue.append(Integer.toHexString(val));}//返回一个字符串return hexValue.toString();}/* 下面是主函数调用 */public static void main(String[] args) {String A = null;try {System.out.println("请输入你要加密的数据:");BufferedReader br = new BufferedReader(new InputStreamReader(System.in));A = br.readLine();} catch (IOException e) {};MD5 md5 = new MD5(A);String postString = md5.compute();System.out.println("加密后的数据:" + postString);}
}

 

9.创建MVC设计模式的C层

package com.sshdemo.action;import java.util.Map;import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.sshdemo.entity.Employee;
import com.sshdemo.service.EmployeeService;
import com.sshdemo.utils.MD5;/*** 用户登录action。* */
public class UserAction extends ActionSupport {private static final long serialVersionUID = -6095372451084071851L;private Employee employee = null;private EmployeeService employeeService = null;/*** 用户登录。* * @return* @throws Exception*/public String login() throws Exception {Employee newEmployee = null;try {// 对登录密码进行MD5加密employee.setPassword(new MD5(employee.getPassword()).compute());newEmployee = employeeService.login(employee);} catch (Exception e) {this.addActionMessage(e.getMessage());}String ret = INPUT;if (newEmployee == null) {ret = INPUT;} else {Map<String, Object> session = ActionContext.getContext().getSession();session.put("employee", newEmployee);String nameCn = newEmployee.getPosition().getNameCn();if ("普通员工".equals(nameCn)) {ret = "staff";} else if ("部门经理".equals(nameCn)) {ret = "deptManager";} else if ("总经理".equals(nameCn)) {ret = "manager";} else if ("财务".equals(nameCn)) {ret = "cashier";}}return ret;}/*** 用户退出。* * @return* @throws Exception*/public String logout() throws Exception {ActionContext ac = ActionContext.getContext();ac.getSession().remove("employee");return SUCCESS;}public String register() throws Exception{String ret = "registerfail";try {// 对登录密码进行MD5加密employee.setPassword(new MD5(employee.getPassword()).compute());employeeService.register(employee);ret = "registerok";} catch (Exception e) {this.addActionMessage(e.getMessage());}return ret;}public void setEmployee(Employee employee) {this.employee = employee;}public void setEmployeeService(EmployeeService employeeService) {this.employeeService = employeeService;}public Employee getEmployee() {return employee;}public EmployeeService getEmployeeService() {return employeeService;}
}

10.创建一个ExportDb创建在各实体类中定义好的xml对应的数据库表格

package com.sshdemo.utils;import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;;
/*** 将hbm生成ddl* @author BCH**/
public class ExportDb {public static void main(String[] args) {//默认读取hibernate.cfg.xml文件Configuration cfr = new Configuration().configure();SchemaExport export = new SchemaExport(cfr);export.create(true, true);}
}

11.创建对应的jsp

login.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><h1>登录</h1><s:actionmessage /><s:form action="login"><s:textfield name="employee.name" label="用户名" /><s:password name="employee.password" label="密码" /><s:submit value="登录"></s:submit></s:form></body>
</html>
<%@ taglib prefix="s" uri="/struts-tags"%>,这里引入了一个jsp脚本的指令,定义了一个s前缀
注意:这里对应的name=employee.name;这里对应的是实体类中name和password属性
register.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><h1>注册</h1><s:actionmessage /><s:form action="register"><s:textfield name="employee.sn" label="序号" /><s:textfield name="employee.name" label="用户名" /><s:password name="employee.password" label="密码" /><s:textfield name="employee.status" label="状态" /><s:submit value="注册"></s:submit></s:form></body>
</html>

manager,jsp

 

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><title>总经理待审核页</title></head><body><h1>总经理待审核页</h1><%if (request.getSession().getAttribute("employee") != null){%><h1>${sessionScope.employee.name } 登录成功</h1><%} else {%><h1>你还没登录,请您先登录。</h1><%}%><br><a href="login.jsp">继续操作</a></body>
</html>

staff.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><title>添加报销单页面</title></head><body><h1>添加报销单页面</h1><%if (request.getSession().getAttribute("employee") != null){%><h1>${sessionScope.employee.name } 登录成功</h1><%} else {%><h1>你还没登录,请您先登录。</h1><%}%><br><a href="login.jsp">继续操作</a></body>
</html>

cashier.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><title>财务处理页</title></head><body><h1>财务处理页</h1><%if (request.getSession().getAttribute("employee") != null){%><h1>${sessionScope.employee.name } 登录成功</h1><%} else {%><h1>你还没登录,请您先登录。</h1><%}%><br><a href="login.jsp">继续操作</a></body>
</html>

deptManager.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><title>部门经理待审核页</title></head><body><h1>部门经理待审核页</h1><%if (request.getSession().getAttribute("employee") != null){%><h1>${sessionScope.employee.name } 登录成功</h1><%} else {%><h1>你还没登录,请您先登录。</h1><%}%><br><a href="login.jsp">继续操作</a></body>
</html>

运行原理以login.jsp为例:

直接在eclipse上运行即可:点击登录后—后将表单提交到action后面对应的login去—此时会去struts.xml文件里面找到name=login的action,然后就会根据class找到对应业务处理的类的位置及其对应的Method方法

—由于在jsp定义了对应的name=employee.XX它就会去找实体类对应的属性,此时它对employee就已经做了一个封装,将前端传回的参数new 成了一个对象,我们拿到对象之后,就可以对它进行一系列的操作

并返回不同的结果—此时结果又会回到struts.xml中的<result name="input">/login.jsp</result>,它会根据不同的结果判断显示出不同的结果

 

其它注册等原理一样,不再赘述

 

总结:对应SSH各部分所起到的作用:spring起一个链接的作用,使得代码之间的耦合性降低,如数据源的配置sqlSessionFactory、对应的template的注入等

  struts取代了servlet,通过jsp上的指令映射到struts配置文件,然后再映射到对应业务逻辑处理所在的位置,根据返回结果,显示出不同的视图

  Hibernate它起到的作用不用去管JDBC实现,直接对对象进行操作,最终会根据它的HQL语句对数据库实现增删改查

 

转载于:https://www.cnblogs.com/fly-boy/p/7508035.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/280449.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

听说这个语言认知服务又出新功能了?

点击上方蓝字关注我们&#xff08;本文阅读时间&#xff1a;7分钟)语言是人类智能发展的基石。鉴于语言拥有普遍性&#xff0c;几乎没有特定的技术或 AI 技术得以颠覆整个社会。微软的使命是赋能地球上的每个人和每个组织&#xff0c;帮助他们取得更多成就。立足于该使命&#…

自定义异常最佳实践_播放,自定义和组织媒体的最佳文章

自定义异常最佳实践Computers today are used for much more than generating documents, writing and receiving email, and surfing the web. We also use them to listen to music, watch movies and TV shows, and to transfer media to and from mobile devices. 如今&…

CSS中的路径裁剪样式clip-path

前面的话 CSS借鉴了SVG裁剪的概念&#xff0c;设置了clip-path样式&#xff0c;本文将详细介绍路径裁剪clip-path 概述 clip-path属性可以防止部分元素通过定义的剪切区域来显示&#xff0c;仅通过显示的特殊区域。剪切区域是被URL定义的路径代替行内或者外部svg&#xff0c;或…

macos mojave_如何修复macOS Mojave上的模糊字体(使用亚像素抗锯齿)

macos mojaveApple’s macOS Mojave disables subpixel antialiasing, also known as font smoothing, by default. On a MacBook Air or a desktop Mac hooked up to a non-Retina display, upgrading will make your fonts look worse. 苹果的macOS Mojave默认情况下禁用子像…

一个变量命名神器:支持中文转变量名

变量命名的规范&#xff0c;对于我们编程&#xff0c;大家都知道是非常重要的&#xff0c;上次给大家推荐过一个命名辅助工具《程序员还在为变量取名苦恼&#xff0c;那是因为你不知道&#xff0c;这个变量命名神器》&#xff0c;但大家一致反馈存在2个问题&#xff1a;1、网速…

1.操作系统概述

2019独角兽企业重金招聘Python工程师标准>>> 操作系统的发展过程 无操作系统的计算机系统单道批处理系统&#xff08;50年代&#xff0c;系统资源利用率低&#xff09;多道批处理系统&#xff08;60年代&#xff09;分时系统&#xff08;70年代&#xff09;实时系统…

测听hl和nhl的区别_播放NHL曲棍球的最便宜方法(无电缆)

测听hl和nhl的区别If you’re like me, you watch hockey, and…basically no other sports. You also, like me, would like to skip the cable subscription. So what’s the cheapest way to watch NHL hockey online so you can cut the cord? 如果您像我一样&#xff0c;…

使用Java实现K-Means聚类算法

2019独角兽企业重金招聘Python工程师标准>>> 关于K-Means介绍很多&#xff0c;还不清楚可以查一些相关资料。 个人对其实现步骤简单总结为4步: 1.选出k值,随机出k个起始质心点。 2.分别计算每个点和k个起始质点之间的距离,就近归类。 3.最终中心点集可以划分为…

在PowerShell中显示高级进度条

如果你需要编写一些PowerShell脚本&#xff0c;尤其在处理一些相对复杂的任务时&#xff0c;你可能希望添加进度条的功能&#xff0c;以便随时可以了解进展情况。Write-Progress 这个命令可以帮助你完成简单的需求&#xff0c;请参考官方文档即可&#xff0c;但下图一个示例&am…

当检测到运动时如何自动打开门灯

If it’s dark out and someone comes to your door, you probably can’t see them unless your porch light is on. Furthermore, if a potential burglar approaches your front door, a motion light can help scare them away. 如果天黑了&#xff0c;有人进了您的门&…

在阿里,我们如何管理测试环境

为什么80%的码农都做不了架构师&#xff1f;>>> 作者&#xff1a;林帆&#xff08;花名金戟&#xff09;&#xff0c;阿里巴巴研发效能部技术专家 相关阅读&#xff1a;在阿里&#xff0c;我们如何管理代码分支 前言 阿里的许多实践看似简单&#xff0c;背后却蕴涵…

数据库_7_SQL基本操作——表操作

SQL基本操作——表操作 建表的过程就是声明列的过程。 表与字段是密不可分的。 一、新增数据表 create table [if not exists] 表名( 字段名字 数据类型, 字段名字 数据类型 -- 最后一行不需要逗号 )[表选项];if not exists:如果表名不存在&#xff0c;那么就创建&#xff0c;…

EXT.NET 更改lable和Text的颜色

2019独角兽企业重金招聘Python工程师标准>>> &#xfeff;&#xfeff; <ext:TextField ID"TextField1" " runat"server" FieldLabel"编号" LabelWidth"60" LabelAlign"Left" LabelStyle"color:red…

ubuntu系统备份和还原_如何使用Aptik在Ubuntu中备份和还原您的应用程序和PPA

ubuntu系统备份和还原If you need to reinstall Ubuntu or if you just want to install a new version from scratch, wouldn’t it be useful to have an easy way to reinstall all your apps and settings? You can easily accomplish this using a free tool called Apti…

AppDomainManager后门的实现思路

本文讲的是AppDomainManager后门的实现思路&#xff0c;0x00 前言从Casey SmithsubTee学到的一个技巧&#xff1a;针对.Net程序&#xff0c;通过修改AppDomainManager能够劫持.Net程序的启动过程。 如果劫持了系统常见.Net程序如powershell.exe的启动过程&#xff0c;向其添加…

所有内耗,都有解药。

你是否常常会有这种感觉&#xff1a;刚开始接手一件事情&#xff0c;脑海中已经幻想出无数个会发生的问题&#xff0c;心里也已笃定自己做不好&#xff1b;即使别人不经意的一句话&#xff0c;也会浮想一番&#xff0c;最终陷入自我怀疑&#xff1b;随便看到点什么&#xff0c;…

ABAP 通过sumbit调用另外一个程序使用job形式执行-简单例子

涉及到两个程序&#xff1a; ZTEST_ZUMA02 (主程序)ZTEST_ZUMA(被调用的程序&#xff0c;需要以后台job执行)"ztest_zuma 的代码DATA col TYPE i VALUE 0.DO 8 TIMES.MESSAGE JOB HERE TYPE S.ENDDO.程序ZTEST_ZUMA是在程序ZTEST_ZUMA02中以job的形式调用的&#xff0c;先…

那些影响深远的弯路

静儿最近反思很多事情&#xff0c;不仅是当时做错了。错误定式形成的思维习惯对自己的影响比事情本身要大的多。经常看到周围的同事&#xff0c;非常的羡慕。他们都很聪明、有自己的方法。就算有些同事工作经验相对少一些&#xff0c;但是就像在废墟上创建一个辉煌的城市要比在…

如何使用APTonCD备份和还原已安装的Ubuntu软件包

APTonCD is an easy way to back up your installed packages to a disc or ISO image. You can quickly restore the packages on another Ubuntu system without downloading anything. APTonCD是将安装的软件包备份到光盘或ISO映像的简便方法。 您可以在不下载任何东西的情况…

使用 Visual Studio 2022 调试Dapr 应用程序

使用Dapr 编写的是一个多进程的程序, 两个进程之间依赖于启动顺序来组成父子进程&#xff0c;使用Visual Studio 调试起来可能会比较困难&#xff0c;因为 Visual Studio 默认只会把你当前设置的启动项目的启动调试。好在有Visual Studio 扩展&#xff08;Microsoft Child Proc…