jsp基礎知識03-1
一:JSP中EL表達式
1、 ${}表達式里面可以進行計算;表達式可包含常數
${}表達式的四種范圍:
pageContext-----一個頁面內部,上面存儲下面提取
request------一個請求內部
session------兩個或兩個以上請求之間
application----一個應用內部;主要是一些比較少的數據比如,bbs論壇,在線人數。
這四種范圍也是四種對象
共同特點:可以存儲數據,取數據
setAttribute
getAttribute
${}表達式的四種范圍:
pageContext-----一個頁面內部,上面存儲下面提取
request------一個請求內部
session------兩個或兩個以上請求之間
application----一個應用內部;主要是一些比較少的數據比如,bbs論壇,在線人數。
這四種范圍也是四種對象
共同特點:可以存儲數據,取數據
setAttribute
getAttribute
********************
request
getParameter取表單信息
getAttribute取request信息(取setAttribute在request放的東西)
********************
request
getParameter取表單信息
getAttribute取request信息(取setAttribute在request放的東西)
********************
2、JSTL標記庫
兩個jar包,standard.jar jstl.jar
<%taglib uri="" prefix=""%>
兩個jar包,standard.jar jstl.jar
<%taglib uri="" prefix=""%>
<c:if test="${}" value="">
</c:if>
</c:if>
<c:choose>
<c:when>
</c:when>
<c:otherwise>
</c:otherwise>
</c:choose>
<c:when>
</c:when>
<c:otherwise>
</c:otherwise>
</c:choose>
<c:forEach items="" var="">
</c:forEach>
</c:forEach>
<c:forEach items="${requestScope.arry1}" var="str">
============= ===
必須是EL表達式,這個
表達式取出來得值必須是
一個集合對象;這里是循
環的次數;集合里面有幾個
對象就循環幾次;把元素從集合
里面取出來以var值為名稱放到
pageContext里面
<h1>
${str}
</h1>
</c:forEach>
============= ===
必須是EL表達式,這個
表達式取出來得值必須是
一個集合對象;這里是循
環的次數;集合里面有幾個
對象就循環幾次;把元素從集合
里面取出來以var值為名稱放到
pageContext里面
<h1>
${str}
</h1>
</c:forEach>
以上代碼的意思是反復輸出forEach里面的內容。
<table border="1" width="80%">
<tr>
<td>
Name
</td>
<td>
Age
</td>
</tr>
<c:forEach items="${requestScope.user_list}" var="u">
<tr>
<td>
${u.name}
</td>
<td>
${u.age}
</td>
</tr>
</c:forEach>
</table>
<tr>
<td>
Name
</td>
<td>
Age
</td>
</tr>
<c:forEach items="${requestScope.user_list}" var="u">
<tr>
<td>
${u.name}
</td>
<td>
${u.age}
</td>
</tr>
</c:forEach>
</table>
多擴展是開放的,對修改是關閉的
二、smartstruts1v1向1v2的轉變
首先要考慮的是,部分action只有一個return "success";
我們怎么改呢?
構建一個框架公共類來完成return "success";
a\首先看下smartstruts-config.xml
forward 的值為success或者fail
b\Action.java父類修改
package org.smartstruts.action;
package org.smartstruts.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponse;
public abstract class Action {
//1v1 to 1v2
public static final String SUCCESS="sucess";
public static final String FAIL="fail";
public abstract String execute(HttpServletRequest request,
HttpServletResponse response) throws Exception;
//其子類可能會將部分異常扔出去
}
//1v1 to 1v2
public static final String SUCCESS="sucess";
public static final String FAIL="fail";
public abstract String execute(HttpServletRequest request,
HttpServletResponse response) throws Exception;
//其子類可能會將部分異常扔出去
}
c\可以創建一個ForwardAction公共類
這個類可以完全替代原來的只有return "success"返回語句的類;
package org.whatisjava.actions;
這個類可以完全替代原來的只有return "success"返回語句的類;
package org.whatisjava.actions;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.whatisjava.controller.Action;
public class ForwardAction extends Action {
//這個類是公共的類
public String execute(HttpServletRequest request,
HttpServletResponse response) throws Exception {
return SUCCESS;
}
public String execute(HttpServletRequest request,
HttpServletResponse response) throws Exception {
return SUCCESS;
}
}
d\config.xml文件中的對應的配置變更;
<action-mappings>
<action path="/listUser" type="org.whatisjava.action.ListUserAction">
<forward name="success" path="/WEB-INF/jsp/user_list.jsp"/>
</action>
<action path="/addUser" type="org.whatisjava.action.AddUserAction"/>
<action path="/register" type="org.whatisjava.action.RegisterFormAction">
<forward name="success" path="/WEB-INF/jsp/login_form.jsp"/>
</action>
<!--變更為
<action path="register" type="org.whatisjava.actions.ForwardAction">
<forward name="success" path="/WEB-INF/jsp/login_form.jsp">
</action>
-->
</action-mappings>
d\config.xml文件中的對應的配置變更;
<action-mappings>
<action path="/listUser" type="org.whatisjava.action.ListUserAction">
<forward name="success" path="/WEB-INF/jsp/user_list.jsp"/>
</action>
<action path="/addUser" type="org.whatisjava.action.AddUserAction"/>
<action path="/register" type="org.whatisjava.action.RegisterFormAction">
<forward name="success" path="/WEB-INF/jsp/login_form.jsp"/>
</action>
<!--變更為
<action path="register" type="org.whatisjava.actions.ForwardAction">
<forward name="success" path="/WEB-INF/jsp/login_form.jsp">
</action>
-->
</action-mappings>
三、假設在提交表單信息時應該保留一段時間,比如注冊信息時,一旦出錯
可能要完全重填。我們希望這些信息能緩存起來
可能要完全重填。我們希望這些信息能緩存起來
用戶提交的表單的信息,我們要緩存起來,便于我們寫這些業務。
這也是真實的struts里面最核心的功能之一
那么針對上面的情況我們應該做哪些更改呢?
1、smartstruts-config.xml配置文件的變更
<struts-config>
1、smartstruts-config.xml配置文件的變更
<struts-config>
<form-beans>
<form-bean name="loginForm" type="test.LoginForm"/>
<form-bean name="" type=""/>
<form-bean name="" type=""/>
<form-bean name="" type=""/>
=====================
//form-beans實際上就是定義了一大堆ActionForm的子類
</form-beans>
<form-bean name="loginForm" type="test.LoginForm"/>
<form-bean name="" type=""/>
<form-bean name="" type=""/>
<form-bean name="" type=""/>
=====================
//form-beans實際上就是定義了一大堆ActionForm的子類
</form-beans>
<action-mappings>
<action path="/abc" type="test.TestAction" attribute =""name="loginForm" attribute ="" scope="request/session">
==========
//這個action的name的值必須是上面form-bean定義的某一個name的值
//scope request session
//如果下次還訪問loginForm的時候,會先到request或者session里面查詢
attribute=""http://表示緩存的名字是什么??
<forward name="success" path="/WEB-INF/jsp/hello.jsp" />
</action>
</action-mappings>
</struts-config>
當地址欄里是abc.action請求的時候,首先根據配置文件<action/>找到對應的test.TestAction類,
然后通過反射來new出一個TestAction.根據配置文件對應的name(無name的話,和以前一樣),然后
再根據此與<form-bean/>找出另外一個類test.LoginForm的對象。
接下來new這個類(這個是用戶做的),這個類的屬性 與用戶提交的表單是一樣的。
這里由servlet將數據一個個取出來,再填到對象里面,然后再調用ACTION(TestAction)的執行方法
執行方法就可以從ActionForm Form中獲得數據(通過get方法獲得數據)
<action path="/abc" type="test.TestAction" attribute =""name="loginForm" attribute ="" scope="request/session">
==========
//這個action的name的值必須是上面form-bean定義的某一個name的值
//scope request session
//如果下次還訪問loginForm的時候,會先到request或者session里面查詢
attribute=""http://表示緩存的名字是什么??
<forward name="success" path="/WEB-INF/jsp/hello.jsp" />
</action>
</action-mappings>
</struts-config>
當地址欄里是abc.action請求的時候,首先根據配置文件<action/>找到對應的test.TestAction類,
然后通過反射來new出一個TestAction.根據配置文件對應的name(無name的話,和以前一樣),然后
再根據此與<form-bean/>找出另外一個類test.LoginForm的對象。
接下來new這個類(這個是用戶做的),這個類的屬性 與用戶提交的表單是一樣的。
這里由servlet將數據一個個取出來,再填到對象里面,然后再調用ACTION(TestAction)的執行方法
執行方法就可以從ActionForm Form中獲得數據(通過get方法獲得數據)
2、增加了一個ActionForm.java
3、在Action執行方法中也增加ActionForm form;
3、在Action執行方法中也增加ActionForm form;
public abstract String execute(ActionForm form,HttpServletRequest request,HttpServletResponse response) throws Exception;
這些更改有什么含義呢??
主要是為了表單提交,且對象還要緩存
///////////////////////////
form.getUser
form.getPassword
form.getPassword
四、來更改struts框架
1、修改配置文件config.xml文件
1、修改配置文件config.xml文件
<struts-config>
<!--
解釋:config文件里面只能有一個form-beans和一個action-mapping
而form-beans里面可以有多個form-bean
對應的類是FormBeans、FormBean
action-mappings里面可以有多個action
對應的類是ActionMappings、ActionMapping
一個Action下面可以有多個forward
其對應類為ActionForward
-->
<form-beans>
<form-bean name="loginForm" type="test.LoginForm"/>
</form-beans>
<!-- 理解意圖看懂實現
一個form-bean表示一個對象,name是標識,type是
一個form-bean表示寫的是ActionForm的一個子類;
-->
<action-mappings>
<action path="/listUser" type="org.whatisjava.action.ListUserAction" name="loginForm" scope="">
<!-- 其后面的name的值必須是前面form-beans里面的某個form-bean的name的值
scope里面只能有兩種寫法:request,session-->
<forward name="success" path="/WEB-INF/jsp/user_list.jsp"/>
<!-- path的路徑一定要注意:在這里用的是轉發的地址,并不包含應用的地址
如果是重定向的話,前面只是加一個redirect=true即可;
如果是轉發的話,就保持現狀即可。
所以在這里一定要轉發的地址(不包含應用的地址)
-->
</action>
<action path="/addUser" type="org.whatisjava.action.AddUserAction"/>
<action path="/register" type="org.whatisjava.action.RegisterFormAction"/>
</action-mappings>
</struts-config>
<!--
解釋:config文件里面只能有一個form-beans和一個action-mapping
而form-beans里面可以有多個form-bean
對應的類是FormBeans、FormBean
action-mappings里面可以有多個action
對應的類是ActionMappings、ActionMapping
一個Action下面可以有多個forward
其對應類為ActionForward
-->
<form-beans>
<form-bean name="loginForm" type="test.LoginForm"/>
</form-beans>
<!-- 理解意圖看懂實現
一個form-bean表示一個對象,name是標識,type是
一個form-bean表示寫的是ActionForm的一個子類;
-->
<action-mappings>
<action path="/listUser" type="org.whatisjava.action.ListUserAction" name="loginForm" scope="">
<!-- 其后面的name的值必須是前面form-beans里面的某個form-bean的name的值
scope里面只能有兩種寫法:request,session-->
<forward name="success" path="/WEB-INF/jsp/user_list.jsp"/>
<!-- path的路徑一定要注意:在這里用的是轉發的地址,并不包含應用的地址
如果是重定向的話,前面只是加一個redirect=true即可;
如果是轉發的話,就保持現狀即可。
所以在這里一定要轉發的地址(不包含應用的地址)
-->
</action>
<action path="/addUser" type="org.whatisjava.action.AddUserAction"/>
<action path="/register" type="org.whatisjava.action.RegisterFormAction"/>
</action-mappings>
</struts-config>
2、根據ActionMapping和ActionMappings結構來建立FormBean和FormBeans類
FormBean類:
package org.whatisjava.controller;
FormBean類:
package org.whatisjava.controller;
public class FormBean {
private String name;
private String type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
private String name;
private String type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
FormBeans類:
package org.whatisjava.controller;
import java.util.HashMap;
import java.util.Map;
import java.util.Map;
public class FormBeans {
private Map<String,FormBean> forms=new HashMap<String,FormBean>();
//Map是鍵值對
//提供一個方法能讓外界訪問
public void addFormBean(FormBean form){
forms.put(form.getName(), form);
}
public FormBean findFormBean(String name){
return forms.get(name);
}
public String toString() {
return forms.toString();
}
}
private Map<String,FormBean> forms=new HashMap<String,FormBean>();
//Map是鍵值對
//提供一個方法能讓外界訪問
public void addFormBean(FormBean form){
forms.put(form.getName(), form);
}
public FormBean findFormBean(String name){
return forms.get(name);
}
public String toString() {
return forms.toString();
}
}
3、修改ActionMaping類
package org.whatisjava.controller;
import java.util.HashMap;
import java.util.Map;
import java.util.Map;
public class ActionMapping {
private String path;
private String type;
//****************************************
private String name; //關聯form
private String scope; //表示緩存到哪里request還是session
private String attribute; //表示緩存的時候叫什么名字
//增加以上3個屬性方法
//這3個屬性是為了把form進行緩存和關聯
private Map<String,ActionForward> forwards=new HashMap<String,ActionForward>();
public void addActionForward(ActionForward forward){
forwards.put(forward.getName(),forward);
}
public ActionForward findActionForward(String name){
return forwards.get(name);
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
public Map<String, ActionForward> getForwards() {
return forwards;
}
public void setForwards(Map<String, ActionForward> forwards) {
this.forwards = forwards;
}
}
private String path;
private String type;
//****************************************
private String name; //關聯form
private String scope; //表示緩存到哪里request還是session
private String attribute; //表示緩存的時候叫什么名字
//增加以上3個屬性方法
//這3個屬性是為了把form進行緩存和關聯
private Map<String,ActionForward> forwards=new HashMap<String,ActionForward>();
public void addActionForward(ActionForward forward){
forwards.put(forward.getName(),forward);
}
public ActionForward findActionForward(String name){
return forwards.get(name);
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
public Map<String, ActionForward> getForwards() {
return forwards;
}
public void setForwards(Map<String, ActionForward> forwards) {
this.forwards = forwards;
}
}
4、建立StrutsConfig類
package org.whatisjava.controller;
public class StrutsConfig {
private ActionMappings mappings;
private FormBeans formbeans;
public ActionMappings getMappings() {
return mappings;
}
public void setMappings(ActionMappings mappings) {
this.mappings = mappings;
}
public FormBeans getFormbeans() {
return formbeans;
}
public void setFormbeans(FormBeans formbeans) {
this.formbeans = formbeans;
}
}
//通過獲得StrutsConfig類就可以獲取到其他的類如ActionMapping,FormBeans等類
//從而就獲取到config.xml文件
private ActionMappings mappings;
private FormBeans formbeans;
public ActionMappings getMappings() {
return mappings;
}
public void setMappings(ActionMappings mappings) {
this.mappings = mappings;
}
public FormBeans getFormbeans() {
return formbeans;
}
public void setFormbeans(FormBeans formbeans) {
this.formbeans = formbeans;
}
}
//通過獲得StrutsConfig類就可以獲取到其他的類如ActionMapping,FormBeans等類
//從而就獲取到config.xml文件
5、修改rule.xml文件
<?xml version='1.0' encoding='UTF-8'?>
<!--
這個xml文件是由commons-digester定義用于告訴digester組件
自定義的配置文件和配置對象之間的關系,commons-digester組件了解了這
個關系后就可以將配置文件中的信息轉換為配置對象
-->
<digester-rules>
<pattern value="struts-config">
<!--
這個xml文件是由commons-digester定義用于告訴digester組件
自定義的配置文件和配置對象之間的關系,commons-digester組件了解了這
個關系后就可以將配置文件中的信息轉換為配置對象
-->
<digester-rules>
<pattern value="struts-config">
<pattern value="form-beans">
<object-create-rule classname="org.whatisjava.controller.FormBeans"/>
<set-next-rule methodname="setFormBeans"/>
<set-properties-rule/>
<pattern value="form-bean">
<object-create-rule classname="org.whatisjava.controller.FormBean"/>
<set-next-rule methodname="addFormBean"/>
<set-properties-rule/>
</pattern>
</pattern>
<object-create-rule classname="org.whatisjava.controller.FormBeans"/>
<set-next-rule methodname="setFormBeans"/>
<set-properties-rule/>
<pattern value="form-bean">
<object-create-rule classname="org.whatisjava.controller.FormBean"/>
<set-next-rule methodname="addFormBean"/>
<set-properties-rule/>
</pattern>
</pattern>
<pattern value="action-mappings">
<object-create-rule classname="org.whatisjava.controller.ActionMappings"/>
<set-next-rule methodname="setMappings"/>
<set-properties-rule/>
<pattern value="action">
<!--每碰到一個action元素,就創建指定類的對象-->
<object-create-rule classname="org.whatisjava.controller.ActionMapping" />
<!--
對象創建后,調用指定的方法,
將其加入它上一級元素所對應的對象
-->
<set-next-rule methodname="addActionMapping" />
<!--
將action元素的各個屬性按照相同的名稱
賦值給剛剛創建的ActionMapping對象
-->
<set-properties-rule />
<pattern value="forward">
<object-create-rule classname="org.whatisjava.controller.ActionMappings"/>
<set-next-rule methodname="setMappings"/>
<set-properties-rule/>
<pattern value="action">
<!--每碰到一個action元素,就創建指定類的對象-->
<object-create-rule classname="org.whatisjava.controller.ActionMapping" />
<!--
對象創建后,調用指定的方法,
將其加入它上一級元素所對應的對象
-->
<set-next-rule methodname="addActionMapping" />
<!--
將action元素的各個屬性按照相同的名稱
賦值給剛剛創建的ActionMapping對象
-->
<set-properties-rule />
<pattern value="forward">
<object-create-rule classname="org.whatisjava.controller.ActionForward" />
<set-next-rule methodname="addActionForward" />
<set-properties-rule />
<!-- 可以一層一層往下添加 -->
</pattern>
</pattern>
</pattern>
</pattern>
</digester-rules>
<set-next-rule methodname="addActionForward" />
<set-properties-rule />
<!-- 可以一層一層往下添加 -->
</pattern>
</pattern>
</pattern>
</pattern>
</digester-rules>
6、修改ActionServlet
v1.1版本的ActionServlet
package org.whatisjava.controller;
package org.whatisjava.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.digester.Digester;
import org.apache.commons.digester.xmlrules.DigesterLoader;
import org.xml.sax.SAXException;
import org.apache.commons.digester.xmlrules.DigesterLoader;
import org.xml.sax.SAXException;
public class ActionServlet extends HttpServlet {
private ActionMappings mappings=new ActionMappings();
public void init(){
//構造完了之后會調用以下init();
//初始化mappings(讀取配置文件信息到mapings對象中)
System.out.println("init....");
try {
Digester digester=DigesterLoader.createDigester(ActionServlet.class.getClassLoader()
.getResource("org/whatisjava/controller/rule.xml"));
digester.push(mappings);
digester.parse(ActionServlet.class.getClassLoader().getResource("config.xml"));
System.out.println(mappings);
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("ActionServlet....");
String uri=request.getRequestURI();
//request.getRequestURI();//根據請求的url返回uri ri(Returned Value)
//For example: First line of HTTP request Returned Value
//POST /some/path.html HTTP/1.1 /some/path.html
//GET http://foo.bar/a.html HTTP/1.0 /a.html
//HEAD /xyz?a=b HTTP/1.1 /xyz
System.out.println("......");
System.out.println(uri);
//String path=uri.substring(uri.lastIndexOf("/"), uri.indexOf("."));
String path=uri.substring(uri.lastIndexOf("/"),uri.lastIndexOf("."));
System.out.println(path);
//String path1=uri.substring(uri.lastIndexOf("/"),uri.indexOf("."));
//System.out.println(path);
//substring(int beginIndex,int endIndex);
//從路徑中取出文件名;
//System.out.println(path);
// //*************************************
// if("/listUser".equals(path)){
// Action action=new ListUserAction();
//
// String forward=action.execute(request, response);
//
// RequestDispatcher rd=request.getRequestDispatcher(forward);
// rd.forward(request, response);
//
//
// }else if("/addUser".equals(path)){
// //添加用戶
// //按照這種模式來做的話,這個serlvet將成了超級類
//
// Action action=new AddUserAction();
//
// String forward=action.execute(request, response);
//
// RequestDispatcher rd=request.getRequestDispatcher(forward);
// rd.forward(request, response);
//
// }
// //*********
// Action action=null;
// if ("user_list".equals(path)){
//
// action=new ListUserAction();
// }else if("addUser".equals(path)){
//
// action=new AddUserAction();
// }
//假設這個地方再增加一個功能比如deleteUser,還是需要修改程序?
//怎么才能避免需要添加功能時不修改Action呢?
//最好的是把其放到配置文件里面
//根據配置文件決定new哪個類......
//采用反射
//String className;
//Class.forName(className).newInstance();
//String path1=uri.substring(uri.lastIndexOf("/"),uri.indexOf("."));
//System.out.println(path);
//substring(int beginIndex,int endIndex);
//從路徑中取出文件名;
//System.out.println(path);
// //*************************************
// if("/listUser".equals(path)){
// Action action=new ListUserAction();
//
// String forward=action.execute(request, response);
//
// RequestDispatcher rd=request.getRequestDispatcher(forward);
// rd.forward(request, response);
//
//
// }else if("/addUser".equals(path)){
// //添加用戶
// //按照這種模式來做的話,這個serlvet將成了超級類
//
// Action action=new AddUserAction();
//
// String forward=action.execute(request, response);
//
// RequestDispatcher rd=request.getRequestDispatcher(forward);
// rd.forward(request, response);
//
// }
// //*********
// Action action=null;
// if ("user_list".equals(path)){
//
// action=new ListUserAction();
// }else if("addUser".equals(path)){
//
// action=new AddUserAction();
// }
//假設這個地方再增加一個功能比如deleteUser,還是需要修改程序?
//怎么才能避免需要添加功能時不修改Action呢?
//最好的是把其放到配置文件里面
//根據配置文件決定new哪個類......
//采用反射
//String className;
//Class.forName(className).newInstance();
//根據配置文件決定new哪個類
if (path==null) throw new ServletException(".....");
if (mappings!=null) System.out.println("mappings isn't null");
ActionMapping mapping=mappings.findActionMapping(path);
//System.out.println(mapping);
if (mapping!=null) System.out.println("mapping isn't null");
if (mapping==null) throw new ServletException("....");
try{
String className=mapping.getType();
Class clazz=Class.forName(className);
Action action=(Action) clazz.newInstance();
String forwardName=action.execute(null, request, response);
//存數據取數據都是通過這個執行方法
System.out.println(forwardName);
//需要知道是轉發給誰?
ActionForward forward=mapping.findActionForward(forwardName);
if (path==null) throw new ServletException(".....");
if (mappings!=null) System.out.println("mappings isn't null");
ActionMapping mapping=mappings.findActionMapping(path);
//System.out.println(mapping);
if (mapping!=null) System.out.println("mapping isn't null");
if (mapping==null) throw new ServletException("....");
try{
String className=mapping.getType();
Class clazz=Class.forName(className);
Action action=(Action) clazz.newInstance();
String forwardName=action.execute(null, request, response);
//存數據取數據都是通過這個執行方法
System.out.println(forwardName);
//需要知道是轉發給誰?
ActionForward forward=mapping.findActionForward(forwardName);
if (forward!=null){
if(!forward.isRedirect()){
RequestDispatcher rd=request.getRequestDispatcher(forward.getPath());
//進行轉發(把請求和響應對象轉給另一個組件)
rd.forward(request, response);
}else{
//重定向
//request.getContextPath();包含/
//forward.getPath();前面不包含/
response.sendRedirect(request.getContextPath()+forward.getPath());
}
}
}catch(Exception e){
throw new ServletException("...",e);
}
}
if(!forward.isRedirect()){
RequestDispatcher rd=request.getRequestDispatcher(forward.getPath());
//進行轉發(把請求和響應對象轉給另一個組件)
rd.forward(request, response);
}else{
//重定向
//request.getContextPath();包含/
//forward.getPath();前面不包含/
response.sendRedirect(request.getContextPath()+forward.getPath());
}
}
}catch(Exception e){
throw new ServletException("...",e);
}
}
}
從上面可以看出該ActionServlet架構已經比較龐大了,如果再增加會越來越大,重構
1、私有方法來實現單個功能
2、StrutsConfig、formBeans擴增
從上面可以看出該ActionServlet架構已經比較龐大了,如果再增加會越來越大,重構
1、私有方法來實現單個功能
2、StrutsConfig、formBeans擴增
package org.whatisjava.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.digester.Digester;
import org.apache.commons.digester.xmlrules.DigesterLoader;
import org.apache.commons.digester.Digester;
import org.apache.commons.digester.xmlrules.DigesterLoader;
public class ActionServlet extends HttpServlet {
//配置文件里面的條目:StrutsConfig;ActionMappings;FormBeans等
//為了方便可以定義一些成員變量;
private StrutsConfig config;
private ActionMappings mappings;
private FormBeans formbeans;
public void init(){
System.out.println("ActionServlet init....");
try{
this.initConfig();
}catch(Exception e){
e.printStackTrace();
}
}
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("ActionServlet....");
try {
//根據request中的信息,截取.action前面的字符串返回
String path=processPath(request);
//根據這個path獲得配置文件中的actionmapping對象的信息
ActionMapping mapping=mappings.findActionMapping(path);
//根據剛才actionmapping對象創建一個action實例
Action action=this.processAction(mapping);
//根據剛才actionmapping對象去獲得一個actionform實例,可能有,也可能無
//有可能來自request,也可能來自session
ActionForm form=this.processForm(request, mapping);
//用剛剛創建的actionForm實例
String forwardName=action.execute(form, request, response);
//根據返回的字符串,做轉發還是重定向
this.processForward(forwardName, mapping, request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* 初始化配置文件
*/
private void initConfig() throws Exception{
* 初始化配置文件
*/
private void initConfig() throws Exception{
Digester digester=DigesterLoader.createDigester(ActionServlet.class.getClassLoader()
.getResource("org/whatisjava/controller/rule.xml"));
config =new StrutsConfig();
digester.push(config);
digester.parse(ActionServlet.class.getClassLoader().getResource("config.xml"));
mappings=config.getMappings();
formbeans=config.getFormbeans();
}
/*
* 根據request請求里面帶過來的uri地址來獲得path(.action前面的)
*/
private String processPath(HttpServletRequest request){
String uri=request.getRequestURI();
String path=uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf("."));
return path;
}
private Action processAction(ActionMapping mapping) throws Exception{
//要用反射的話就存在拋出異常
//通過類名來反射對象
String type=mapping.getType();
Class clazz=Class.forName(type);
return (Action)clazz.newInstance();
}
private ActionForm processForm(HttpServletRequest request,ActionMapping mapping) throws Exception{
//為什么這里用request呢,由于scope只有兩個可選范圍:request或者session;而session也
//是通過request獲得的
//根據mapping里面的name信息
String name=mapping.getName();
HttpSession session=request.getSession();
if (name!=null){
//action中的attribute,scope,name
String attribute=mapping.getAttribute();
if (attribute==null) attribute=name;
String scope=mapping.getScope();
//如果以前已經做過form對象的話,就直接使用就行,如果無的話,則需要新建
ActionForm form=null;
if (scope==null) scope="session";
if ("session".equals(scope)){
form=(ActionForm)session.getAttribute(attribute);
//把attribute封裝到form里面
}else{
form=(ActionForm)request.getAttribute(attribute);
}
if(form==null){
FormBean formBean=formbeans.findFormBean(name);
String type=formBean.getType();
Class clazz=Class.forName(type);
form=(ActionForm)clazz.newInstance();
if ("session".equals(scope)){
session.setAttribute(attribute,form);
}else{
request.setAttribute(attribute, form);
}
.getResource("org/whatisjava/controller/rule.xml"));
config =new StrutsConfig();
digester.push(config);
digester.parse(ActionServlet.class.getClassLoader().getResource("config.xml"));
mappings=config.getMappings();
formbeans=config.getFormbeans();
}
/*
* 根據request請求里面帶過來的uri地址來獲得path(.action前面的)
*/
private String processPath(HttpServletRequest request){
String uri=request.getRequestURI();
String path=uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf("."));
return path;
}
private Action processAction(ActionMapping mapping) throws Exception{
//要用反射的話就存在拋出異常
//通過類名來反射對象
String type=mapping.getType();
Class clazz=Class.forName(type);
return (Action)clazz.newInstance();
}
private ActionForm processForm(HttpServletRequest request,ActionMapping mapping) throws Exception{
//為什么這里用request呢,由于scope只有兩個可選范圍:request或者session;而session也
//是通過request獲得的
//根據mapping里面的name信息
String name=mapping.getName();
HttpSession session=request.getSession();
if (name!=null){
//action中的attribute,scope,name
String attribute=mapping.getAttribute();
if (attribute==null) attribute=name;
String scope=mapping.getScope();
//如果以前已經做過form對象的話,就直接使用就行,如果無的話,則需要新建
ActionForm form=null;
if (scope==null) scope="session";
if ("session".equals(scope)){
form=(ActionForm)session.getAttribute(attribute);
//把attribute封裝到form里面
}else{
form=(ActionForm)request.getAttribute(attribute);
}
if(form==null){
FormBean formBean=formbeans.findFormBean(name);
String type=formBean.getType();
Class clazz=Class.forName(type);
form=(ActionForm)clazz.newInstance();
if ("session".equals(scope)){
session.setAttribute(attribute,form);
}else{
request.setAttribute(attribute, form);
}
}
BeanUtils.populate(form, request.getParameterMap());
return form;
BeanUtils.populate(form, request.getParameterMap());
return form;
}else{
return null;
}
}
private void processForward(String forwardName,ActionMapping mapping,
HttpServletRequest request,HttpServletResponse response) throws Exception{
ActionForward forward=mapping.findActionForward(forwardName);
if (forward!=null){
if(!forward.isRedirect()){
request.getRequestDispatcher(forward.getPath()).forward(request, response);
}else{
response.sendRedirect(request.getContextPath()+forward.getPath());
}
}
}
}
導出
public 與private的區別
一個類有一個public就代表這個類就有一個方法,這個類就公開了一個方法,對外就提供一種功能;
也就代表其維護成本就高了。
1、register_form.jsp頁面
<td valign="middle" align="left">
<input type="text" class="inputgri" name="username" value="${rf.username}" />
=============
</td>
<td valign="middle" align="left">
<input type="text" class="inputgri" name="username" value="${rf.username}" />
=============
</td>
<td valign="middle" align="left">
男
<input type="radio" class="inputgri" name="sex" value="m" checked="checked"/>
女
<input type="radio" class="inputgri" name="sex" value="f"/>
</td>
<tr>
<td valign="middle" align="right">
性別:
</td>
<c:choose>
<c:when test="${rf.sex eq 'm'} ">
<td valign="middle" align="left">
男
<input type="radio" class="inputgri" name="sex" value="m" checked="checked"/>
女
<input type="radio" class="inputgri" name="sex" value="f"/>
</td>
</c:when>
<c:otherwise test="${rf.sex eq 'f'}">
<td valign="middle" align="left">
男
<input type="radio" class="inputgri" name="sex" value="m" />
女
<input type="radio" class="inputgri" name="sex" value="f" checked="checked"/>
</td>
</c:otherwise>
</c:choose>
</tr>
2、struts-config.xml文件
<struts-config>
<form-beans>
<form-bean name="rf" type="org.whatisjava.form.RegisterForm" />
<form-bean name="lf" type="org.whatisjava.form.LoginForm" />
</form-beans>
<action-mappings>
<action path="/registerForm"
type="org.smartstruts.actions.ForwardAction">
<forward name="success"
path="/WEB-INF/jsp/register_form.jsp" />
</action>
<action path="/registerForm"
type="org.smartstruts.actions.ForwardAction">
<forward name="success"
path="/WEB-INF/jsp/register_form.jsp" />
</action>
<action path="/loginForm"
type="org.smartstruts.actions.ForwardAction">
<forward name="success" path="/WEB-INF/jsp/login_form.jsp" />
</action>
type="org.smartstruts.actions.ForwardAction">
<forward name="success" path="/WEB-INF/jsp/login_form.jsp" />
</action>
<action path="/addUser"
type="org.whatisjava.action.AddUserAction" name="rf">
<forward name="success" path="/loginForm.action"
redirect="true" />
<forward name="fail" path="/WEB-INF/jsp/register_form.jsp" />
</action>
type="org.whatisjava.action.AddUserAction" name="rf">
<forward name="success" path="/loginForm.action"
redirect="true" />
<forward name="fail" path="/WEB-INF/jsp/register_form.jsp" />
</action>
<action path="/listUser"
type="org.whatisjava.action.ListUserAction">
<forward name="success" path="/WEB-INF/jsp/user_list.jsp" />
</action>
type="org.whatisjava.action.ListUserAction">
<forward name="success" path="/WEB-INF/jsp/user_list.jsp" />
</action>
<action path="/login"
type="org.whatisjava.action.LoginAction" name="lf">
<forward name="success" path="/listUser.action"
redirect="true" />
<forward name="fail" path="/WEB-INF/jsp/login_form.jsp" />
</action>
type="org.whatisjava.action.LoginAction" name="lf">
<forward name="success" path="/listUser.action"
redirect="true" />
<forward name="fail" path="/WEB-INF/jsp/login_form.jsp" />
</action>
</action-mappings>
<message-resources parameter="appRes"/>
</struts-config>
<message-resources parameter="appRes"/>
</struts-config>
三、AddUserAction
導入BeansUtils.copyProperties(user,rf)
BeanUtils.copyProperties(user, rf);
dao.addUser(user);
其中rf為actionform表單
把一個對象的屬性copy到另外一個對象里面(前提是相同的屬性)
package org.whatisjava.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;
import org.smartstruts.action.Action;
import org.smartstruts.action.ActionForm;
import org.whatisjava.dao.UserDao;
import org.whatisjava.domain.User;
import org.whatisjava.form.RegisterForm;
import org.smartstruts.action.Action;
import org.smartstruts.action.ActionForm;
import org.whatisjava.dao.UserDao;
import org.whatisjava.domain.User;
import org.whatisjava.form.RegisterForm;
public class AddUserAction extends Action {
@Override
public String execute(ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
public String execute(ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
RegisterForm rf = (RegisterForm) form;
String number1 = rf.getNumber();
HttpSession session = request.getSession();
String number2 = (String) session.getAttribute("number");
if (number2 != null && number2.equals(number1)) {
UserDao dao = new UserDao();
User user = new User();
String number2 = (String) session.getAttribute("number");
if (number2 != null && number2.equals(number1)) {
UserDao dao = new UserDao();
User user = new User();
BeanUtils.copyProperties(user, rf);
dao.addUser(user);
String dir = "pic";
dir = this.getServlet().getServletContext().getRealPath(dir);
File file = new File(dir + "/" + "pic_" + user.getId());
file.mkdir();
dir = this.getServlet().getServletContext().getRealPath(dir);
File file = new File(dir + "/" + "pic_" + user.getId());
file.mkdir();
return "success";
} else {
//getAttribute
//不能期望用戶對框架的核心都很了解,我們應該封裝起來
//讓他調用一些api
request.setAttribute("error_msg", "驗證碼錯誤");
} else {
//getAttribute
//不能期望用戶對框架的核心都很了解,我們應該封裝起來
//讓他調用一些api
request.setAttribute("error_msg", "驗證碼錯誤");
return "fail";
}
}
}
}
}
頁面能夠緩存起來先前輸入的內容
<td valign="middle" align="left">
<input type="text" class="inputgri" name="username" value="${rf.username}" />
=============
</td>
<input type="text" class="inputgri" name="username" value="${rf.username}" />
=============
</td>
<td valign="middle" align="left">
男
<input type="radio" class="inputgri" name="sex" value="m" checked="checked"/>
女
<input type="radio" class="inputgri" name="sex" value="f"/>
</td>
<tr>
<td valign="middle" align="right">
性別:
</td>
<c:choose>
<c:when test="${rf.sex eq 'm'} ">
<td valign="middle" align="left">
男
<input type="radio" class="inputgri" name="sex" value="m" checked="checked"/>
女
<input type="radio" class="inputgri" name="sex" value="f"/>
</td>
</c:when>
<c:otherwise test="${rf.sex eq 'f'}">
<td valign="middle" align="left">
男
<input type="radio" class="inputgri" name="sex" value="m" />
女
<input type="radio" class="inputgri" name="sex" value="f" checked="checked"/>
</td>
</c:otherwise>
</c:choose>
</tr>
本文由用戶 honghu79 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!