5.struts2中Action类中获取ServletAPI的三种方式
2021-02-11 00:17
阅读:504
YPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
标签:def str print content ext.get struts doctype term author
**Servlet的API的访问(开发中偶尔会使用到)** 1.在Action类中也可以获取到Servlet一些常用的API,有如下三种方式获取 * 完全解耦合的方式 * 使用接口注入的方式 * 使用ServletActionContext中静态方法直接访问Servlet的API * 需求:提供JSP的表单页面的数据,在Action中使用Servlet的API接收到,然后保存到三个域对象中,最后再显示到JSP的页面上。 * 提供JSP注册的页面,演示下面这三种方式:2.完全解耦合的方式 * 如果使用该种方式,Struts2框架中提供了一个类,ActionContext类,该类中提供一些方法,通过方法获取Servlet的API * 一些常用的方法如下: * static ActionContext getContext() -- 获取ActionContext对象实例 * java.util.Map注册页面
demo4.jsp:
Insert title here 注册页面(完全解耦合的方式)
注册页面(接口注入的方式)
通过ServletActionContext对象的方式
struts_demo4.xml:
/demo4/success.jsp /demo4/success.jsp /demo4/success.jsp
Action:
package demo4;
import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
* 完全解耦合的方式
* @author mjl
*
*/
public class UserAction extends ActionSupport{
public String regist(){
//接收表单的数据
//先获取到ActionContext对象
ActionContext context=ActionContext.getContext();
//获取请求的参数
Map map = context.getParameters();
//通过Key获取值
String[] username=(String[]) map.get("username");
String[] password=(String[]) map.get("password");
System.out.println("用户名:"+username[0]+",密码:"+password[0]);
//获取session
Map sessionMap = context.getSession();
//像该map存入具体的值
sessionMap.put("sessName", "美美");
return SUCCESS;
}
}
package demo4;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction2 extends ActionSupport implements ServletRequestAware{
private HttpServletRequest request;
public void setServletRequest(HttpServletRequest request) {
this.request=request;
}
public String regist(){
String username=request.getParameter("username");
request.getSession().setAttribute("sessName", username);
return SUCCESS;
}
}
package demo4;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
* 采用servletActionContext对象的方法
* @author mjl
*
*/
public class UserAction3 extends ActionSupport{
public String regist(){
HttpServletRequest request = ServletActionContext.getRequest();
String username=request.getParameter("username");
request.getSession().setAttribute("sessName", username);
return SUCCESS;
}
}
5.struts2中Action类中获取ServletAPI的三种方式
标签:def str print content ext.get struts doctype term author
原文地址:https://www.cnblogs.com/syj1993/p/8509368.html
文章来自:搜素材网的编程语言模块,转载请注明文章出处。
文章标题:5.struts2中Action类中获取ServletAPI的三种方式
文章链接:http://soscw.com/essay/53802.html
文章标题:5.struts2中Action类中获取ServletAPI的三种方式
文章链接:http://soscw.com/essay/53802.html
评论
亲,登录后才可以留言!