`

JSP入门初级教程之Actions的使用

 
阅读更多
<script type="text/javascript"> <!-- var theForm = document.forms['Form1']; if (!theForm) { theForm = document.Form1; } function __doPostBack(eventTarget, eventArgument) { if (!theForm.onsubmit || (theForm.onsubmit() != false)) { theForm.__EVENTTARGET.value = eventTarget; theForm.__EVENTARGUMENT.value = eventArgument; theForm.submit(); } } // --> </script><script src="/WebResource.axd?d=VT-DPrLTYP31jDF3TQ1B-w2&amp;t=632963535947587500" type="text/javascript"></script><script type="text/javascript"> //<![CDATA[ var Anthem_DefaultURL = "322771.aspx?Anthem_CallBack=true"; var Anthem_FormID = "Form1"; //]]> </script><script type="text/javascript"> //<![CDATA[ // Anthem.js // Updated Nov 13, 2006 // Used by encodeURIComponentNew to mimic function encodeURIComponent in // IE 5.5+, Netscape 6+, and Mozilla function utf8(wide) { var c, s; var enc = ""; var i = 0; while(i<wide.length) { c= wide.charCodeAt(i++); // handle UTF-16 surrogates if (c>=0xDC00 && c<0xE000) continue; if (c>=0xD800 && c<0xDC00) { if (i>=wide.length) continue; s= wide.charCodeAt(i++); if (s<0xDC00 || c>=0xDE00) continue; c= ((c-0xD800)<<10)+(s-0xDC00)+0x10000; } // output value if (c<0x80) enc += String.fromCharCode(c); else if (c<0x800) enc += String.fromCharCode(0xC0+(c>>6),0x80+(c&0x3F)); else if (c<0x10000) enc += String.fromCharCode(0xE0+(c>>12),0x80+(c>>6&0x3F),0x80+(c&0x3F)); else enc += String.fromCharCode(0xF0+(c>>18),0x80+(c>>12&0x3F),0x80+(c>>6&0x3F),0x80+(c&0x3F)); } return enc; } var hexchars = "0123456789ABCDEF"; function toHex(n) { return hexchars.charAt(n>>4)+hexchars.charAt(n & 0xF); } var okURIchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"; // Mimics function encodeURIComponent in IE 5.5+, Netscape 6+, and Mozilla function encodeURIComponentNew(s) { var s = utf8(s); var c; var enc = ""; for (var i= 0; i<s.length; i++) { if (okURIchars.indexOf(s.charAt(i))==-1) enc += "%"+toHex(s.charCodeAt(i)); else enc += s.charAt(i); } return enc; } function Anthem_Encode(s){ if (typeof encodeURIComponent == "function") { // Use JavaScript built-in function // IE 5.5+ and Netscape 6+ and Mozilla return encodeURIComponent(s); } else { // Need to mimic the JavaScript version // Netscape 4 and IE 4 and IE 5.0 return encodeURIComponentNew(s); } } // Primarily used by Anthem.Manager to add an onsubmit event handler // when validators are added to a page during a callback. function Anthem_AddEvent(control, eventType, functionPrefix) { var ev; eval("ev = control." + eventType + ";"); if (typeof(ev) == "function") { ev = ev.toString(); ev = ev.substring(ev.indexOf("{") + 1, ev.lastIndexOf("}")); } else { ev = ""; } var func; if (navigator.appName.toLowerCase().indexOf('explorer') > -1) { func = new Function(functionPrefix + " " + ev); } else { func = new Function("event", functionPrefix + " " + ev); } eval("control." + eventType + " = func;"); } function Anthem_GetXMLHttpRequest() { if (window.XMLHttpRequest) { return new XMLHttpRequest(); } else { if (window.Anthem_XMLHttpRequestProgID) { return new ActiveXObject(window.Anthem_XMLHttpRequestProgID); } else { var progIDs = ["Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"]; for (var i = 0; i < progIDs.length; ++i) { var progID = progIDs[i]; try { var x = new ActiveXObject(progID); window.Anthem_XMLHttpRequestProgID = progID; return x; } catch (e) { } } } } return null; } function Anthem_CallBack(url, target, id, method, args, clientCallBack, clientCallBackArg, includeControlValuesWithCallBack, updatePageAfterCallBack) { if (window.Anthem_PreCallBack) { var preCallBackResult = Anthem_PreCallBack(); if (!(typeof preCallBackResult == "undefined" || preCallBackResult)) { if (window.Anthem_CallBackCancelled) { Anthem_CallBackCancelled(); } return null; } } var x = Anthem_GetXMLHttpRequest(); var result = null; if (!x) { result = { "value": null, "error": "NOXMLHTTP" }; Anthem_DebugError(result.error); if (window.Anthem_Error) { Anthem_Error(result); } if (clientCallBack) { clientCallBack(result, clientCallBackArg); } return result; } x.open("POST", url ? url : Anthem_DefaultURL, clientCallBack ? true : false); x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); x.setRequestHeader("Accept-Encoding", "gzip, deflate"); if (clientCallBack) { x.onreadystatechange = function() { if (x.readyState != 4) { return; } Anthem_DebugResponseText(x.responseText); result = Anthem_GetResult(x); if (result.error) { Anthem_DebugError(result.error); if (window.Anthem_Error) { Anthem_Error(result); } } if (updatePageAfterCallBack) { Anthem_UpdatePage(result); } Anthem_EvalClientSideScript(result); clientCallBack(result, clientCallBackArg); x = null; if (window.Anthem_PostCallBack) { Anthem_PostCallBack(); } } } var encodedData = ""; if (target == "Page") { encodedData += "&Anthem_PageMethod=" + method; } else if (target == "MasterPage") { encodedData += "&Anthem_MasterPageMethod=" + method; } else if (target == "Control") { encodedData += "&Anthem_ControlID=" + id.split(":").join("_"); encodedData += "&Anthem_ControlMethod=" + method; } if (args) { for (var argsIndex = 0; argsIndex < args.length; ++argsIndex) { if (args[argsIndex] instanceof Array) { for (var i = 0; i < args[argsIndex].length; ++i) { encodedData += "&Anthem_CallBackArgument" + argsIndex + "=" + Anthem_Encode(args[argsIndex][i]); } } else { encodedData += "&Anthem_CallBackArgument" + argsIndex + "=" + Anthem_Encode(args[argsIndex]); } } } if (updatePageAfterCallBack) { encodedData += "&Anthem_UpdatePage=true"; } if (includeControlValuesWithCallBack) { var form = document.getElementById(Anthem_FormID); if (form != null) { for (var elementIndex = 0; elementIndex < form.length; ++elementIndex) { var element = form.elements[elementIndex]; if (element.name) { var elementValue = null; if (element.nodeName.toUpperCase() == "INPUT") { var inputType = element.getAttribute("type").toUpperCase(); if (inputType == "TEXT" || inputType == "PASSWORD" || inputType == "HIDDEN") { elementValue = element.value; } else if (inputType == "CHECKBOX" || inputType == "RADIO") { if (element.checked) { elementValue = element.value; } } } else if (element.nodeName.toUpperCase() == "SELECT") { if (element.multiple) { elementValue = []; for (var i = 0; i < element.length; ++i) { if (element.options[i].selected) { elementValue.push(element.options[i].value); } } } else if (element.length == 0) { elementValue = null; } else { elementValue = element.value; } } else if (element.nodeName.toUpperCase() == "TEXTAREA") { elementValue = element.value; } if (elementValue instanceof Array) { for (var i = 0; i < elementValue.length; ++i) { encodedData += "&" + element.name + "=" + Anthem_Encode(elementValue[i]); } } else if (elementValue != null) { encodedData += "&" + element.name + "=" + Anthem_Encode(elementValue); } } } // ASP.NET 1.1 won't fire any events if neither of the following // two parameters are not in the request so make sure they're // always in the request. if (typeof form.__VIEWSTATE == "undefined") { encodedData += "&__VIEWSTATE="; } if (typeof form.__EVENTTARGET == "undefined") { encodedData += "&__EVENTTARGET="; } } } if (encodedData.length > 0) { encodedData = encodedData.substring(1); } Anthem_DebugRequestText(encodedData.split("&").join("/n&")); x.send(encodedData); if (!clientCallBack) { Anthem_DebugResponseText(x.responseText); result = Anthem_GetResult(x); if (result.error) { Anthem_DebugError(result.error); if (window.Anthem_Error) { Anthem_Error(result); } } if (updatePageAfterCallBack) { Anthem_UpdatePage(result); } Anthem_EvalClientSideScript(result); if (window.Anthem_PostCallBack) { Anthem_PostCallBack(); } } return result; } function Anthem_GetResult(x) { var result = { "value": null, "error": null }; var responseText = x.responseText; try { result = eval("(" + responseText + ")"); } catch (e) { if (responseText.length == 0) { result.error = "NORESPONSE"; } else { result.error = "BADRESPONSE"; result.responseText = responseText; } } return result; } function Anthem_SetHiddenInputValue(form, name, value) { var input = null; if (form[name]) { input = form[name]; } else { input = document.createElement("input"); input.setAttribute("name", name); input.setAttribute("type", "hidden"); } input.setAttribute("value", value); var parentElement = input.parentElement ? input.parentElement : input.parentNode; if (parentElement == null) { form.appendChild(input); form[name] = input; } } function Anthem_RemoveHiddenInput(form, name) { var input = form[name]; if (input != null && typeof(input) != "undefined") { var parentElement = input.parentElement ? input.parentElement : input.parentNode; if (parentElement != null) { form[name] = null; parentElement.removeChild(input); } } } function Anthem_FireEvent(eventTarget, eventArgument, clientCallBack, clientCallBackArg, includeControlValuesWithCallBack, updatePageAfterCallBack) { var form = document.getElementById(Anthem_FormID); Anthem_SetHiddenInputValue(form, "__EVENTTARGET", eventTarget); Anthem_SetHiddenInputValue(form, "__EVENTARGUMENT", eventArgument); Anthem_CallBack(null, null, null, null, null, clientCallBack, clientCallBackArg, includeControlValuesWithCallBack, updatePageAfterCallBack); form.__EVENTTARGET.value = ""; form.__EVENTARGUMENT.value = ""; } function Anthem_UpdatePage(result) { var form = document.getElementById(Anthem_FormID); if (result.viewState) { Anthem_SetHiddenInputValue(form, "__VIEWSTATE", result.viewState); } if (result.viewStateEncrypted) { Anthem_SetHiddenInputValue(form, "__VIEWSTATEENCRYPTED", result.viewStateEncrypted); } if (result.eventValidation) { Anthem_SetHiddenInputValue(form, "__EVENTVALIDATION", result.eventValidation); } if (result.controls) { for (var controlID in result.controls) { var containerID = "Anthem_" + controlID.split("$").join("_") + "__"; var control = document.getElementById(containerID); if (control) { control.innerHTML = result.controls[controlID]; if (result.controls[controlID] == "") { control.style.display = "none"; } else { control.style.display = ""; } } } } if (result.pagescript) { Anthem_LoadPageScript(result, 0); } } // Load each script in order and wait for each one to load before proceeding function Anthem_LoadPageScript(result, index) { if (index < result.pagescript.length) { try { var script = document.createElement('script'); script.type = 'text/javascript'; if (result.pagescript[index].indexOf('src=') == 0) { script.src = result.pagescript[index].substring(4); } else { if (script.canHaveChildren ) { script.appendChild(document.createTextNode(result.pagescript[index])); } else { script.text = result.pagescript[index]; } } var heads = document.getElementsByTagName('head'); if (heads != null && typeof(heads) != "undefined" && heads.length > 0) { var head = heads[0]; // The order that scripts appear is important since later scripts can // redefine a function. Therefore it is important to add every script // to the page and in the same order that they were added on the server. // On the other hand, if we just keep adding scripts the DOM will grow // unnecessarily. This code scans the <head> element block and removes // previous instances of the identical script. var found = false; for (var child = 0; child < head.childNodes.length; child++) { var control = head.childNodes[child]; if (control.tagName.toUpperCase() == "SCRIPT") { if (script.src.length > 0) { if (script.src == control.src) { found = true; break; } } else if (script.innerHTML.length > 0) { if (script.innerHTML == control.innerHTML) { found = true; break; } } } } if (found) { head.removeChild(control); } // Now we append the new script and move on to the next script. // Note that this is a recursive function. It stops when the // index grows larger than the number of scripts. document.getElementsByTagName('head')[0].appendChild(script); if (typeof script.readyState != "undefined") { script.onreadystatechange = function() { if (script.readyState != "complete" && script.readyState != "loaded") { return; } else { Anthem_LoadPageScript(result, index + 1); } } } else { Anthem_LoadPageScript(result, index + 1); } } } catch (e) { Anthem_DebugError("Error adding page script to head. " + e.name + ": " + e.message); } } } function Anthem_EvalClientSideScript(result) { if (result.script) { for (var i = 0; i < result.script.length; ++i) { try { eval(result.script[i]); } catch (e) { alert("Error evaluating client-side script!/n/nScript: " + result.script[i] + "/n/nException: " + e); } } } } function Anthem_DebugRequestText(text) { } function Anthem_DebugResponseText(text) { } function Anthem_DebugError(text) { } //Fix for bug #1429412, "Reponse callback returns previous response after file push". //see http://sourceforge.net/tracker/index.php?func=detail&aid=1429412&group_id=151897&atid=782464 function Anthem_Clear__EVENTTARGET() { var form = document.getElementById(Anthem_FormID); Anthem_SetHiddenInputValue(form, "__EVENTTARGET", ""); } function Anthem_InvokePageMethod(methodName, args, clientCallBack, clientCallBackArg) { Anthem_Clear__EVENTTARGET(); // fix for bug #1429412 return Anthem_CallBack(null, "Page", null, methodName, args, clientCallBack, clientCallBackArg, true, true); } function Anthem_InvokeMasterPageMethod(methodName, args, clientCallBack, clientCallBackArg) { Anthem_Clear__EVENTTARGET(); // fix for bug #1429412 return Anthem_CallBack(null, "MasterPage", null, methodName, args, clientCallBack, clientCallBackArg, true, true); } function Anthem_InvokeControlMethod(id, methodName, args, clientCallBack, clientCallBackArg) { Anthem_Clear__EVENTTARGET(); // fix for bug #1429412 return Anthem_CallBack(null, "Control", id, methodName, args, clientCallBack, clientCallBackArg, true, true); } function Anthem_PreProcessCallBack( control, e, eventTarget, causesValidation, validationGroup, imageUrlDuringCallBack, textDuringCallBack, enabledDuringCallBack, preCallBackFunction, callBackCancelledFunction, preProcessOut ) { preProcessOut.Enabled = !control.disabled; var preCallBackResult = true; if (preCallBackFunction) { preCallBackResult = preCallBackFunction(control); } if (typeof(preCallBackResult) == "undefined" || preCallBackResult) { var valid = true; if (causesValidation && typeof(Page_ClientValidate) == "function") { valid = Page_ClientValidate(validationGroup); } if (typeof(WebForm_OnSubmit) == "function") { valid = WebForm_OnSubmit(); } if (valid) { var inputType = control.getAttribute("type"); inputType = (inputType == null) ? '' : inputType.toUpperCase(); if (inputType == "IMAGE" && e != null) { var form = document.getElementById(Anthem_FormID); if (e.offsetX) { Anthem_SetHiddenInputValue(form, eventTarget + ".x", e.offsetX); Anthem_SetHiddenInputValue(form, eventTarget + ".y", e.offsetY); } else { Anthem_SetHiddenInputValue(form, eventTarget + ".x", e.clientX - control.offsetLeft + 1); Anthem_SetHiddenInputValue(form, eventTarget + ".y", e.clientY - control.offsetTop + 1); } } if (imageUrlDuringCallBack || textDuringCallBack) { if (control.nodeName.toUpperCase() == "INPUT") { if (inputType == "CHECKBOX" || inputType == "RADIO" || inputType == "TEXT") { preProcessOut.OriginalText = GetLabelText(control.id); SetLabelText(control.id, textDuringCallBack); } else if (inputType == "IMAGE") { if (imageUrlDuringCallBack) { preProcessOut.OriginalText = control.src; control.src = imageUrlDuringCallBack; } else { preProcessOut.ParentElement = control.parentElement ? control.parentElement : control.parentNode; if (preProcessOut.ParentElement) { preProcessOut.OriginalText = preProcessOut.ParentElement.innerHTML; preProcessOut.ParentElement.innerHTML = textDuringCallBack; } } } else if (inputType == "SUBMIT") { preProcessOut.OriginalText = control.value; control.value = textDuringCallBack; } } else if (control.nodeName.toUpperCase() == "SELECT") { preProcessOut.OriginalText = GetLabelText(control.id); SetLabelText(control.id, textDuringCallBack); } else { preProcessOut.OriginalText = control.innerHTML; control.innerHTML = textDuringCallBack; } } control.disabled = (typeof enabledDuringCallBack == "undefined") ? false : !enabledDuringCallBack; return true; } else { return false; } } else { if (callBackCancelledFunction) { callBackCancelledFunction(control); } return false; } } function Anthem_PreProcessCallBackOut() { // Fields this.ParentElement = null; this.OriginalText = ''; this.Enabled = true; } function Anthem_PostProcessCallBack( result, control, eventTarget, clientCallBack, clientCallBackArg, imageUrlDuringCallBack, textDuringCallBack, postCallBackFunction, preProcessOut ) { if (postCallBackFunction) { postCallBackFunction(control); } control.disabled = !preProcessOut.Enabled; var inputType = control.getAttribute("type"); inputType = (inputType == null) ? '' : inputType.toUpperCase(); if (inputType == "IMAGE") { var form = document.getElementById(Anthem_FormID); Anthem_RemoveHiddenInput(form, eventTarget + ".x"); Anthem_RemoveHiddenInput(form, eventTarget + ".y"); } if (imageUrlDuringCallBack || textDuringCallBack) { if (control.nodeName.toUpperCase() == "INPUT") { if (inputType == "CHECKBOX" || inputType == "RADIO" || inputType == "TEXT") { SetLabelText(control.id, preProcessOut.OriginalText); } else if (inputType == "IMAGE") { if (imageUrlDuringCallBack) { control.src = preProcessOut.OriginalText; } else { preProcessOut.ParentElement.innerHTML = preProcessOut.OriginalText; } } else if (inputType == "SUBMIT") { control.value = preProcessOut.OriginalText; } } else if (control.nodeName.toUpperCase() == "SELECT") { SetLabelText(control.id, preProcessOut.OriginalText); } else { control.innerHTML = preProcessOut.OriginalText; } } if (clientCallBack) { clientCallBack(result, clientCallBackArg); } } function Anthem_FireCallBackEvent( control, e, eventTarget, eventArgument, causesValidation, validationGroup, imageUrlDuringCallBack, textDuringCallBack, enabledDuringCallBack, preCallBackFunction, postCallBackFunction, callBackCancelledFunction, includeControlValuesWithCallBack, updatePageAfterCallBack ) { var preProcessOut = new Anthem_PreProcessCallBackOut(); var preProcessResult = Anthem_PreProcessCallBack( control, e, eventTarget, causesValidation, validationGroup, imageUrlDuringCallBack, textDuringCallBack, enabledDuringCallBack, preCallBackFunction, callBackCancelledFunction, preProcessOut ); if (preProcessResult) { Anthem_FireEvent( eventTarget, eventArgument, function(result) { Anthem_PostProcessCallBack( result, control, eventTarget, null, null, imageUrlDuringCallBack, textDuringCallBack, postCallBackFunction, preProcessOut ); }, null, includeControlValuesWithCallBack, updatePageAfterCallBack ); } } function AnthemListControl_OnClick( e, causesValidation, validationGroup, textDuringCallBack, enabledDuringCallBack, preCallBackFunction, postCallBackFunction, callBackCancelledFunction, includeControlValuesWithCallBack, updatePageAfterCallBack ) { var target = e.target || e.srcElement; if (target.nodeName.toUpperCase() == "LABEL" && target.htmlFor != '') return; var eventTarget = target.id.split("_").join("$"); Anthem_FireCallBackEvent( target, e, eventTarget, '', causesValidation, validationGroup, '', textDuringCallBack, enabledDuringCallBack, preCallBackFunction, postCallBackFunction, callBackCancelledFunction, true, true ); } function GetLabelText(id) { var labels = document.getElementsByTagName('label'); for (var i = 0; i < labels.length; i++) { if (labels[i].htmlFor == id) { return labels[i].innerHTML; } } return null; } function SetLabelText(id, text) { var labels = document.getElementsByTagName('label'); for (var i = 0; i < labels.length; i++) { if (labels[i].htmlFor == id) { labels[i].innerHTML = text; return; } } } //]]> </script><script src="/WebResource.axd?d=1wkz58Z1rsBL-eFHJPld5ERhyO-4qXtUzHp7Q1KwrOE1&amp;t=632963535947587500" type="text/javascript"></script><script type="text/javascript"> <!-- function WebForm_OnSubmit() { if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) return false; return true; } // --> </script>
CSDN| 社区| 技术中心| BLOG首页| 我的首页| 个人档案| 联系作者| 聚合 | | 搜索| 登录
485篇原创: 0篇翻译: 8篇转载: 958875次点击: 584个评论: 79个Trackbacks
<script type="text/javascript">document.write("<img src=http://counter.csdn.net/pv.aspx?id=26 border=0 width=0 height=0>");</script>

公告

<script type="text/javascript"><!-- google_ad_client = "pub-3051157228350391"; google_ad_width = 120; google_ad_height = 600; google_ad_format = "120x600_as"; google_ad_type = "text_image"; google_ad_channel ="4498546349"; google_color_border = "FFFFFF"; google_color_bg = "FFFFFF"; google_color_link = "000000"; google_color_url = "336699"; google_color_text = "333333"; //--></script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </script><iframe name="google_ads_frame" marginwidth="0" marginheight="0" src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-3051157228350391&amp;dt=1177200651790&amp;lmt=1177200651&amp;format=120x600_as&amp;output=html&amp;channel=4498546349&amp;url=http%3A%2F%2Fblog.csdn.net%2Farielxp%2Farchive%2F2005%2F03%2F18%2F322771.aspx&amp;color_bg=FFFFFF&amp;color_text=333333&amp;color_link=000000&amp;color_url=336699&amp;color_border=FFFFFF&amp;ad_type=text_image&amp;ref=http%3A%2F%2Fblog.csdn.net%2Farielxp%2Fcategory%2F14896.aspx%3FPageNumber%3D2&amp;cc=471&amp;u_h=768&amp;u_w=1024&amp;u_ah=740&amp;u_aw=1024&amp;u_cd=32&amp;u_tz=540&amp;u_his=4&amp;u_java=true" frameborder="0" width="120" scrolling="no" height="600" allowtransparency="allowtransparency"></iframe>

文章

收藏

    相册

    <!--category title-->

      存档

      最近评论



      <script language="javascript" src="http://tag.csdn.net/urltag.aspx" type="text/javascript"></script> CSDN 推荐tag:属性jsp页面语法文件代码
      <script type="text/javascript">function StorePage(){d=document;t=d.selection?(d.selection.type!='None'?d.selection.createRange().text:''):(d.getSelection?d.getSelection():'');void(keyit=window.open('http://www.365key.com/storeit.aspx?t='+escape(d.title)+'&u='+escape(d.location.href)+'&c='+escape(t),'keyit','scrollbars=no,width=475,height=575,left=75,top=20,status=no,resizable=yes'));keyit.focus();}</script>
       JSP actions 使用您可以动态的插入一个文件,重用JavaBeans组件,前进到另一个页面,或为Java 插件生成一个HTML。可以使用的action 有:

        (1) jsp:include --在页面被请求时包含进一个文件。

        (2) jsp:useBean--找到或实例化一个JavaBean。

        (3) jsp:setProperty--设置一个JavaBean属性。

        (4) jsp:getProperty--将JavaBean的属性插入到输出。

        (5) jsp:forward--让请求者可以向前到一个新的页面。

        (6) jsp:plugin--用OBJECT或EMBED标签为Java plugins生成特定的浏览器的代码。

        1、jsp:include Action

        这个action使您可以在即将生成的页面上包含进一些文件:

      <jsp:include page="relative URL" flush="true" />
        
        与include directive不同,这个action是在页面被请求时才将文件包含进来,而,include directive则是在JSP页面被转换为servlet时包含文件。为了提高效率,include action做了一点小小的牺牲,即,它不允许被包含的页面含有一般的JSP代码(例如,不可设置HTTP头),但是,它具有显著的灵活性,如下面的JSP 代码,它实现将四个不同的片段插入如下的页面。每一次当标题改变的时候,您仅需修改这四个文件而无须更改主要的JSP 页面。

        WhatsNew.jsp

      <HTML>
      <HEAD>
      <TITLE> JSP教程</TITLE>
      <BODY >
      <CENTER>
      <TABLE BORDER=5 BGCOLOR="#EF8429">
      <TR><TH CLASS="TITLE"> What"s New at Chinese comic sites</TABLE>
      </CENTER>
      <P>
      Here is a summary of our four most recent news stories:
      <OL>
      <LI><jsp:include page="news/Item1.html" flush="true"/>
      <LI><jsp:include page="news/Item2.html" flush="true"/>
      <LI><jsp:include page="news/Item3.html" flush="true"/>
      <LI><jsp:include page="news/Item4.html" flush="true"/>
      </OL>
      </BODY>
      </HTML>

        当然您可以定义自己? ML文件,但有一点请注意:

        您应该将文件放到您的JSP目录下的news目录内。

        jsp:useBean Action 的使用

        一、 语法:

      <jsp:useBean
      id="beanInstanceName"
      scope="page|request|session|application"
      { class="package.class" |
      type="package.class" |
      class="package.class" type="package.class" |
      beanName="{package.class | <%= expression %>}" type="package.class"
      }
      { /> |
      > 其他元素
      </jsp:useBean>
      }

        这个action使您能将一个JavaBean装入一个JSP页面。这是一个非常有用的能力,因为它使您可以使用可重用的JAVA类而不需牺牲性能。最简单的语法用于指定一个bean:

      <jsp:useBean id="name" class="package.class" />


        这通常意味着“实例化一个类的对象通过指定一个类,并将之与一个通过id指定名称的变量绑定”。然而,就象我们看到的,您可以指定一个scope属性来使得bean不仅仅与当前的页面相联系。在这种情形下,得到一个对已存在的bean的引用是非常有用的,而且,仅当没有相同的id和scope的bean存在时才创建一个新的。现在,您已有了bean,您可以通过jsp:setProperty来修改它,或者,通过使用之前用id指定的名字来使用scriptlet或明确的调用方法。当您说“这个bean有一个称为foo的X类型的属性”,您真正的意思是“这个类有一个称为getFoo的方法,它返回X类型的某类值,还有另一个方法称为setFoo,它以X为参数。”这jsp:setProperty action 将在下一单元详细的介绍,但是现在您既可以给出一个明确的值,给出一个属性来说明此值是从request的参数继承而来,也可以仅仅列出属性来标志此值应该从与属性名同名的参数继承而来。您可以通过调用适用的getXxx方法,或更普遍的,使用jsp:getProperty action,来得到已存在的JSP表达式或scriptlet属性。

        请注意,为bean指定的类必须在服务器的规则的类路径下,而不是用来保留当改变时自动装载的类的路径。例如,在Java Web Server上,它和它所用的类必须到类的目录或在lib目录下的一个jar文件内,而不是在servlets的目录下。

        下面让我们来看一个非常简单的例子,它装载一个bean并且设置/得到一个简单的串参数。

      BeanTest.jsp

      <HEAD>
      <TITLE>Reusing JavaBeans in JSP</TITLE>
      </HEAD>
      <BODY>
      <CENTER>
      <TABLE BORDER=5>
      <TR><TH CLASS="TITLE">
      Reusing JavaBeans in JSP</TABLE>
      </CENTER>
      <P>
      <jsp:useBean id="test" class="hall.SimpleBean" />
      <jsp:setProperty name="test"
      property="message"
      value="Hello WWW" />
      <H1>Message: <I>
      <jsp:getProperty name="test" property="message" />
      </I></H1>
      </BODY>

        SimpleBean.java

        以下是bean的原代码:

      package hall;
      public class SimpleBean {
       private String message = "No message specified";
       public String getMessage() {
        return(message);
       }
       public void setMessage(String message) {
        this.message = message;
       }
      }

        运行结果为:页面输出: Reusing JavaBeans in JSP

        Message:Hello WWW

        二、jsp:useBean 的详细用法

        最简单的使用bean的方式是:

        
      <jsp:useBean id="name" class="package.class"/>
        为了装载bean,需要用jsp:setProperty和 jsp:getProperty来修改和检索bean的属性。且,还有两种别的选项。首先,您可以使用容器的格式,也就是:

      <jsp:useBean ...>
      Body
      </jsp:useBean>

        要指出的是,Body部分应该仅在bean第一次实例化时被执行,而不是在每次被找到和使用时。Beans能够被共享,因此,并不是所有的jsp:useBean 陈述都产生一个新的bean的实例。其次,除了id 或class以外,还有三种属性您可以使用:scope,type,和beanName。这些属性总结如下:

      属性 含义
      id 给一个变量命名,此变量将指向bean。如果发现存在一个具有相同的id和scope 的bean则使用之而不新建一个。
      class 指出bean的完整的包名。
      scope 指明bean在之上可以被使用的前后关系。有四个可能的值:page,request,session,和application。缺省为page,表明bean仅在当前页可用(保存在当前的PageContext中)。request的一个值表明bean仅用于当前客户端的请求(保存在ServletRequest对象中)。Session的值指出在当前的HttpSession的生命周期内,对象对所有的页面可用。 最后,application的值指出对象对所有共享ServletsContext的页面可以使用。使用jsp:useBean 仅在没有相同的id和scope 的bean时创建一个新的bean,如果已有则使用之,并忽略以jsp:useBean标志开始和结尾的代码。
      type 指明将指向对象的变量的类型。这必须与类名相匹配或是一个超类或者是一个实现类的接口。记住,变量的名由id属性来指定。
      beanName 赋予bean一个名字,您应该在Beans的实例化方法中提供。它允许您给出type和一个beanName,并省略类属性。
          三、jsp:setProperty Action

        语法:

      <jsp:setProperty
      name="beanInstanceName"
      {
       property="*" | property="propertyName" [ param="parameterName" ] | property="propertyName" value="{string | <%= expression %>}"
      }
      />

        在前面我们就知道了可以使用 jsp:setProperty 来为一个bean的属性赋值。您可以使用两种方式实现它。其一是,在jsp:useBean后(而不是在之内)使用jsp:setProperty:

      <jsp:useBean id="myName" ... />
      ...
      <jsp:setProperty name="myName"
      property="someProperty" ... />

        在这种方式中,jsp:setProperty 将被执行无论是否已有一个具有相同的id和scope的bean存在。另一种方式是,jsp:setProperty出现在jsp:useBean 元素内,如:

      <jsp:useBean id="myName" ... >
      ...
      <jsp:setProperty name="myName" property="someProperty" ... />
      </jsp:useBean>

        此种情况下,jsp:setProperty仅在新的对象被实例化时才执行。

        以下是四种jsp:setProperty的可用的属性:

      属性 用法
      name 这是一个必选属性。它指出哪一个bean的属性将被设置。jsp:usebean必须出现在jsp:setProperty之前。
      property 这是一个必选属性。表明您将设置哪一个属性。然而,有一个特殊的情况:如果以"*"为值意味着,所有的名称与bean的属性匹配的request参数都将被传递到相应的属性设置方法。
      value 这是一个可选属性。它指定被设置的属性的值。字符串的值通过相应的对象或包的标准的valueOf方法将自动的转换为numbers,boolean,Boolean,byte,Byte,char,和Character。例如,boolean或Boolean属性的值“true”将通过Boolean.valueOf方法转化,而,一个int或Integer属性的值“42”将通过Integer.valueOf转化。您不能同时使用value和param属性,但,两个都不用是允许的。
      param 这是一个可选属性。它指明了bean的属性应该继承的request的参数。如果当前的request没有这样的一个参数,就什麽也不做:系统并不将null传给设置属性的方法。因此,您可以使用bean的缺省值。例如下面的这段程序执行“将numberOfItems属性设置为任意numItems request参数的值,如果有这样的一个request参数,否则什么也不做。”

      <jsp:setProperty name="orderBean" property="numberOfItems" param="numItems" />
        

        如果您将value和param同时缺省,这和您将param的名称设为bean的属性名相同一样。您可以通过将name的值设置为”*”和省略value和param来自动的使用与bean的属性相应的request的属性。在这种情况下,服务器将反复的查找可用的属性和request参数来匹配具有相同名字的。

        四、jsp:getProperty Action

        语法:

      <jsp:getProperty name="beanInstanceName" property="propertyName" />

       
        这个属性检索出bean的属性的值并将之转化为一个字符串,然后将之插入到输出。它有两个必选属性:name,在之前用jsp:useBean引入的名称,property,必须被插入值的属性。

      <script type="text/javascript">&amp;lt;!--google_ad_client = "pub-3051157228350391";google_alternate_color = "FF0000";google_ad_width = 728;google_ad_height = 90;google_ad_format = "728x90_as";google_ad_channel ="9050871643";google_page_url = document.location;google_color_border = "CCCCCC";google_color_bg = "FFFFFF";google_color_link = "000000";google_color_url = "666666";google_color_text = "333333";//--&amp;gt;</script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script><iframe name="google_ads_frame" marginwidth="0" marginheight="0" src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-3051157228350391&amp;dt=1177200653759&amp;lmt=1177200653&amp;prev_fmts=120x600_as&amp;format=120x600&amp;output=html&amp;url=http%3A%2F%2Fblog.csdn.net%2Farielxp%2Farchive%2F2005%2F03%2F18%2F322771.aspx&amp;ref=http%3A%2F%2Fblog.csdn.net%2Farielxp%2Fcategory%2F14896.aspx%3FPageNumber%3D2&amp;cc=20&amp;u_h=768&amp;u_w=1024&amp;u_ah=740&amp;u_aw=1024&amp;u_cd=32&amp;u_tz=540&amp;u_his=4&amp;u_java=true" frameborder="0" width="120" scrolling="no" height="600" allowtransparency="allowtransparency"></iframe><iframe name="google_ads_frame" marginwidth="0" marginheight="0" src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-3051157228350391&amp;dt=1112785763609&amp;alt_color=FF0000&amp;format=728x90_as&amp;output=html&amp;channel=9050871643&amp;url=http%3A%2F%2Fblog.csdn.net%2Ffckeditor%2Feditor%2Ffckeditor.html%3FInstanceName%3DEditor_Edit_FCKEditor%26Toolbar%3DDefault&amp;color_bg=FFFFFF&amp;color_text=333333&amp;color_link=000000&amp;color_url=666666&amp;color_border=CCCCCC&amp;u_h=768&amp;u_w=1024&amp;u_ah=740&amp;u_aw=1024&amp;u_cd=32&amp;u_tz=480&amp;u_his=4&amp;u_java=true" frameborder="0" width="728" scrolling="no" height="90" allowtransparency="allowtransparency"></iframe><iframe name="google_ads_frame" marginwidth="0" marginheight="0" src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-3051157228350391&amp;dt=1112785773515&amp;prev_fmts=728x90_as&amp;format=728x90&amp;output=html&amp;u_h=768&amp;u_w=1024&amp;u_ah=740&amp;u_aw=1024&amp;u_cd=32&amp;u_tz=480&amp;u_his=4&amp;u_java=true" frameborder="0" width="728" scrolling="no" height="90" allowtransparency="allowtransparency"></iframe>

      Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=322771

      分享到:
      评论

      相关推荐

      Global site tag (gtag.js) - Google Analytics