注意:
完全解耦合的方式,这种方式只能获得代表request、session、application的数据的Map集合。
不能操作这些对象的本身的方法。
1 jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h1>Struts2访问Servlet的PAI</h1> <h3>方式一:完全解耦合方式</h3> <form action="${pageContext.request.contextPath }/requestDemo1.action" method="post"> 姓名:<input type="text" name="name" /><br/> 密码:<input type="password" name="password"/><br/> <input type="submit" value="提交" > </form> </body> </html>
2 Action类
package com.itheima.struts2.demo1; import java.util.Arrays; import java.util.Map; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; /** * 访问ServletAPI的方式一:完全解耦合的方式 * @author 李腾 * */ public class RequestDemo1 extends ActionSupport{ public String execute() throws Exception{ //接收参数 //利用Struts2中的ActionContext对象 ActionContext context = ActionContext.getContext(); //调用ActionContext中的方法,类似于request.getParameterMap(); Map<String,Object> map = context.getParameters(); for (String key : map.keySet()) { String[] values =(String[])map.get(key); System.out.println(key+" "+Arrays.toString(values)); } //二、向域对象中存入数据 context.put("reqName", "reqValue");//相当于request.setAttribute(); context.getSession().put("sessName", "sessValue");//相当于session.setAttribute(); context.getApplication().put("appName", "appValue");//相当于application.setAttribute(); return SUCCESS; } }
3 配置文件
<?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="demo1" extends="struts-default" namespace="/"> <action name="requestDemo1" class="com.itheima.struts2.demo1.RequestDemo1" method=""> <result name="success">/demo1/demo2.jsp</result> </action> </package> </struts>
4 success跳转JSP
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>显示数据</title> </head> <body> <h1>显示数据</h1> ${reqName } ${sessName } ${appName } </body> </html>