package com.hd.action; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.http.HttpServlet; import javax.servlet.http.Htt... ...
package com.hd.action; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionContext; /** * 獲取web對象 * 1.通過非IOC方式獲取 * 1)直接方式獲取web對象 * 2)間接方式獲取web對象 * @author think * */ public class UserAction { public String add(){ /* * 1).直接方式獲取 * 通過類ServletActionContext調用提供的方法獲取 */ //獲取request對象 HttpServletRequest req = ServletActionContext.getRequest(); //獲取session對象 HttpSession session = req.getSession(); //獲取response HttpServletResponse res = ServletActionContext.getResponse(); //獲取applicationContext ServletContext appc = ServletActionContext.getServletContext(); //獲取jsp頁面傳過來的參數 String username = req.getParameter("username"); String pwd = req.getParameter("pwd"); System.out.println("賬號:" + username); System.out.println("密碼:" + pwd); //往jsp頁面傳值 req.setAttribute("msg", "來自req中的數據"); session.setAttribute("msg", "來自session中的數據"); appc.setAttribute("msg", "來自applicationContext中的數據"); return "success"; } public String update(){ /* * 2)間接方式獲取 * 一般用來存儲數據 */ //獲取request對象 ActionContext req = ActionContext.getContext(); //獲取session對象 Map<String, Object> session = req.getSession(); //獲取applicationContext Map<String, Object> appc = req.getApplication(); req.put("msg", "間接方式獲取req"); session.put("msg", "間接方式獲取session"); appc.put("msg", "間接方式獲取ApplicationContext"); return "success"; } }