SSH(三)——實現Service層、事務管理以及部署業務邏輯組件和實現Web層

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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章