Master java skills

Scriptlet Tag

JSP scriplet tag is used to keep java code inside a jsp page. Any kind of java code can be written inside a scriplet tag.

Note -> There can be any number of scriptlet tags in a jsp page.

Scriptlet Tag Syntax

<% java code %>

examples

<%
out.println("This is a scriptlet tag");
out.println("Addition of 5 and 6 = " + (5 + 6));
%>

Note -> To print something on the browser, you need to use out.print statement in jsp. Here out is an implicit object, meaning it is already provided to the jsp page. You don’t have to create it separately.

Example to print current date in jsp page

printDate.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<% out.print("Today is: " + java.util.Calendar.getInstance().getTime()); %>
</body>
</html>

Deploy and Test

In order to test this jsp page, you need to create a dynamic web project using maven and then keep this under webapp folder. If you don’t know how to create a dynamic web project click the below link

After the deployment is successful, hit the below url to test

http://localhost:8080/my-first-jsp-app/printDate.jsp

Display form parameters in jsp

In the below example, we will display form parameters of a html page onto a jsp page.

index.html

<html>
<body>
	<form action="welcome.jsp">
		Username : <input type="text" name="username"><br><br>
		Password : <input type="password" name="password">
		<input type="submit" value="Submit"><br />
	</form>
</body>
</html>

welcome.jsp

<html>
<body>
	<form>
		<%
		String name = request.getParameter("username");
		String password = request.getParameter("password");
		out.println("Welcome " + name + ". <br>");
		out.println("We know it's not good to capture your password," + 
		" it's just for testing purpose. <br> Your password is : " + password );
		%>
	</form>
</body>
</html>