*J2EE—d—>JAVAEE
【struts1——struts2】
【Spring——】
【hibernate——】
*开发模式:表示层—(控制层)—>业务层——>持久层
组建 : V C M(实体模型)复杂融合——————————
1.why——解决web中流程控制和业务选择杂合在servlet中的问题。
2.what——在JSP模式2的基础上实现的一个mvc框架
2.1:mvc开发模式的优点
2.1.1:试图共享模型
2.1.2:3者相互独立
2.1.3:控制器——灵活、配置
3.原理
JSP
|
|
|web.xml——配置org.apache.struts.action.ActionServlet和action的配置文件(config=struts_config.xml)
|
ACTIONSERVLET——控制跳转哪个action
|
|ACTIONFORM——封转表单数据
|struts_config.xml——配置action
|
|
ACTION(应用控制)——获得服务层需要的参数、方法、类
|
|
|
|
SERVICE
4.struts内容
4.1:国际化(internationalization)=i18n
4.1.1:Locate
4.1.2:RescourceBundle
4.1.3:代码
Locale[] locales = Locale.getAvailableLocales();
for(Locale locale : locales){
System.out.println(locale.getDisplayLanguage() + " " + locale.getLanguage());
System.out.println("*********************************************");
System.out.println(locale.getDisplayCountry() + " " + locale.getCountry());
}
Locale locale = Locale.CHINA;
ResourceBundle rb = ResourceBundle.getBundle("test67",locale);//将文件和地区绑定
String value = rb.getString("hello");//从绑定后的文件中获得参数指定键的值
String result = MessageFormat.format(value, "","","Lucy","!");//为通过键获得的值串赋值
System.out.println(result);
在struts-config.xml中配置国际化文件
<message-resources parameter="com.lovo.struts.ApplicationResources" />
<!--native2ascii——将字符转换为utf-8字符集-->
<!--native2ascii -encoding 字符集 原文件 新文件——将文件转为utf-8字符集的文件-->
<!--国际化文件命名规则——文件名-语言-地区.文件类型-->
国际化文件内容
hello={2}\u8bf4\uff1a\u6211\u7231\u5317\u4eac\u5929\u5b89\u95e8
<!--{n}——表示对象集合中的第n号对象即format中的第n+1个参数-->
<!---->
<!---->
4.2:标记库——一切标签最终都化为Java。
4.2.1:HTML标记
4.2.1.1:基本HTML(HTML、img、link)——在struts2中废除
4.2.1.2: 表单HTML
4.2.1.2.1:特点——默认以post为提交方式,与普通的form不一样;struts和HTML标签可以混用,但不推介;当网页包含struts的form标签时actionform在请求网页时产生;
4.2.1.2.2:form中的file标记
jsp
<body>
<html:form action="upload.do" method="post" enctype="multipart/form-data"><!--不指定enctype只会读取文本-->
<table border="0">
<tr>
<td>文件上传:</td>
<td><html:file property="myFile" />
<html:submit value="上传"/></td>
</tr>
</table>
</html:form>
</body>
struts-config.xml
<data-sources />
<form-beans>
<form-bean name="uploadForm" type="com.lovo.struts.form.UploadForm"></form-bean>
</form-beans>
<action-mappings>
<action path="/upload" name="uploadForm" type="com.lovo.struts.action.UploadAction">
<forward name="success" path="/success.jsp"></forward>
</action>
</action-mappings>
form
public class UploadForm extends ActionForm {
private FormFile myFile;
public FormFile getMyFile() {
return myFile;
}
public void setMyFile(FormFile myFile) {
this.myFile = myFile;
}
}
action
public class UploadAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
UploadForm uf = (UploadForm) form;
FormFile myFile = uf.getMyFile();
InputStream in = null;
OutputStream out = null;
try {
in = myFile.getInputStream();
String path = this.servlet.getServletContext().getRealPath(
"/upload");
String fileName = myFile.getFileName();
out = new FileOutputStream(path + "/" + fileName);
byte[] b = new byte[1024];
int length = 0;
while ((length = in.read(b)) != -1) {
out.write(b, 0, length);
out.flush();
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
in.close();
out.close();
}
return mapping.findForward("success");
}
}
4.2.1.3:错误标记
4.2.2:bean标记
4.2.2.1:消息国际化——message
4.2.2.2:输出——write
4.2.2.3:创建、赋值bean——bean:size;bean:define
4.2.2.4:访问资源
4.2.1.
4.2.3:logic标记
4.2.3..1;条件
4.2.3.2: 迭代(循环)
4.2.3.3:转发重定向
4.2.4.
标记库代码
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'success.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<bean:size id="girlsNum" name="allGirls"/>
<h1> This is my Success page.</h1> <br>
欢迎你,<bean:write name="username"/><br>
受害者是:<bean:write property="name" name="theGirl"/>,她才<bean:write property="age" name="theGirl"/>岁<br>
目前受害人总数达到:<bean:write name="girlsNum"/>人<br>
<bean:define id="newBean" value="hello" toScope="session"></bean:define>
创建Bean:<bean:write name="newBean"/><br>
<bean:define id="copyBean" name="username" scope="session" toScope="page"></bean:define>
复制Bean:<bean:write name="copyBean"/><br>
<bean:define id="copyGirlName" property="name" name="theGirl" scope="request" toScope="page"></bean:define>
复制属性:<bean:write name="copyGirlName"/><br>
<logic:lessEqual property="age" name="theGirl" value="25">
你好可怜哦,小妹儿!
</logic:lessEqual>
<logic:greaterThan property="age" name="theGirl" value="25">
你好天真哦,大妈!
</logic:greaterThan>
<br>
受害者详细列表:<br>
<logic:iterate id="tmpGirl" indexId="i" name="allGirls" offset="0" length="girlsNum">
第<%=i+1 %>位--
姓名:<bean:write name="tmpGirl" property="name"/>,
年龄:<bean:write name="tmpGirl" property="age"/><br>
</logic:iterate>
</body>
</html>
4.3:提交表单
4.3.1:原理
actionservlet接受请求
|
|
生成actionform对象
|
| scope
|
表单作用域:request、session
|
|attribute——查找表单的唯一依据,默认情况下与name同名
|
找到 找不到
|
|
|
重置 创建
赋值
|
|validate——验证数据的有效性
|
FALSE ---------TRUE----------
|
| 成功 失败
| input——指定验证失败跳转的页面
-----------action-------------
4.3.2:静态表单代码
action
public class LoginAction extends Action{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
LoginForm lf = (LoginForm)form;//默认在session中找
LoginForm lf = (LoginForm)request.getSession().getAttribute("lf");//在指定作用域类找到指定的表单
UserService us = new UserService();
if(us.checkLogin(lf.getUsername(), lf.getPassword())){
return mapping.findForward("ok");
}
return mapping.findForward("nook");
}
}
struts-config.xml
<form-beans >
<form-bean name="loginForm" type="com.lovo.struts.form.LoginForm"></form-bean>
</form-beans>
<action-mappings >
<action attribute="lf" path="/login" name="loginForm"
scope="session" validate="true" input="/login.jsp"
type="com.lovo.struts.action.LoginAction">
<forward name="ok" path="/success.jsp"></forward>
<forward name="nook" path="/login.jsp"></forward>
</action>
</action-mappings>
form
public class LoginForm extends ActionForm {//1.继承ActionForm
private String username1 = "zhzang3";
private String password1;
public String getUsername() {
return username1;
}
public void setUsername(String username) {
this.username1 = username;
}
public String getPassword() {
return password1;
}
public void setPassword(String password) {
this.password1 = password;
}
//重写重置方法——在存在旧表时自动调用该方法
public void reset(ActionMapping mapping, HttpServletRequest request) {
// TODO Auto-generated method stub
this.username1 = "zhang3";
this.password1 = null;
}
//重写验证方法,静态表才需要重写;
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
// TODO Auto-generated method stub
ActionErrors errors = new ActionErrors();//创建错误信息的集合errors
if(this.username1 == null || "".equals(this.username1.trim())){
errors.add("usernameIsNull", new ActionMessage("error.usernameIsNull"));//将错误信息添加到errors中
//add中第一个参数指定国际化文件中的单个键值对;第二个参数指定国际化文件中的一类文件。
}
if(this.password1 == null || "".equals(this.password1.trim())){
errors.add("passwordIsNull", new ActionMessage("error.passwordIsNull"));
}
return errors;
}
}
4.3.3:动态表单的代码
action
public class LoginAction extends Action{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaActionForm dynaForm = (DynaActionForm)form;
UserService us = new UserService();
if(us.checkLogin(dynaForm.getString("username"), dynaForm.getString("password"))){
return mapping.findForward("ok");
}
return mapping.findForward("nook");
}
}
struts-config.xml
<form-beans >
<form-bean name="dynaLoginForm" type="org.apache.struts.action.DynaActionForm">
<form-property name="username" type="java.lang.String"></form-property>——指定字段名字和数据类型
数据类型写全路径(引用类型必须写全)
<form-property name="password" type="java.lang.String"></form-property>
</form-bean>
</form-beans>
<action-mappings >
<action attribute="lf" path="/login" name="dynaLoginForm"
scope="session" validate="true" input="/login.jsp"
type="com.lovo.struts.action.LoginAction">
<forward name="ok" path="/success.jsp"></forward>
<forward name="nook" path="/login.jsp"></forward>
</action>
</action-mappings>
form
不必书写,在struts-config.xml中配置了,动态表单没法验证
4.3.4:lazy表单代码
<body>
<html:form method="POST" action="lazy.do">
姓名:<html:text property="username"></html:text>
<br>密码:<html:password property="password"></html:password>
<br>
<br>国家:<html:text property="address(nation)"></html:text>
<!--数据封装在名为address的map中,该字段在address中的键为nation-->
<br>省份:<html:text property="address(state)"></html:text>
<br>城市:<html:text property="address(city)"></html:text>
<br>街道:<html:text property="address(street)"></html:text>
<html:submit value="注册" property="subBtn"></html:submit>
<br>
<br>
</html:form>
</body>
struts-config.xml
<struts-config>
<data-sources />
<form-beans>
<form-bean name="lazyForm" type="org.apache.struts.validator.LazyValidatorForm">
</form-bean>
</form-beans>
<global-exceptions />
<global-forwards />
<action-mappings>
<action path="/lazy" name="lazyForm" type="com.lovo.struts.action.LazyAction">
<forward name="success" path="/success.jsp"></forward>
</action>
</action-mappings>
<message-resources parameter="com.lovo.struts.ApplicationResources" />
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames"
value="/WEB-INF/validator-rules.xml, /WEB-INF/validation.xml" />
</plug-in>
</struts-config>
action
public class LazyAction extends Action{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
// TODO Auto-generated method stub
LazyValidatorForm lf = (LazyValidatorForm)form;
System.out.println(lf.get("username"));
System.out.println(lf.get("password"));
Map addressMap = (Map)lf.get("address");
System.out.println(addressMap.get("nation"));
System.out.println(addressMap.get("state"));
System.out.println(addressMap.get("city"));
System.out.println(addressMap.get("street"));
return mapping.findForward("success");
}
}
4.3.
4.4:验证框架
4.4.1:条件——jakarta-oro.jar+commons-validator.jar
4.4.2:文件组成——validate_rule.xml+validation.xml(将验证规则与表单字段绑定)
4.4.3:相关表单——ActionForm<——ValidatorForm
/|\
|
DynaActinForm<——DynavalidatorForm
4.4.4:静态表单验证代码
struts-config.xml
<struts-config>
<data-sources />
<form-beans>
<form-bean name="registerForm"
type="com.lovo.struts.form.RegisterForm">
</form-bean>
</form-beans>
<global-exceptions />
<global-forwards />
<action-mappings>
<action path="/register" name="registerForm" validate="true"
input="/register.jsp" type="com.lovo.struts.action.RegisterAction">
<forward name="success" path="/success.jsp"></forward>
</action>
</action-mappings>
……
……
……
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames"
value="/WEB-INF/validator-rules.xml, /WEB-INF/validation.xml" />
</plug-in>
</struts-config>
validation.xml
<form-validation> <formset> <form name="registerForm"> <field property="username" depends="required,minlength,maxlength"> <!--property:指定字段名;depends:指定需要做哪些验证。--> <arg0 key="label.username"/> <arg1 key="${var:minlength}" resource="false"/> <!--将resource设置为false,直接找页面上的变量;否则在i18n文件中找--> <arg2 key="${var:maxlength}" resource="false"/><!--当arg参数多余4个时,用position属性来制定--> <var> <var-name>minlength</var-name> <!--变量的名字一般已经由alidator-rules.xml指定--> <var-value>6</var-value> </var> <var> <var-name>maxlength</var-name> <var-value>10</var-value> </var> </field> <field property="repassword" depends="validwhen"> <msg key="errors.repassword" name="validwhen"/><!--通过key绑定国际化中的键;name绑定验证--> <var> <var-name>test</var-name> <var-value>(*this*==password)</var-value> <!--表达式需要用()括起来;*this*——表示当前表单提交项--> </var> </field> </form> </formset> </form-validation>
I18N
label.username=username
label.password=password
errors.required=The {0} can not be blank!
errors.minlength=The {0} can not less than {1} charactors!
errors.maxlength=The {0} can not greater than {2} charactors!
4.4.5:自定义验证代码
validation.xml
<form-validation> <formset> <form name="/register"> <field property="loving" depends="intRange,myRules"> <arg0 key="label.loving"/> <arg1 key="${var:min}" resource="false"/> <arg2 key="${var:max}" resource="false"/> <arg3 key="${var:maxValue}" resource="false"/> <var> <var-name>min</var-name> <var-value>0</var-value> </var> <var> <var-name>max</var-name> <var-value>30</var-value> </var> <var> <var-name>maxValue</var-name> <var-value>75</var-value> </var> </field> </form> </formset> </form-validation>
validator-rules.xml
<!--自定义的验证可以以原代码为模板来克隆--> <validator name="myRules" classname="com.lovo.struts.rules.MyValidateRules" method="validateSAL" methodParams="java.lang.Object, org.apache.commons.validator.ValidatorAction, org.apache.commons.validator.Field, org.apache.struts.action.ActionMessages, javax.servlet.http.HttpServletRequest" depends="" msg="errors.sal"/>
java——自定义验证方法
public class MyValidateRules implements Serializable{
public static boolean validateSAL(Object bean,
ValidatorAction va, Field field,
ActionMessages errors,
HttpServletRequest request) {
RegisterForm rf = (RegisterForm)bean;
int strength = Integer.parseInt(rf.getStrength());
int ability = Integer.parseInt(rf.getAbility());
int loving = Integer.parseInt(rf.getLoving());
int value = Integer.parseInt(field.getVarValue("maxValue"));
if(strength + ability + loving > value){
errors.add(field.getKey(), Resources.getActionMessage(request, va, field));
return false;
}
return true;
}
}
I18N
label.strength=strength
label.ability=ability
label.loving=loving
errors.sal=The sum of strength,ability and loving must less than {3}
4.5:action
action的子类
/**
*继承Action
*/
public class LoginAction extends Action{
/**
* 重写父类的方法execute
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String username = request.getParameter("username");
String password = request.getParameter("password");
UserService us = new UserService();
if(us.checkLogin(username, password)){
return mapping.findForward("ok");
}
return mapping.findForward("nook");
}
}
struts-config.xml中action的配置
<action-mappings >
<action path="/login" ——path——对外开启的窗,通过path认路。
type="com.lovo.struts.action.LoginAction">——type指定处理该业务的类
<forward name="ok" path="/success.jsp"></forward>——forward指定跳转的网页(name指定引用别名,path指定本体)
</action>
</action-mappings>
4.5.1:ForwardAction——页面间的跳转;parameter
jsp
<body>
This is my JSP page. <br>
<a href="toLogin.do">登录界面</a>
</body>
struts-config.xml
</action>
<action path="/toLogin" type="org.apache.struts.actions.ForwardAction" parameter="/login.jsp"></action>
</action-mappings>
4.5.2:IncludeAction——页面的包含;parameter
jsp
<body>
<jsp:include page="includeWelcome.do"></jsp:include>
This is my JSP page. <br>
<a href="toLogin.do">登录界面</a>
</body>
struts-config.xml
</action>
<action path="/includeWelcome" type="org.apache.struts.actions.IncludeAction" parameter="/welcome.jsp"></action>
</action-mappings>
4.5.3:DispatchAction——一个表单,多个提交;parameter
jsp
<body>
<form method="get" action="myDispatch.do" name="dispatchForm">
<!--
<input type="hidden" name="myMethod">需要协同js一起完成
-->
<p>
<input type="submit" value="add" name="subBtn">
</p>
<p>
<input type="submit" value="mod" name="subBtn" >
<br>
</p>
<p>
<input type="submit" value="del" name="subBtn">
</p>
</form>
</body>
struts-config.xml
</action> <action path="/myDispatch" type="com.lovo.struts.action.MyDispatchAction" parameter="subBtn"></action> </action-mappings>
Java
public class MyDispatchAction extends DispatchAction{
//不能重写execute(),因为以下方法的实现基于父类的execute方法。
public ActionForward add(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("This is Add");
return null;
}
public ActionForward mod(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("This is Mod");
return null;
}
public ActionForward del(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("This is Del");
return null;
}
}
4.5.4:MappingDispatchAction——多个表单,相同数据;parameter
jsp
<body>
<form method="post" action="mappingAdd.do" name="mappingAddForm">
<p>
<input type="submit" value="add" name="addBtn">
</p>
</form>
</body>
<body>
<form method="post" action="mappingDel.do" name="mappingDelForm">
<p>
<input type="submit" value="del" name="delBtn">
</p>
</form>
</body>
<body>
<form method="post" action="mappingMod.do" name="mappingModForm">
<p>
<input type="submit" value="mod" name="modBtn">
</p>
</form>
</body>
struts-config.xml
<action-mappings > <action path="/mappingAdd" type="com.lovo.struts.action.MyMappingDispatchAction" parameter="myAdd"></action> <action path="/mappingMod" type="com.lovo.struts.action.MyMappingDispatchAction" parameter="myMod"></action> <action path="/mappingDel" type="com.lovo.struts.action.MyMappingDispatchAction" parameter="myDel"></action> </action-mappings>
java
public class MyMappingDispatchAction extends MappingDispatchAction{
public ActionForward myAdd(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("This is Add");
return null;
}
public ActionForward myMod(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("This is Mod");
return null;
}
public ActionForward myDel(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("This is Del");
return null;
}
}
4.5.5:LookupDispatchAction——action+标签+国际化;parameter
原理——1.先通过struts标记查询I18N文件显示;2.当提交的时候,根据显示的值在I18N中找到键,再用action中的方法getKeyMethodMap找到方法。
jsp
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<body>
<html:form action="lookup.do" method="post">
<bean:message key="lab.name"/>:<html:text property="username"></html:text><br>
<html:submit property="subBtn">
<bean:message key="btn.add"/><!--通过key找到值 -->
</html:submit><br>
<html:submit property="subBtn">
<bean:message key="btn.mod"/>
</html:submit><br>
<html:submit property="subBtn">
<bean:message key="btn.del"/>
</html:submit><br>
</html:form>
</body>
struts-config.xml
<action-mappings >
<action path="/lookup" name="loginForm" type="com.lovo.struts.action.MyLookupDispatchAction" parameter="subBtn"></action>
</action-mappings>
action
public class MyLookupDispatchAction extends LookupDispatchAction{//继承内部类lookupDispatchAction
public ActionForward add(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("This is Add");
return null;
}
public ActionForward mod(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("This is Mod");
return null;
}
public ActionForward del(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("This is Del");
return null;
}
//通过i18n里面的键找到对应的action里面的方法。
protected Map getKeyMethodMap() {
Map map = new HashMap();
map.put("btn.add", "add");
map.put("btn.mod", "mod");
map.put("btn.del", "del");
return map;
}
}
i18n
btn.add=\u589e\u52a0
btn.mod=\u4fee\u6539
btn.del=\u5220\u9664
lab.name=\u59d3\u540d
4.5.6:SwitchAction——多个剧本(配置文件struts-config.xml)
web.xml
web.xml <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> <!--可以将多个配置文件写在一个param-value中,用逗号分隔;文件之间平等;工作中使用--> </init-param> <init-param> <param-name>config/ma</param-name> <param-value>/WEB-INF/struts-moduleA.xml</param-value> <!--配置存在阶级性的子配置文件;param-name的值由config开头--> </init-param> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
struts-config.xml
<action-mappings >
<action path="/toModuleA" type="org.apache.struts.actions.SwitchAction"></action>
<!--将剧本联系起来-->
</action-mappings>
jsp
<body>
<jsp:include page="includeWelcome.do"></jsp:include>
This is my JSP page. <br>
<a href="toModuleA.do?prefix=/ma&page=/toLogin.do">登录界面</a>
<!--prefix:;page:指定子文件中的某个action-->
</body>
4.6: titles(标签+架构)