简介
之前学习的时候,后端代码通过获取root栈或者map栈,将值放进去,就等于放入了域中
然后在前端jsp页面通过ognl表达式或者el表达式将值取出来,root栈和map栈前面博客有介绍.
后来学ssm的时候,值也都是通过放在request域,session域,application域中,然后前端页面
再从域中取值,即通过如下方式存放数据
ServletActionContext.getRequest().setAttribute("name", "request数据");
ServletActionContext.getRequest().getSession().setAttribute("name", "session数据");
ServletActionContext.getServletContext().setAttribute("name", "applicatio数据");
从而导致我长期认为如果在后端代码中不通过如上方法把值放入域中,前端页面是取不到值的,在struts2框架中,
我也一直这样认为:要想从前端页面取值,值必须现在action类中通过如上代码人为的被放入域中,然后前端页面才可以从域中取值.
现在工作,我的任务是维护一个系统,用的struts2框架,我发现在action类中,根本没有人为的写代码将值
放入域中,然而前端jsp页面却可以通过ognl表达式或者el表达式取到值,过了半个多月,才弄明白,struts2
内部有映射机制,只要前端页面往后端传值的时候,在action类中有set(赋值方法)与get(取值方法)方法,前端页面就可以取到值.
之前的博客 对域的介绍比较多,这里对域不再做介绍
小试牛刀
web.xml-struts2核心过滤器
<filter>
<filter-name>struts</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
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>
<package name="struts" extends="struts-default" namespace="/">
<action name="login" class="com.lanou3g.Demo01Action">
<result>/result.jsp</result>
</action>
</package>
</struts>
begin.jsp-开始页面
<body>
<form action="${pageContext.request.contextPath }/login.action" method="get">
姓名:<input type="text" name="name" />
年龄:<input type="text" name="age" />
<input type="submit" value="登录 " />
</form>
</body>
Demo01Action.java
package com.lanou3g;
import com.opensymphony.xwork2.ActionSupport;
public class Demo01Action extends ActionSupport{
private String name;
private int age;
public String login() throws Exception {
return SUCCESS;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
result.jsp
<body>
<h1>struts2的映射机制</h1>
姓名:<s:property value="name" />
年龄:${age }
</body>
结果截图


总结
代码中将多余的部分都去掉了,留下的是主要,看起来简洁很多,其余的想总结的都在简洁里面了。
本文详细介绍了Struts2框架中的映射机制,揭示了即使不在后端手动放置数据到域中,前端页面也能通过OGNL表达式取值的现象。通过示例代码展示了如何在Action类中实现set和get方法,使前端页面能够直接获取数据。
1459

被折叠的 条评论
为什么被折叠?



