好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

在JSP页面内编写java代码方法总结

jsp脚本元素的类型

脚本元素提供了在jsp中插入java代码的能力。脚本元素有三种类型:

脚本(scriptlet):

是jsp页面中java代码片段的容器。将页面转换为servlet类时,会将scriptlet内容插入到servlet类的jspservice()方法中,同时从jsp生成servlet。语法如下:

?

1

<% java源代码 %>

表达式(expression):

用于将转换为string的java表达式的值插入到返回给客户端的响应中。语法如下:

?

1

<%= 表达式语句 %>

声明(declarations):

用于为jsp页面声明全局的方法和变量。在jsp文件中,必须先声明这些变量和方法然后才能使用它们。

在页面转换中,声明的方法和变量成为jsp页面的servlet类中的类成员声明。语法如下:

?

1

<%! 字段或方法声明 %>

代码示例

下面通过简单示例来介绍这三种脚本元素的使用

示例一:脚本(scriptlet)

?

1

2

3

4

5

6

7

8

9

10

11

12

<%@ page language= "java" contenttype= "text/html; charset=utf-8"

   pageencoding= "utf-8" %>  //中文编码

<!doctype html>

<html>

<head><title>hello world</title></head>

<body>

hello world!<br/>

<%

out.println( "your ip address is " + request.getremoteaddr());

%>

</body>

</html>

示例二:表达式(expression)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<%@ page language= "java" contenttype= "text/html; charset=utf-8"

   pageencoding= "utf-8" %> //中文编码

<!doctype html>

<html>

<head>

<meta charset= "utf-8" >

<title>菜鸟教程(runoob测试数据)</title>

</head>

<body>

<p>

   今天的日期是: <%= ( new java.util.date()).tolocalestring()%>

</p>

</body>

</html>

示例三:声明(declarations)

?

1

2

3

<%! int i = 0 ; %>

<%! int a, b, c; %>

<%! circle a = new circle( 2.0 ); %>

 

查看更多关于在JSP页面内编写java代码方法总结的详细内容...

  阅读:17次