First JSP
In the previous tutorial we discussed Servlets. These are supposed to alter data and reply on userinput. If you are familiar with the MVC-pattern you’ll see that this is the controller. A JSP is the view with all the layout-tags and maybe a little bit of java code. There’s a few ways to do this, for example with the ${}-tag or with the <%= %>-tags.
If you have an html-page but you want some dynamic content you can use these tags. Here’s an example to display the current date:
<%@ page contentType=”text/html;charset=UTF-8″ language=”java” %>
<html>
<head><title>Date</title></head>
<body>
<h1><%= new java.util.Date() %></h1>
</body>
</html>
Above you’ll see an example of how java code is run inside a jsp. It’s best to use these tags as little as possible but sometimes you just have to use them. It’s also possible to write entire java classes inside a webpage, but you’ll understand that this is very messy:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Simple jsp page</title></head>
<body>
<%
class Test {
public String getText() {
return "some text";
}
}
%>
<%
Test test = new Test();
String text= test.();
%>
<%= text %>
</body>
</html>
You can see that it is very messy and it gets unreadable after a while. That’s why we use servlets to write our classes and we use our JSP to create a layout.