JSP组件创建 [英] JSP Component Creation

查看:144
本文介绍了JSP组件创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建JSP页面时,我经常想要做的一件事就是能够执行以下操作:

When creating JSP pages one thing that I'd often like is the ability to do something like this:

<jsp:include page="fancystoryrenderer.jsp" value="${aStoryObjectInMyModel}/>

...

fancystoryrenderer.jsp

<div id="fancymainbody">
    ...
    ${theStory.title}
    ...
</div>

这的主要重要特征是,我可以在同一JSP页面上的不同位置重用相同的组件,而不必复制粘贴该组件并为故事变量指定不同的名称,请注意该故事在在JSP中,而不是在"aStoryObjectInMyModel"中,我们的模型之间的联系已被视图破坏,在这种情况下,这是一件好事.另外,我知道您可以将参数传递到JSP视图,但是我根本不希望从请求对象中获取属性,我希望能够使用来自表达式语言的参数.

The main important characteristics of this is that I can reuse the same component on the same JSP page in different places without having to copy paste the component and give the story variables different names, notice that the story is called "theStory" in the JSP and not "aStoryObjectInMyModel", the linkage between our model has been broken by the view, which is a good thing in this case. Also, I know you can pass a parameter to the JSP view, but I DO NOT WANT to grab attributes from the request object at all, I want to be able to use the parameters from expression language.

您如何做到的?

我正在使用Spring-MVC和JSP,请不要添加任何框架,我有兴趣仅使用当前拥有的Web堆栈来使其工作.

I am using Spring-MVC and JSP, please no added frameworks, I'm interested in getting this to work using only the web stack I currently have.

推荐答案

使用所谓的标记文件"可以将其保存.标记文件基本上是放在WEB-INF/tags下的jsps,然后可以像taglib一样使用.我在此示例中使用的是xml语法,但它也应与较早的语法一起使用.

This can be arhcives using so called "tag files". Tag files are basically jsps that are put under WEB-INF/tags and that can then be used like a taglib. I am using the xml syntax in this example but it should also work with the older syntax.

/WEB-INF/tags/mytag.jspx

/WEB-INF/tags/mytag.jspx

<?xml version='1.0' encoding='utf-8'?>
<jsp:root version="2.1" xmlns:jsp="http://java.sun.com/JSP/Page">
    <jsp:directive.attribute name="mybean" required="true" rtexprvalue="true" type="mypackage.MyBean"/>
    <div>
       ${mybean.myproperty}
    </div>
</jsp:root>

test.jspx

test.jspx

<?xml version='1.0' encoding='utf-8'?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1" xmlns:tags="urn:jsptagdir:/WEB-INF/tags/">
    <jsp:directive.page contentType="text/html; charset=utf-8"/>
    <div>
      <tags:mytag mybean="${mymodel.mybean}"/>
    </div>
</jsp:root>

您可能还需要在WEB-INF/tags中有一个hidden.tld文件来设置taglib版本:

You might also need a file implicit.tld in WEB-INF/tags to set the taglib version:

<?xml version='1.0' encoding='utf-8'?>
<taglib xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
    version="2.1" xmlns="http://java.sun.com/xml/ns/javaee">
    <tlib-version>2.1</tlib-version>
</taglib>

这篇关于JSP组件创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