表达式语言和JSTL
创建一个HTML文件,要求用户输入待转换的摄氏温度,通过按钮提交请求一个JSP页面,返回对应的华氏温度。
其中:华氏温度 = 1.8*摄氏温度 + 32。
JSP文件必须使用表达式语言(Expression Language)获取待转换的摄氏温度,并使用表达式语言计算对应的华氏温度,使用JSTL的核心标签库中的out标签显示摄氏温度和华氏温度。
JSP示例代码为(假设表单中输入摄氏温度值的输入控件名称为ctemp):
注意:
(1)在JSP页面中引入某个具体的JSTL标签库,必须在JSP文件中写入:
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
(2)必须把2个jar文件(分别是jstl.jar和standard.jar)放到web-inf/lib/下。
2个jar文件的下载及使用请参照:https://www.runoob.com/jsp/jsp-jstl.html
操作说明
在Eclipse中,建立名为“TempConvert”的动态网页项目
由于实验中用到JSTL标签,所以要导入jstl.jar和standard.jar两个JAR包到“web-inf/lib/”下,如图5-16。可右击WEBContent中的WEB-INF中的lib子目录,在弹出菜单项中选择“import…”、“General”、“File System”引入上述2个jar文件。Eclipse会自动将两个JAR包配置到Path中。
在“WebContent”文件夹上点击右键新建HTML文件
在弹出的对话框中,设置HTML文件名为“tempConvert.html”
修改HTML文件内容:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv= "Content-Type" content="text/html; charset=UTF-8" >
<title>Get a Celsius temperature</title>
</head>
<body>
<form action = "tempConvert.jsp" method = "post">
<p>
Celsius temperature:
<input type = "text" name = "ctemp" /> <br />
<input type = "submit" value = "Convert to Fahrenheit" />
</p>
</form>
</body>
</html>
再新建JSP文件,名称为“tempConvert.jsp”
由于用到了JSTL标签,所以在JSP页面开始要声明JSTL标签:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
然后修改JSP页面内容,来接收请求:
<html>
<head>
<meta charset="UTF-8">
<title>Temperature converter</title>
</head>
<body>
<p>
Given temperature in Celsius:
<c:out value="${param.ctemp}" />
<br/>
Temperature in Fahrenheit:
<c:out value="${(1.8 * param.ctemp) + 32 }" />
</p>
</body>
</html>
页面编写完成后,将项目部署到Tomcat上,并启动Tomcat。
在IE地址栏中敲入URL:http://localhost:8080/TempConvert/tempConvert.html,点击“Convert to Fanhrenheit”按钮,即可得到转换结果