JAVA框架Struts2 servlet API

一:servlet API

1)完全解耦接口:

  使用ActionContext类进行相关操作:

 package jd.com.actioncontex;

 import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.lang.reflect.Array;
import java.util.Map;
import java.util.Set; public class actioncon extends ActionSupport{ public String getInfo(){
//获取actioncontex对象通过静态方法getcontext
ActionContext actionContext=ActionContext.getContext();
// 获取requet参数
Map<String, Object> map=actionContext.getParameters();
Set<String> k=map.keySet();
for(String i:k){
System.out.println(i);
Object[] objects= (Object[]) map.get(i);
System.out.println(Array.get(objects,));
}
//给servletcontex设置值
Map<String,Object> con=actionContext.getApplication();
con.put("oop",); // 给session设置值
Map<String,Object> session=actionContext.getSession();
session.put("oop",);
//给request设置值
actionContext.put("oop",);
return "ok";
}
}

jsp:

 <%--
Created by IntelliJ IDEA.
User: liumeide
Date: //
Time: :
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body> ${oop} ${sessionScope.oop}<br>
${applicationScope.oop}<br>
${requestScope.get("oop")}
</body>
</html>

原生servletAPI这个比较常用(直接获取相应的域对象)

通过ServletActionContext对象获取相应的域对象。

 package jd.com.or;

 import com.opensymphony.xwork2.ActionSupport;

 import org.apache.struts2.ServletActionContext;

 import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; public class or extends ActionSupport {
/**
* 原生servletAPI
* @return
* @throws Exception
*/
@Override
public String execute() throws Exception {
// 获取HttpServletResponse
HttpServletResponse httpServletResponse= ServletActionContext.getResponse();
httpServletResponse.getWriter();
// 获取HttpServletRequest对象
HttpServletRequest httpServletRequest=ServletActionContext.getRequest();
httpServletRequest.setAttribute("oop","");
// 获取session
HttpSession httpSession=httpServletRequest.getSession();
httpSession.setAttribute("oop","oopsdadad");
return SUCCESS;
}
}
上一篇:2018牛客网暑假ACM多校训练赛(第三场)D Encrypted String Matching 多项式 FFT


下一篇:从MVC到前后端分离