搭建环境:

引入jar包,src下建立struts.xml文件

项目配置文件web.xml.

web.xml:

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>struts2Test</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list> <filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter> <filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping> </web-app>

struts.xml:

 <?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>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" /> <package name="default" namespace="/gys" extends="struts-default">
<action name="test" class="action.GetServletAPIAction">
<result name="api">/servletApi.jsp</result>
</action>
</package>
</struts>

Struts2的Action类并不直接与任何Servlet API耦合,这是Struts2的一个改良之处,因为Action类不在于Servlet API耦合,从而能更轻松地测试该Action.

Web中通常访问Servlet API就是HttpServletRequest,HttpSession和ServletContext,这3个类分别代表JSP内置对象中的request,session,application.

Struts2提供了一个ActionContext类来访问API,

该类提供了几个常用的方法:

Object get(Object key):该方法类似于调用HttpServletRequest的getAttribute(String name)方法.

Map getApplication():返回一个Map对象,该对象模拟了ServletContext实例.

static ActionContext getContext():静态方法,获取系统的ActionContext实例.

Map getParameters():获取所有的请求参数.类似于调用HttpServletRequest对象的getParameterMap方法.

Map getSession()返回一个Map对象,模拟了HttpSession实例.

void setApplication(Map application)直接传入一个Map实例,将该Map实例里的key-value转换成application的属性名,属性值.

void setSession(Map session)直接传入一个Map实例,将该Map实例里的key-value转换成session的属性名,属性值.

建立action类:

 package action;

 import com.opensymphony.xwork2.ActionContext;

 public class GetServletAPIAction {
private String name;
private String pass;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
} public void getServletAPI1(){
//获取ActionContext实例,通过该实例访问Servlet API
ActionContext ctx=ActionContext.getContext();
//获取ServletContext里的count属性
Integer count=(Integer)ctx.getApplication().get("count");
if(count==null){
count=1;
}
else {
count++;
}
//将访问人数设置成application的一个属性
ctx.getApplication().put("count", count);
ctx.getSession().put("username", "思思博士"); } public String execute(){
getServletAPI1();
return "api";
} }

建立页面servletApi.jsp:

 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head> <body>
<h1>访问次数:${applicationScope.count }</h1>
<h1>登陆人:${sessionScope.username }</h1>
</body>
</html>

测试一下:

虽然Struts2提供了ActionCotext来访问Servlet API,但这种访问毕竟不能直接获得Servlet API实例,为了在Action中直接访问Servlet API,struts2还提供了如下系统接口.

ServletContextAware:实现该接口的Action可以直接访问web应用的ServletContext实例.

ServletRequestAwart:实现该接口的Action可以直接访问用户请求的HttpServletRequest实例

ServletResponseAware:实现该接口的Action可以直接访问服务器响应的HttpServletResponse实例.

下面以ServletRequestAware为例,介绍如何在Action中访问HttpServletRequest对象.

修改上面的代码:

ServletApi.jsp

 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head> <body>
<%-- <h1>访问次数:${applicationScope.count }</h1>
<h1>登陆人:${sessionScope.username }</h1> --%>
<h3>${requestScope.API }</h3>
</body>
</html>

GetServletAPIAction.java

package action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware; import com.opensymphony.xwork2.ActionContext; public class GetServletAPIAction implements ServletRequestAware{
private HttpServletRequest request; private String name;
private String pass;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
} public void getServletAPI1(){
//获取ActionContext实例,通过该实例访问Servlet API
ActionContext ctx=ActionContext.getContext();
//获取ServletContext里的count属性
Integer count=(Integer)ctx.getApplication().get("count");
if(count==null){
count=1;
}
else {
count++;
}
//将访问人数设置成application的一个属性
ctx.getApplication().put("count", count);
ctx.getSession().put("username", "思思博士"); }
public void getServletAPI2(){
request.setAttribute("API","我来自于struts2中直接访问servletAPI的request");
} @Override
public void setServletRequest(HttpServletRequest request) {
this.request=request;
}
public String execute(){
//getServletAPI1();
getServletAPI2();
return "api";
} }

测试结果:

