创建Action层
Action层,引用对应的Service层,在Action层这里可以结合Struts的配置文件,跳转到指定的页面,当然也可以接受页面传递过来的请求数据,也可以做一些计算处理。
1. 创建Action层(以用户登录为例)
1.1 文件结构
1.2 UserAction.java
package cn.itcast.web.action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import cn.itcast.domain.User;
import cn.itcast.service.UserService;
public class UserAction extends ActionSupport implements ModelDriven<User>{
private User user = new User();
private UserService userService ;
public void setUserService(UserService userService) {
this.userService = userService;
}
public String login() throws Exception {
//1 调用Service执行登陆逻辑
User u = userService.getUserByCodePassword(user);
//2 将返回的User对象放入session域
ActionContext.getContext().getSession().put("user",u);
//3 重定向到项目首页
return "toHome";
}
@Override
//实现接口 ModelDriven<User>,将用户输入的信息封装到实体类中
public User getModel() {
return user;
}
}
1.3 在struts.xml配置Action交由spring容器来创建
<!-- # struts.objectFactory = spring 将action的创建交给spring容器
struts.objectFactory.spring.autoWire = name spring负责装配Action依赖属性 -->
<constant name="struts.objectFactory" value="spring"></constant>
1.4 在struts.xml配置刚刚创建的UserAction.java活动
<!-- ========================================配置struts活动 ================================================== -->
<package name="crm" namespace="/" extends="struts-default">
<global-exception-mappings>
<exception-mapping result="error" exception="java.lang.RuntimeException"></exception-mapping>
</global-exception-mappings>
<!-- 整合方案1:class属性上仍然配置action的完整类名
struts2仍然创建action,由spring负责组装Action中的依赖属性
-->
<!-- 整合方案2:class属性上填写spring中action对象的BeanName 完全由spring管理action生命周期,包括Action的创建
注意:需要手动组装依赖属性 -->
<action name="UserAction_*" class="userAction" method="{1}">
<result name="toHome" type="redirect">/index.htm</result>
<result name="error">/login.jsp</result>
</action>
</package>
对于其中的:
<global-exception-mappings>
<exception-mapping result="error" exception="java.lang.RuntimeException"></exception-mapping>
</global-exception-mappings>
简单点就是声明全局异常列表,里面详细到每一种可能抛出的异常的子类,详情可以参考本人的一篇转自别人的博文,里面有详细的说明:
http://blog.csdn.net/weixin_37820901/article/details/78992670
1.5 在applicationContext.xml中创建刚刚创建的UserAction.java对象。
<!-- ==========================配置struts2的action对象都由spring进行创建================================= -->
<!-- 注意:Action对象作用范围一定是多例的.这样才符合struts2架构 -->
<bean name="userAction" class="cn.itcast.web.action.UserAction" scope="prototype">
<property name="userService" ref="userService"></property>
</bean>