博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring+springMvc+struts的SSH框架整合
阅读量:5854 次
发布时间:2019-06-19

本文共 29984 字,大约阅读时间需要 99 分钟。

1.建立一个web项目

2.导入SSH框架所需jar包

 

3.配置web.xml文件

SSHDemo
login.jsp
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
contextConfigLocation
classpath:applicationContext.xml
org.springframework.web.context.ContextLoaderListener
OpenSessionInViewFilter
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
OpenSessionInViewFilter
*.action
struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
struts2
/*
25

4.配置applicationContext.xml文件

org.hibernate.dialect.MySQLDialect
true
true
classpath:com/sshdemo/entity/

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

package com.sshdemo.entity;/** * 员工 实体类。  */public class Employee implements java.io.Serializable {    // Fields    private 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文件

package com.sshdemo.entity;/** * 部门 实体类。  */public class Department implements java.io.Serializable {    // Fields    private 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;    }}
部门经理
部门名称

创建Dictionary

package com.sshdemo.entity;/** * 数据字典 实体类。  */public class Dictionary implements java.io.Serializable {    // Fields    private 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;    }}

创建positon类和xml

package com.sshdemo.entity;/** * 职务 实体类。  */public class Position implements java.io.Serializable {    // Fields    private 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;    }}
职务名称(中文)
职务名称(英文)

创建CheckResult类和xml文件

package com.sshdemo.entity;import java.util.Date;/** * 审核结果 实体类。  */public class CheckResult implements java.io.Serializable {    // Fields    private 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;    }}
单据类型
单据编号
审核时间
审核类型
审核人
审核结果
审核意见

创建ClaimVoucher类

package com.sshdemo.entity;import java.util.Date;import java.util.HashSet;import java.util.Set;/** * 报销申请单 实体类。  */public class ClaimVoucher implements java.io.Serializable {    // Fields    private 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
details = new HashSet
(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
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
getDetails() { return this.details; } public void setDetails(Set
claimVoucherDetails) { this.details = claimVoucherDetails; }}
待处理人
填报人
填写时间
事由
总金额
状态
明细

创建ClaimVoucherDetail类和xml

package com.sshdemo.entity;/** * 报销申请单明细 实体类。  */public class ClaimVoucherDetail implements java.io.Serializable {    // Fields    private 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;    }}
报销单(主单)编号
项目
金额
费用说明

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
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 implements        EmployeeDao {    /*     * (non-Javadoc)     *      * @see com.sshdemo.dao.EmployeeDao#add(com.sshdemo.entity.Employee)     */    @Transactional    public 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
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
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"%>            登录                

登录

<%@ 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"%>            注册                

注册

manager,jsp

 

<%@ page language="java" pageEncoding="UTF-8"%>            总经理待审核页            

总经理待审核页

<% if (request.getSession().getAttribute("employee") != null){ %>

${sessionScope.employee.name } 登录成功

<% } else { %>

你还没登录,请您先登录。

<% } %>
继续操作

staff.jsp

<%@ page language="java" pageEncoding="UTF-8"%>            添加报销单页面            

添加报销单页面

<% if (request.getSession().getAttribute("employee") != null){ %>

${sessionScope.employee.name } 登录成功

<% } else { %>

你还没登录,请您先登录。

<% } %>
继续操作

cashier.jsp

<%@ page language="java" pageEncoding="UTF-8"%>            财务处理页            

财务处理页

<% if (request.getSession().getAttribute("employee") != null){ %>

${sessionScope.employee.name } 登录成功

<% } else { %>

你还没登录,请您先登录。

<% } %>
继续操作

deptManager.jsp

<%@ page language="java" pageEncoding="UTF-8"%>            部门经理待审核页            

部门经理待审核页

<% if (request.getSession().getAttribute("employee") != null){ %>

${sessionScope.employee.name } 登录成功

<% } else { %>

你还没登录,请您先登录。

<% } %>
继续操作

运行原理以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

你可能感兴趣的文章
聊聊 TCP 长连接和心跳那些事
查看>>
MacBook 最佳实践
查看>>
flutter笔记5 官方资料搬运-安卓客户端打包
查看>>
浅谈首屏渲染速度及defer和async的异同
查看>>
JDBC数据库连接池实现
查看>>
3 Java NIO Buffer-翻译
查看>>
adb通信协议分析以及实现(三):adb网络通信部分解析
查看>>
从Windows到Linux
查看>>
CSS常用Mixin封装
查看>>
Java IO之NIO
查看>>
字符串replace方法的使用
查看>>
算法(二):分而治之
查看>>
Mac OS X系统常用工具
查看>>
[译] 用 git flow 来让 git workflow 自动化
查看>>
MVP实战心得(五) Toolbar封装优化,放弃butterknife
查看>>
简单的交叉熵损失函数,你真的懂了吗?
查看>>
前端SEO小结
查看>>
boolean?
查看>>
vuecli3.0和ts踩坑
查看>>
25_underscore.js_isArrayLike
查看>>