博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Struts2获取request三种方法
阅读量:6942 次
发布时间:2019-06-27

本文共 1859 字,大约阅读时间需要 6 分钟。

  hot3.png

复习啊..

     struts2里面有三种方法可以获取request,最好使用ServletRequestAware接口通过IOC机制注入Request对象。
  • 在Action中获取request方法一:
 
在Action中的代码:
Map request = (Map)ActionContext.getContext().get("request");List
tasks = taskManager.findAll();request.put("tasks", tasks);

 
在JSP页面中获取其中的值:

--------------------------------------------------------------------------------------------
  • 方法二:通过ServletActionContext类来获取,使用struts2经验如果处理get传参是中文,只能使用该方法进行处理乱码问题
 
Action中代码:
HttpServletRequest request = ServletActionContext.getRequest();request.setAttribute("username", "zhangsan");

 
在jsp中获取其中的值
 
或者${requestScope.req}

-------------------------------------------------------------------------------------------- 
  • 方法三:通过ServletRequestAware接口通过IOC机制注入Request对象
Action中的代码:
Action实现ServletRequestAware接口,实现接口中的方法
     
private HttpServletRequest request;     //实现接口中的方法     public void setServletRequest(HttpServletRequest request){      this.request = request;     }     //然后在execute()方法中就可以使用了     public String execute(){      request.setAttribute("username", "zhangsan");      request.getSession().getServletContext().getApplication(); //得到Application     }

     该方法必须要实现,而且该方法是自动被调用
     这个方法在被调用的过程中,会将创建好的request对象通过参数的方式传递给你,你可以用来赋给你本类中的变量,然后request就可以使用了
     
注意:setServletRequest()方法一定会再execute()方法被调用前执行
 
在jsp页面中获取其中的值

在上面的代码中, 在Action实现了一个 ServletRequestAware接口,并且实现了 setServletRequest方法。

如果一个动作类实现了 ServletRequestAware接口, Struts2在调用 execute方法之前,就会先调用setServletRequest方法,并将Request参数传入这个方法。如果想获得 HttpServletResponse、HttpSession和 Cookie等对象,动作类可以分别实现 ServletResponseAware、 SessionAware和CookiesAware等接口。这些接口都在 org.apache.struts2.interceptor包中。

struts2超链接传值: <s:a href="info.action?id=%{#list.id}"> <s:property value="#list.title"/></s:a>

转载于:https://my.oschina.net/i33/blog/50644

你可能感兴趣的文章
parcel初体验
查看>>
强行来一波Dagger2使用介绍
查看>>
区块链100讲:零知识证明算法之zkSNARKs
查看>>
cloud
查看>>
Vue递归组件+Vuex开发树形组件Tree--递归组件
查看>>
ffmpeg 视频压缩
查看>>
你应该知道的JS: reduce的n种应用
查看>>
Juniper防火墙配置
查看>>
PHP编码规范(PSR-3)-日志接口规范
查看>>
人生职业规划
查看>>
Servlet,Filter,Listener,Interceptor的作用和区别
查看>>
VC中Ansi、Unicode、UTF8字符串之间的转换和写入文本
查看>>
北京邮电大学加入ONOS 系国内首个高校成员单位
查看>>
Binder进程间通信(附)---- binder结构体说明
查看>>
linux下安装jdk环境变量
查看>>
Ubuntu 安装 mysql
查看>>
java Map 一个key其实可以保存多个value
查看>>
Bootstrap-Select 动态加载数据的小记
查看>>
Python中re的match、search、findall、finditer区别
查看>>
spring中scope作用域
查看>>