You can write java code through script elements in JSP pages. The following article will introduce you to the script elements of JSP and how to write java code in JSP pages. I hope it will be helpful to everyone.
#Java Server Page (JSP) is a technology that uses servlets to control the content or appearance of Web pages. A small program specified in a Web page and run on the Web server to modify the Web page before sending it to the user who requested it. [Video tutorial recommendation: Java tutorial]
Types of JSP script elements
Script elements are provided in jsp The ability to insert java code. There are three types of script elements:
Script (scriptlet):
is a container for Java code snippets in a JSP page. When converting a page to a servlet class, the scriptlet content is inserted into the jspService() method of the servlet class, and the servlet is generated from the JSP. The syntax is as follows:
<% java源代码 %>
Expression (expression):
is used to insert the value of a Java expression converted to String into the response returned to the client middle. The syntax is as follows:
<%= 表达式语句 %>
Declarations:
is used to declare global methods and variables for the JSP page. In a JSP file, these variables and methods must be declared before they can be used.
In page conversion, the declared methods and variables become class member declarations in the servlet class of the JSP page. The syntax is as follows:
<%! 字段或方法声明 %>
Code example
The following is a simple example to introduce the use of these three script elements
Example One: scriptlet
<%@ 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>
Example two: expression
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> //中文编码 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> <p> 今天的日期是: <%= (new java.util.Date()).toLocaleString()%> </p> </body> </html>
Example three: declarations
<%! int i = 0; %> <%! int a, b, c; %> <%! Circle a = new Circle(2.0); %>
The above is the entire content of this article , I hope it can be helpful to everyone’s study. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of How to write java code inside JSP page? (code example). For more information, please follow other related articles on the PHP Chinese website!