With this example we are going to demonstrate how to use Java code in a JSP page. JavaServer Pages (JSP) is a server-side programming technology that enables the creation of dynamic, platform-independent method for building Web-based applications. JSP have access to the entire family of Java APIs, including the JDBC API to access enterprise databases. In short, to use Java code in a JSP page you should:
- Create a jsp page that contains the
<%code fragment%>scriptlet. It can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language.
- Keep any html tags in the page outside the scriptlet.
- Use the
importattribute inside the
<%@ page ... %>directive to define any packages for use in the page, just like the Java
importstatement does for Java classes.
Let’s take a look at the code snippet that follows:
<%@ page import="java.util.Random"%> <html> <head> <title>Java Code Geeks Snippets - Use Java Code in JSP Page</title> </head> <body> Random Generator - Java Code Geeks Snippets <% System.out.println(); %> <% Random random = new Random(); System.out.println("Random: " + random.nextBoolean()); %> </body>
Random Generator - Java Code Geeks Snippets Random: true
This was an example of how to use Java code in a JSP page.