标签:
主要就是接收表单参数及向域对象中存取值.
关于SevletAPI的方法在Action中有三种方式:
1.完全解耦合的形式:
* 使用一个类:ActionContext.
* static ActionContext getContext(); --- 获得ActionContext对象
* Map getParameters(); --- 接收提交到Action中的参数.
* Map getSession(); --- 获得Session的Map.
* Map getApplication(); --- 获得Application的Map.
* void put(String key,Object value); --- 向request中存值.
* Object get(String key); --- 从request中获得值.
* 代码实现:
// 获得ActionContext对象
ActionContext context = ActionContext.getContext();
// 获得表单提交参数:
Map<String,Object> map = context.getParameters();
String[] username = (String[]) map.get("username");
System.out.println(username[0]);
String[] password = (String[]) map.get("password");
System.out.println(password[0]);
// 向request域中存值
context.put("reqName", "reqValue");
System.out.println("request域中的值:"+context.get("reqName"));
// 向session域中存值
context.getSession().put("sessName", "sessValue");
System.out.println("session域中的值:"+context.getSession().get("sessName"));
// 向ServletContext中存值
context.getApplication().put("appName", "appValue");
System.out.println("application域中的值:"+context.getApplication().get("appName"));
2.使用接口注入的方式:
* 实现接口:
* ServletRequestAware
* ServletResponseAware
* ServletContextAware
* 代码实现:
public class RequestAction2 extends ActionSupport implements ServletRequestAware,ServletContextAware{
private HttpServletRequest request;
private ServletContext context;
@Override
public String execute() throws Exception {
// 1.接收参数:
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username +" "+password);
// 2.向request域中存值:
request.setAttribute("reqName", "李健");
// 3.向session域中存值:
request.getSession().setAttribute("sessName", "凤姐");
// 4.向application域中存值.
context.setAttribute("appName", "芙蓉");
return SUCCESS;
}
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
public void setServletContext(ServletContext context) {
this.context = context;
}
}
3.使用ServletActionContext中静态方法:
方法:
* getRequest();
* getResponse();
* getServetContext();
代码:
// 1.接收参数:
HttpServletRequest request = ServletActionContext.getRequest();
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username+" "+password);
// 2.向request域中存值:
request.setAttribute("reqName", "小健健");
// 3.向session域中存值:
request.getSession().setAttribute("sessName", "小凤凤");
// 4.向application中存值:
ServletActionContext.getServletContext().setAttribute("appName", "小蓉蓉");
***** 第一种方式是最好的!习惯第三种用的很方便.
标签:
原文地址:http://www.cnblogs.com/jiemoxiaodi/p/5621917.html