簡介
之前學習的時候,後端代碼通過獲取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>
結果截圖
總結
代碼中將多餘的部分都去掉了,留下的是主要,看起來簡潔很多,其餘的想總結的都在簡潔裏面了。