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=""//表示缓存的名字是什么??
<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=""//表示缓存的名字是什么??
<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>