标签:
Struts对数据操作方式一:直接拿到servletAPI,执行操作
@Override public String execute() throws Exception { HttpServletRequest request = ServletActionContext.getRequest(); HttpSession session = request.getSession(); ServletContext application = ServletActionContext.getServletContext(); request.setAttribute("request_data","request_data"); session.setAttribute("session_data","session_data"); application.setAttribute("application_data","application_data"); return SUCCESS; }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <package name="data" namespace="/" extends="struts-default"> <global-results> <result name="success">/data.jsp</result> </global-results> <action name="data" class="com.cx.Data.DataAction"> </action> </package> </struts>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>data</title> </head> <body> data <br> ${request_data} <br> ${session_data} <br> ${application_data} </body> </html>
方式二:通过ActionContext类-解耦方式-不引入servelt-api
//方式二 ActionContext ac = ActionContext.getContext(); Map<String , Object> request = ac.getContextMap(); Map<String, Object> session = ac.getSession(); Map<String ,Object> application = ac.getApplication(); request.put("request_data","request_data"); session.put("session_data","session_data"); application.put("application_data","application_data");
方式三:实现接口
package com.cx.Data; import com.opensymphony.xwork2.ActionSupport; import org.apache.struts2.interceptor.ApplicationAware; import org.apache.struts2.interceptor.RequestAware; import org.apache.struts2.interceptor.SessionAware; import java.util.Map; /** * Created by cxspace on 16-7-10. */ public class DataAction extends ActionSupport implements RequestAware , SessionAware ,ApplicationAware{ private Map<String,Object> request; private Map<String,Object> application; private Map<String,Object> session; /* 1.请求数据封装 2.调用service层处理业务逻辑,拿到结果数据 3.数据保存到域中 Struts对数据操作方式一:直接拿到servletAPI,执行操作 */ @Override public String execute() throws Exception { request.put("request_data","request_data-方式三"); session.put("session_data","session_data-方式三"); application.put("application_data","application_data-方式三"); return SUCCESS; } @Override public void setRequest(Map<String, Object> request) { //struts运行的时候,会把代表request的map对象注入 this.request = request; } @Override public void setApplication(Map<String, Object> application) { this.application = application; } @Override public void setSession(Map<String, Object> session) { this.session = session; } }
总结
方式1:直接通过ServletActionContext获取servelt-api
方式2:通过ActionContext获取不同的map
方式3:实现接口的方法
方式2 vs 方式3
方式2适合业务方法少的
方式3适合业务方法多的
标签:
原文地址:http://www.cnblogs.com/cxspace/p/5657311.html