SSH(三)——实现Service层、事务管理以及部署业务逻辑组件和实现Web层

来源:互联网 发布:白额高脚蛛淘宝 编辑:程序博客网 时间:2024/06/07 01:27

1.实现业务逻辑组件
EmployeeService.java的源代码。

    package org.coolerwu.mydo.service;    import java.util.List;    import org.coolerwu.mydo.domain.Employee;    public interface EmployeeService {        /**         * 登录失败         */        public static final int LOGIN_FAIL = 0;        /**         * 以普通员工登录         */        public static final int LOGIN_EMP = 1;        /**         * 以经理登录         */        public static final int LOGIN_MGR = 2;        /**         *          * @param user         * @param password         * @return         */        List<Employee> queryEmployee(String user, String password);    }

EmployeeServiceImpl.java的源代码。

    package org.coolerwu.mydo.service.impl;    import java.util.List;    import org.coolerwu.mydo.dao.EmployeeDao;    import org.coolerwu.mydo.domain.Employee;    import org.coolerwu.mydo.service.EmployeeService;    public class EmployeeServiceImpl implements EmployeeService{        private EmployeeDao employeeDao;        public void setEmployeeDao(EmployeeDao employeeDao) {            this.employeeDao = employeeDao;        }        @Override        public List<Employee> queryEmployee(String user, String password) {            List<Employee> l = employeeDao.queryEmployee(user, password);            return l;        }    }

其中获取数据可以用VO模式,这样便于JSON数据传输方便
EmployeeVo.java的源代码。

    package org.coolerwu.mydo.vo;    import java.io.Serializable;    public class EmployeeVo implements Serializable{        /**         *          */        private static final long serialVersionUID = 1L;        private String user;        private String password;        private double salary;        public String getUser() {            return user;        }        public void setUser(String user) {            this.user = user;        }        public String getPassword() {            return password;        }        public void setPassword(String password) {            this.password = password;        }        public double getSalary() {            return salary;        }        public void setSalary(double salary) {            this.salary = salary;        }        public EmployeeVo(String user, String password, double salary) {            super();            this.user = user;            this.password = password;            this.salary = salary;        }        public EmployeeVo() {            super();        }    }

2.事务管理以及部署业务逻辑组件
在tx:命名空间下的tx:advice元素用于配置事务增强处理,而aop:命名空间下的aop:advisor元素用于配置自动代理
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:aop="http://www.springframework.org/schema/aop"        xmlns:p="http://www.springframework.org/schema/p"        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/tx         http://www.springframework.org/schema/tx/spring-tx-4.0.xsd        http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">        <!-- 定义业务逻辑组件模板,为之注入DAO组件 -->        <bean id="employeeTemplate" abstract="true" lazy-init="true"            p:employeeDao-ref="employeeDao"/>        <!-- 定义业务逻辑组件,继承业务逻辑组件的模板 -->        <bean id="employeeService" class="org.coolerwu.mydo.service.impl.EmployeeServiceImpl"            parent="employeeTemplate"/>        <!-- 配置Hibernate的局部事务管理器,使用HibernateTransactionManager类             并注入SessionFactory的引用 -->        <bean id="transactionManager" class=        "org.springframework.orm.hibernate4.HibernateTransactionManager"        p:sessionFactory-ref="sessionFactory"/>        <!-- 配置事务增强处理Bean,指定事务管理器 -->        <tx:advice id="txAdvice" transaction-manager="transactionManager">            <!-- 用于配置详细的事务语义 -->            <tx:attributes>                <!-- 所有以'get'开头的方法是read-only的 -->                <tx:method name="get*" read-only="true"/>                <!-- 其他方法使用默认的事务设置 -->                <tx:method name="*"/>            </tx:attributes>        </tx:advice>        <aop:config>            <!-- 配置一个切入点,匹配empManager和mgrManager                两个Bean的所有方法的执行 -->            <aop:pointcut expression="bean(employeeService)" id="coolerwuPointcut"/>            <!-- 指定在leePointcut切入点应用txAdvice事务增强处理 -->            <aop:advisor advice-ref="txAdvice"                pointcut-ref="coolerwuPointcut"/>        </aop:config>    </beans>

