代码演示在action类中使用servlet的API
struts.xml配置
<?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="default" namespace="/" extends="struts-default">
<!-- 全局result -->
<global-results>
<result name="success">/main.html</result>
</global-results>
<!-- 不写method直接执行action类中的execute方法 -->
<action name="demoAction" class="web.action.ActionDemo1"/>
<action name="userAction_*" class="web.action.UserAction" method="{1}">
<result name="msg">/retMsg.jsp</result>
</action>
</package>
</struts>
action类
public class UserAction extends ActionSupport {
/**
*
* 1.通过ActionContext类使用servlet的API(完全解耦合方式)
* 2.通过servletACtionContext类使用原生servlet的API
* @return
*/
public String doReg() {
/*
* 1.通过ActionContext类使用servlet的API(完全解耦合方式)
*/
//获得action上下文
ActionContext actionContext = ActionContext.getContext();
//获得页面参数
Map<String, Object> map = actionContext.getParameters();
Set<String> keyset = map.keySet();
for (String key : keyset) {
//这里返回的应该是一个字符串数组,需要强转一下
String[] vals = (String[]) map.get(key);
System.out.println(key + ":" + vals[0]);
}
//获得session域的map集合
Map<String, Object> session = actionContext.getSession();
session.put("sessionText", "sessionText");
//获得application域的map集合
Map<String, Object> application = actionContext.getApplication();
application.put("applicationText", "applicationText");
//写入request域
actionContext.put("requestText", "requestText");
/*
* 2.通过servletACtionContext类使用原生servlet的API,不再演示。。
*
*/
/*
PageContext pageContext = ServletActionContext.getPageContext();
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
ServletContext servletContext = ServletActionContext.getServletContext();
//获得域对象后就可以使用servlet的API了。。。
*/
return "msg";
}