JSP基础----Scriptlet

JSP中最重要的部分就是Sciptlet(脚本小程序),所有嵌入在HTML代码中的Java程序都必须使用Scriptlet标记出来。

JSP一共有三种Scriptlet代码:

      1.第一种:<%%>:在此Scriptlet中可以定义局部变量、编写语句

      2.第二种:<%!%>:在此Scriptlet中可以定义全局变量、方法、类

      3.第三种:<%=%>:用于输出一个变量或者一个具体内容

<%!%>中定义的是变量就是全局变量,一般而言,使用<%!%>的操作都是声明全局常量较多,而所谓的定义方法或定义类基本上是不使用的。


样例1:

<%!
	public static final String INFO = "www.huangmeixi.cn";
	int x = 10;
%>
<%!
	public int add(int x, int y){
		return x + y;
	}
%>
<%!
	class Person{
		private String name;
		private int age;
		public Person(String name, int age){
			this.name = name;
			this.age = age;
		}
		public String toString(){
			return "name = " + this.name + ";age = " + this.age;
		}
	}
%>
<%
	out.println("<h3>x = " + x++ + "</h3>");
	out.println("<h3>" + new Person("Joywy", 23) + "</h3>");
	out.println("<h3>3 + 5 = " +add(3, 5) + "</h3>");
%>


样例2:

<%
	String info = "www.huangmeixi.cn";	//局部变量
	int temp = 30;
%>
<h3>info = <%=info%></h3>
<h3>temp = <%=temp%></h3>
<h3>name = <%="Joywy"%></h3>

样例3:

<html>
<head>
	<title>Insert title here</title>
</head>
<body>
<%
	int rows = 10;
	int cols = 10;
%>
<table border="1" width="100%">
<% 
	for(int x = 0; x < rows; x++){
%>
		<tr>
<% 
			for(int y = 0; y < cols; y++){
%>
				<td><%=x*y%></td>
<% 
			}
%>
		</tr>
<% 
	}
%>
</table>
</body>
</html>
以上代码达到了HTML代码和JAVA代码相分离,以后在使用输出的时候坚决不再使用out.println,而使用<%=%>

样例4:(通过交互性打印表格)

index.html

<html>
	<head><title>交互式打印表格</title></head>
	<body>
		<form action="print_table.jsp" method="post">
			<table>
				<tr>
					<td>请输入要显示表格的行数:</td>
					<td><input type="text" name="row"></td>
				</tr>
				<tr>
					<td>请输入要显示表格的列数:</td>
					<td><input type="text" name="col"></td>
				</tr>
				<tr>
					<input type="submit" value="显示">
					<input type="reset" value="重置">
				</tr>
			</table>
		</form>
	</body>
</html>

print_table.jsp

<html>
<head>
	<title>Insert title here</title>
</head>
<body>
<%
	int rows = 0;
	int cols = 0;
	try{
		rows = Integer.parseInt(request.getParameter("row"));
		cols = Integer.parseInt(request.getParameter("col"));
	}catch(Exception e){}
	
%>
<table border="1" width="100%">
<% 
	for(int x = 0; x < rows; x++){
%>
		<tr>
<% 
			for(int y = 0; y < cols; y++){
%>
				<td><%=x*y%></td>
<% 
			}
%>
		</tr>
<% 
	}
%>
</table>
</body>
</html>

Scriptlet标签:

JSP中专门提供了一种Scriptlet的标签,语法如下:

<jsp:scriptlet>

        Java的scriptlet代码

</jsp:scriptlet>

样例5:

<html>
	<head><title>交互式打印表格</title></head>
	<body>
		<jsp:scriptlet>
			String url = "www.huangmeixi.cn";
		</jsp:scriptlet>
		<h2><%=url%></h2>
	</body>
</html>





  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值