Simple JSP Part 4
As i promised a long.. long time ago..
i will write an example of using java beans in jsp pages.
The idea of this scenario is so you as a java web developer not being mixed up between HTML scripts and Java scripts.
So, if in the previous example we embedded some java instructions in HTML scripts then for this tutorial we will separate both.
Supposed you have this usual Java class acting as our first created java beans.
package pages;
public class HelloWorld {
public String getMessage(){
return “Hello Word”;
}
}
and then you have a regular HTML in a JSP file like below,
<html>
<head>
<title>Simple JSP Part 4</title>
</head>
<body>
</body>
</html>
and let’s name it message.jsp
Now, the idea is to display message from our HelloWorld class to our jsp page. How we will do it?
Add below java instruction between body tag in our message.jsp
<%
pages.HelloWord hw = new pages.HelloWorld();
out.println(“message is: “+hw.getMessage());
%>
To putting it all together, below is the full code.
<html>
<head>
<title>Simple JSP Part 4</title>
</head>
<body>
<%
pages.HelloWord hw = new pages.HelloWorld();
out.println(“message is: “+hw.getMessage());
%>
</body>
</html>
Then you will see a nice hello word message.
This is just a tiny example of how usefull java beans will be. The other benefit is if separate our logic into our java class, then we will able to test it first and will not having much difficulties in debuging compared to when we join our java instructions in our jsp pages.
But.. there is always a backside of this. If you want to update your java class, then you have to restart your web server to get it work.
So… have a nice try n error.
usaha sukses 7:45 am on December 29, 2011 Permalink |
just keep it simple.