Technorati 标签:  jsp 教程, javeee

承接上一节 jsp page 指令 的讲解,这一次将会谈到另外一个指令 include 和 其他的一些相关的知识。

一、page include 属性

include 指令用于将指定的文件包含到容器当中,包含操作是在 jsp 文件编译时发生的,包含过程是静态的。包含的文件可以是 jsp、html,java程序或其他静态文本文件。include 指令的语法格式如下:

<%@ include file="file-URL" %>

其中,file-url 为包含的文件名及其路径,执行include 指令的效果相当于将 file-url 文件的内容嵌入到指令所在的文职。这种嵌入操作是在编译前一刻发生,随后对嵌入后得到的 jsp 文件进行编译,编译后形成的 servlet 融合了包含者和被包含着,他们在 servlet 中不再有包含和被包含的区别。

被插入的文件要求满足一下条件:

(1)被插入的文件必须与当前 jsp 页面在同一 web 目录下

(2)被插入的文件与当前 jsp 页面合并后的jsp 页面必须符合 jsp 的语法规则。

include 指令为简化jsp 程序设计复杂性提供了一种良好的机制。对于复杂的jsp 页面,我们将之分成若干个文件(导航栏,脚注,表格等),然后分别测试,最后利用include 指令将它们包含到主 jsp 文件中即可。

下面给出一个Demo:

mian.jsp代码:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <div id="mainbody">
 
    

this is the mainbody

 
   
 
   
    <%@ include file="footer.jsp" %>
</body>
</html>

footer.jsp 代码如下:

<div class="footer">
 
    

CopyRight@ 2013 Design by tiy920415@126.com

 
   
<!-- end .footer –>

可以相应导航栏和其他不变的元素。

输出如下:

160147187.jpg

二、jsp 行为标签 jsp:inclue

指令标题 include 是在编译前将文件包含进去的,不过在jsp 里还有一个类似的但又不一样的行为标签 jsp:include,在接受请求时包含其他文件。

<jsp:include> 元素用于在 jsp 页面中包含静态或动态文件资源。但这两种包含文件的结果是不同的——如果被包含文件是静态文件,那么这种包含仅仅把被包含文件内容嵌入到<jsp:include> 元素所在的jsp 页面,如果包含的文件是动态文件,那么这个被包含的文件也会被jsp 编译器执行,执行结果被加入到<jsp:inclue>元素所在的 jsp页面。

语法格式如下:

<jsp:include page="url-spec">

Demo:

newItem.jsp代码如下:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    Here is a summary of our four most recent news stories:
    <ol>
        <li><jsp:include page="item1.jsp" />
        <li><jsp:include page="item2.jsp" />
        <li><jsp:include page="item3.jsp" />
        <li><jsp:include page="item4.jsp" />
    </ol>
</body>
</html>


item1.jsp,item2.jsp等代码如下:

//item1.jsp 代码
Bill Gates acts humble. In a startling and unexpected
development, Microsoft big wig Bill Gates put on an open act of
humility yesterday.
<a href="#">more details...
 
//item2.jsp
Scott McNealy acts serious. In an unexpected twist, 
wisecracking Sun head Scott McNealy was sober and subdued at 
yesterday's meeting.
<a href="#">more details...
 
//item3.jsp
Larry Ellison acts conciliatory. Catching his competitors 
off guard yesterday, Oracle prez Larry Ellison referred to his 
rivals in friendly and respectful terms.
<a href="#">more details...
 
//item4.jsp
Sportscaster uses "literally" correctly. In an apparent 
slip of the tongue, a popular television commentator was 
heard to use the word "literally" when he did not
mean "figuratively."
<a href="#">more details...

输出如下:

160256922.jpg

三、在 jsp 页面包含applet

因为applet 已经不怎么使用了,所以如果你对此不感兴趣的,可以到此直接结束阅读。

在 jsp 页面嵌入applet,要用到行为标签 jsp:plugin.<jsp:plugin>元素用于在浏览器播放或显示一个对象,如applet或 bean。当 jsp文件被编译并将结果返回到浏览器时,<jsp:plugin>会根据浏览器的版本替换成<object>(用于html4.0),如果没有java 插件,还需指定从哪里下载这个java 插件。

语法格式如下:

<jsp:plugin options>: .. 可以选择填写以下属性(加粗的属性是必须包含的):

type = bean or applet 标识组件类型是 bean 还是 applet

code = classname of plugin object 插件对象名 类名.class

codebase = location of class object 类的文件目录

name,align, archive, height,width,hspace, vspace,iepluginurl,nspluginurl, jrevision

其他属性解释如下:

name="instanceName" 这个Bean或applet实例的名字,它将会在Jsp其它的地方调用.

align = “bottom|top|left|rigeht|middle”——用html语法

archive = “url to archive” 一些由逗号分开的路径名,这些路径名用于预装一些将要使用的class,这会提高applet的性能.

height="displayPixels" ;displayPixels" Applet或Bean将要显示的长宽的值,此值为数字,单位为象素.

hspace="leftRightPixels" vspace="topBottomPixels" Applet或Bean显示时在屏幕左右,上下所需留下的空间,单位为象素.

iepluginurl="URLToPlugin" IE用户能够使用的JRE的下载地址,此值为一个标准的URL

nspluginurl="URLToPlugin" Netscape Navigator用户能够使用的JRE的下载地址,此值为一个标准的URL,

jreversion="JREVersionNumber | 1.1" Applet或Bean运行所需的Java Runtime Environment (JRE) 的版本. 缺省值是 1.1.

另外可能还会用到的两个行为标签有:

<jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" /> ] </jsp:params>