3.实现系统Web层
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">        <!-- 定义Struts 2的核心Filter -->        <filter>            <filter-name>struts2</filter-name>            <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>        </filter>        <!-- 让Struts 2的核心Filter拦截所有请求 -->        <filter-mapping>            <filter-name>struts2</filter-name>            <url-pattern>/*</url-pattern>        </filter-mapping>        <!-- 配置Spring配置文件的位置 -->        <context-param>            <param-name>contextConfigLocation</param-name>            <param-value>/WEB-INF/classes/daoContext.xml, /WEB-INF/classes/applicationContext.xml</param-value>        </context-param>        <!-- 使用ContextLoaderListener初始化Spring容器 -->        <listener>            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>        </listener>    </web-app>

一旦Spring容器初始化完成,Struts2的Action就可通过自动装配策略来访问Spring容器中的Bean,例如Action中包含一个setA()方法,如果Spring容器中有一个id为a的bean实例,则该bean将会被自动装配给该Action。在自动装配策略下,如果不指定自动装配,则系统默认使用按byName自动装配。byName:是根据setter方法名进行自动装配。Spring容器查找容器中的全部Bean,找出id与setter方法名去掉set前缀,并小写首字母后同名的Bean来完成注入。如果没有找到匹配的Bean实例,则Spring不会进行任何注入。
struts.xml的源代码。

    <?xml version="1.0" encoding="GBK"?>    <!-- 指定Struts2配置文件的DTD信息 -->    <!DOCTYPE struts PUBLIC        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"        "http://struts.apache.org/dtds/struts-2.3.dtd">    <!-- Struts2配置文件的根元素 -->    <struts>        <!-- 配置了系列常量 -->        <constant name="struts.custom.i18n.resources" value="resource"/>        <constant name="struts.i18n.encoding" value="GBK"/>        <constant name="struts.devMode" value="true"/>        <package name="default" extends="struts-default">            <!-- 登录验证 -->            <action name="login" class="org.coolerwu.action.LoginAction">                <result>/WEB-INF/success.jsp</result>                <result name="error">/WEB-INF/failed.jsp</result>            </action>        </package>    </struts>   

EmployeeBaseAction.java的源代码。

    package org.coolerwu.action.base;    import org.coolerwu.mydo.service.EmployeeService;    import com.opensymphony.xwork2.ActionSupport;    public class EmployeeBaseAction extends ActionSupport{        /**         *          */        private static final long serialVersionUID = 1L;        protected EmployeeService eps;        public void setEmployeeService(EmployeeService eps) {            this.eps = eps;        }    }

LoginAction.java的源代码。

    package org.coolerwu.action;    import java.util.List;    import org.coolerwu.action.base.EmployeeBaseAction;    import org.coolerwu.mydo.domain.Employee;    import org.coolerwu.mydo.vo.EmployeeVo;    public class LoginAction extends EmployeeBaseAction{        /**         *          */        private static final long serialVersionUID = 1L;        private String user;        private String password;        @Override        public String execute() throws Exception {            List<Employee> l = (List<Employee>) eps.queryEmployee(user, password);            EmployeeVo vo = new EmployeeVo();            if(l.size() != 0){                for(Employee o : l){                    vo.setUser(o.getUser());                    vo.setPassword(o.getPassword());                    vo.setSalary(o.getSalary());                }                System.out.println(vo);                addActionMessage("登录成功");                return SUCCESS;            }            addActionMessage("登录失败");            return ERROR;        }        public void setUser(String user) {            this.user = user;        }        public String getUser() {            return user;        }        public void setPassword(String password) {            this.password = password;        }        public String getPassword() {            return password;        }    }

4.剩下的jsp源代码。
login.jsp源代码。

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags" %><!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>登录界面</title></head><body>    <s:form action="login">        <s:textfield name="user" value=""/>        <s:textfield name="password" value=""/>        <s:submit value="login"/>    </s:form></body></html>

success.jsp源代码。

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags" %><!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>成功</title></head><body>    <s:actionmessage/></body></html>

failed.jsp源代码。

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags" %><!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>失败</title></head><body>    <s:actionmessage/></body></html>
阅读全文
0 0