SSH5

来源:互联网 发布:《网络黑白》 编辑:程序博客网 时间:2024/05/19 00:50
在逻辑层之前,我们已经使用了hibernate框架和spring框架,现在要写的表现层需要用到struts框架,我们知道,在struts框架中,类实例的建立是由struts框架来完成的,现在action实例仍然由struts框架创建,但是action类需要service层的类作为属性,这时将这个任务交给spring框架,需要在lib文件夹中添加struts-spring插件(附件),这个插件使用自动装配的方式,比如在spring配置文件中有bean名字叫做ms;引入该插件后,在action中属性名需要叫ms,这样通过反射机制spring就可以代替struts实现自动装配。
通常情况下,我们会在action的文件夹下建立子文件夹base,里面是基础action,action中是这些基础action的子类,如下:
package org.atm.action.base;
import com.opensymphony.xwork2.ActionSupport;

import org.atm.service.*;
public class AtmBaseAction extends ActionSupport
{
protected AtmService atmService;
  public void setAtmService(AtmService atmService)
{
  this.atmService= atmService;
}

}

package org.atm.action;
import org.atm.vo.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.opensymphony.xwork2.*;

import org.apache.struts2.interceptor.*;
import org.atm.po.*;
import org.atm.action.base.*;
import org.atm.service.*;


public class GetMoneyAction extends AtmBaseAction{
private String money;
    private String tip;
public String getMoney() {
return money;
}

public void setMoney(String money) {
this.money = money;
}
public void setTip(String tip)
{
this.tip=tip;
}
public String getTip()
{
return tip;
}
public String execute() throws Exception
{
ActionContext ctx=ActionContext.getContext();
String cardNumber=(String)ctx.getSession().get("cardnumber");
String atm_id=(String)ctx.getSession().get("atmid");
System.out.println(cardNumber);
System.out.println(atm_id);
System.out.println(getMoney());
setTip(atmService.getMoney(cardNumber,Double.parseDouble(getMoney()),Integer.parseInt(atm_id)));
if(getTip().equals("正在出钞"))
return SUCCESS;
else
return ERROR;

}
}
实际上,base中的action对应的是service层,一般情况下,service层有几个类,action的base文件夹中就对应几个类。其他类有这些类派生。
至于struts配置文件,与正常无异,不在赘述。
最后仅仅需要配置web.xml文件即可。
<?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">
  <display-name></display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>

  <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>


   <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<!-- 使用ContextLoaderListener初始化Spring容器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
 
  </web-app>
在web.xml中,声明使用struts拦截器,同时使用spring的IOC功能,至此后端代码全部完毕。

原创粉丝点击