用来指定 applet 或 bean 运行所需要的参数。

<jsp:fallback> text message for user </jsp:fallback> </jsp:fallback>

如果插件能启动,则显示该标签指定的内容。如:

<jsp:plugin type="applet" code="MyApplet.class">
    <jsp:fallback>
Error: this example requires Java.
    </jsp:fallback>
</jsp:plugin>

Demo:显示带有背影的文本.

shadowedText.jsp 代码如下:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <jsp:plugin type="applet" code="ShadowedTextApplet.class"
     codebase="com.tools"  style="color: #006080">"475" height="350">
        <jsp:params>
            <jsp:param name="message" value="Your message here" />
        </jsp:params>
        <jsp:fallback>
this example requires java
        </jsp:fallback>
    </jsp:plugin>
</body>
</html>


ShadowedTestApplet.java

package com.tools;
 
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
 
publicclass ShadowedTextApplet extends JApplet implements ActionListener {
private JTextField messageField;
private JComboBox<String> fontBox;
private JSlider fontSizeSlider;
private JButton showFrameButton;
 
publicvoid init() {
        Color bgColor = new Color(0xFD, 0xF5, 0xE6);
        Font font = new Font("Serif", Font.PLAIN, 16);
        Container contentPane = getContentPane();
        contentPane.setLayout(new GridLayout(4, 1));
        contentPane.setbgColor);< /pre>
//用 JTextField 获取初始文本
        messageField = new JTextField(20);
        String message = getParameter("message");
if (message != null) {
            messageField.setText(message);
        }
        JPanel messagePanel = new LabelPanel("Message:", "Message to Display", bgColor, font, messageField);
        contentPane.add(messagePanel);
//使用复选框选择字体
        GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] fontNames = env.getAvailableFontFamilyNames();
        fontBox = new JComboBox<>(fontNames);
        fontBox.setEditable(false);
        JPanel fontPanel = new LabelPanel("Font:", "Font to Use", bgColor, font, fontBox);
        contentPane.add(fontPanel);
// 使用 JSlider选择文字大小
        fontSizeSlider = new JSlider(0, 150);
        fontSizeSlider.setbgColor);< /pre>
        fontSizeSlider.setMajorTickSpacing(50);
        fontSizeSlider.setMinorTickSpacing(25);
        fontSizeSlider.setPaintTicks(true);
        fontSizeSlider.setPaintLabels(true);
        JPanel fontSizePanel = new LabelPanel("Font Size:", "Font Size to Use", bgColor, font, fontSizeSlider);
        contentPane.add(fontSizePanel);
//点击按钮便可打开阴影文字
        showFrameButton = new JButton("Open Frame");
        showFrameButton.addActionListener(this);
        JPanel buttonPanel = new LabelPanel("Show Shadowed Text:", "Open JFrame to Show Shadowed Text", bgColor, font,
                showFrameButton);
        contentPane.add(buttonPanel);
    }
 
publicvoid actionPerformed(ActionEvent event) {
        String message = messageField.getText();
if (message.length() == 0) {
            message = "No Message";
        }
        String fontName = (String) fontBox.getSelectedItem();
int fontSize = fontSizeSlider.getValue();
        JFrame frame = new ShadowedTextFrame(message, fontName, fontSize);
        frame.pack();
        frame.setVisible(true);
    }
}

LabelPanle.jave

package com.tools;
 
import java.awt.Color;
import java.awt.Font;
 
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
 
 
publicclass LabelPanel extends JPanel {
public LabelPanel(String labelMessage, String title, Color bgColor, Font font, JComponent component) {
        setbgColor);< /pre>
        setFont(font);
        setBorder(BorderFactory.createTitledBorder(title));
        JLabel label = new JLabel(labelMessage);
        label.setFont(font);
        add(label);
        component.setFont(font);
        add(component);
    }
 
}

ShadowedTextFrame.java

package com.tools;
 
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.TextLayout;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
 
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
 
publicclass ShadowedTextFrame extends JFrame {
 
privateint width = 400;
privateint height = 300;
 
private TextLayout textLayout;
 
public ShadowedTextFrame(String message, String fontName, int fontSize) {
        initUI();
        BufferedImage image = createImage(message,fontName,fontSize);
        add(new JLabel(new ImageIcon(image)));
    }
 
private BufferedImage createImage(String message, String fontName, int fontSize) {
 
    
int x = 10;
int y = 100;
 
        Font font = new Font(fontName, Font.ITALIC, 50);
 
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g1 = image.createGraphics();
        setRenderingHints(g1);
        textLayout = new TextLayout(message, font, g1.getFontRenderContext());
        g1.setPaint(Color.WHITE);
        g1.fillRect(0, 0, width, height);
 
        g1.setPaint(new Color(150, 150, 150));
        textLayout.draw(g1, x + 3, y + 3);
        g1.dispose();
 
float[] kernel = { 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f };
 
        ConvolveOp op = new ConvolveOp(new Kernel(3, 3, kernel), ConvolveOp.EDGE_NO_OP, null);
        BufferedImage image2 = op.filter(image, null);
 
        Graphics2D g2 = image2.createGraphics();
        setRenderingHints(g2);
        g2.setPaint(Color.BLACK);
        textLayout.draw(g2, x, y);
 
return image2;
    }
 
privatevoid initUI() {
 
        setTitle("Shadowed Text");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(width, height);
        setLocationRelativeTo(null);
    }
 
privatevoid setRenderingHints(Graphics2D g) {
 
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    }
 
 
    
}

因为需要在浏览器安装插件,在这里只能给出大致的运行效果如下:

160351531.jpg