struts2访问servlet API的更多相关文章

  1. 配置Struts2及Struts2访问servlet api的方式

    Struts2的起源与背景 在很长的一段时间内,在所有的MVC框架中,Struts1处于绝对的统治地位,无论是从市场的普及范围,还是具体的使用者数量. 其他MVC框架都无 法与其相比,作为一一款优秀的 ...

  2. Struts2访问Servlet API的三种方式

    有时我们需要用到Request, Response, Session,Page, ServletContext这些我们以前常用的对象,那么在Struts2中怎么样使用到这些对象呢,通常有三种方式. * ...

  3. Struts2访问Servlet API的几种方式

    struts2提供了三种方式访问servlet API:大致分为两类 1. ActionContext:  public static ActionContext getContext() :获得当前 ...

  4. 3.struts2访问Servlet API,并和mybaits实现全套增删改查

    1.创建数据库脚本userinfo.sql prompt PL/SQL Developer import file prompt Created on 2016年5月19日 by pc set fee ...

  5. struts2 笔记01 登录、常用配置参数、Action访问Servlet API 和设置Action中对象的值、命名空间和乱码处理、Action中包含多个方法如何调用

    Struts2登录 1. 需要注意:Struts2需要运行在JRE1.5及以上版本 2. 在web.xml配置文件中,配置StrutsPrepareAndExecuteFilter或FilterDis ...

  6. struts2中访问servlet API

    Struts2中的Action没有与任何Servlet API耦合,,但对于WEB应用的控制器而言,不访问Servlet API几乎是不可能的,例如需要跟踪HTTP Session状态等.Struts ...

  7. struts2的action访问servlet API的三种方法

    学IT技术,就是要学习... 今天无聊看看struts2,发现struts2的action访问servlet API的三种方法: 1.Struts2提供的ActionContext类 Object g ...

  8. Struts2(七) Struts2访问Servlet的API

    当接受表单参数,向页面保持数据时.要用到Struts访问Servlet 的API .下面只做参考,有错误或不同意见可以发送邮箱2440867831@qq.com  .建议大家看struts文档,源代码 ...

  9. 关于Struts2自动装配和访问Servlet API

    自动装配 1.根据属性的getter和setter获取值  index.jsp <s:form action="hello" method="POST"& ...

随机推荐

  1. javascript中href和replace比较

      在使用javascript的时候,有时候对于经常使用的方法太熟悉而忽略了他们之间原理的细微差别.举例如下:window.location.href,window.location.replace. ...

  2. Windows 8.1 系统上用Oracle VM VirtualBox 安装windows 2008 R2 SP1 的虚拟机 出现 Error Code: 0x000000C4

    Windows 8.1 本来可以安装Hyper-v来安装虚拟机,但是我现在需要使用Oracle VM VirtualBox来安装虚拟机, 所以必须先卸载Hyper-v VirtualBox 安装的虚拟 ...

  3. 删除Android自带软件方法及adb remount 失败解决方案

    删除Android自带软件方法 1.在电脑上打开cmd,然后输入命令 adb remount adb shell su 2.接着就是Linux命令行模式了,输入 cd system/app 3然后输入 ...

  4. UI-UIImageView和Image的区别

    1.UIImageView图片视图控件 继承于UIView 用于显示图片在应用程序中 2.UIImage 是将真实图片文件转化为程序中的图片,然后3.UIImageView是Image的载体,负责显示 ...

  5. Python基础教程【读书笔记】 - 2016/7/31

    希望通过博客园持续的更新,分享和记录Python基础知识到高级应用的点点滴滴! 第十波:第10章  充电时刻 Python语言的核心非常强大,同时还提供了更多值得一试的工具.Python的标准安装包括 ...

  6. php定时执行脚本

    php定时执行脚本 ignore_user_abort(); // run script. in background set_time_limit(0); // run script. foreve ...

  7. 【java】之转码

    GBK->UTF-8 String str = "任意字符串"; str = new String(str.getBytes("gbk"),"u ...

  8. PHP Socket 编程详解

    PHP中的实现 服务端 <?php set_time_limit(0); // 设置主机和端口 $host = "127.0.0.1"; $port = 12387; // ...

  9. C#学习笔记四: C#3.0自动属性&匿名属性及扩展方法

    前言 这一章算是看这本书最大的收获了, Lambda表达式让人用着屡试不爽, C#3.0可谓颠覆了我们的代码编写风格. 因为Lambda所需篇幅挺大, 所以先总结C#3.0智能编译器给我们带来的诸多好 ...

  10. cmd命令行给main传参数

    int main(int argc, char **argv) { cout << "arguments passed to main() : " << e ...