This article introduces Struts, a Model-View-Controller implementation that uses servlets and JavaServer Pages (JSP) technology. Struts can help you control change in your Web project and promote specialization. Even if you never implement a system with Struts, you may get some ideas for your future servlets and JSP page implementation.
A JavaServer Page (JSP) file is nothing more than another way to view a servlet. The concept of a JSP file is to allow us to see a Java servlet as an HTML page. This view eliminates all of the ugly
print()
statements that normally show up in Java code. The JSP file is pre-processed into a .java
file, then compiled into a .class
. If you are using Tomcat, you can view your pre-processed .java
files in the work
directory. Other containers may store the .java
and .class
files elsewhere; the location is container specific. Figure 1 demonstrates the JSP file-to-servlet flow.Figure 1. JSP file-to-servlet flow
(This is significantly different from a Microsoft Active Server Page (ASP). An ASP is compiled into memory, not into a separate file.)
The simple self-contained JSP file
In a small JSP application, it is common to see the data, business logic, and the user interface combined into one module of code. In addition, the application generally contains the logic that controls the flow of the application. Listing 1 and Figure 2 demonstrate a simple JSP file that allows a user to join a mailing list.
In a small JSP application, it is common to see the data, business logic, and the user interface combined into one module of code. In addition, the application generally contains the logic that controls the flow of the application. Listing 1 and Figure 2 demonstrate a simple JSP file that allows a user to join a mailing list.
<%@ page language="java" %> <%@ page import="business.util.Validation" %> <%@ page import="business.db.MailingList" %> <% String error = ""; String email = request.getParameter("email"); // do we have an email address if( email!=null ) { // validate input... if( business.util.Validation.isValidEmail(email) ) { // store input... try { business.db.MailingList.AddEmail(email); } catch (Exception e) { error = "Error adding email address to system. " + e; } if( error.length()==0 ) { %> // redirect to welcome page... <jsp:forward page="welcome.html"/> <% } } else { // set error message and redisplay page error = email + " is not a valid email address, please try again."; } } else { email = ""; } %> <html> <head> <title>Join Mailing List</title> </head> <body> <font color=red><%=error%></font><br> <h3>Enter your email to join the group</h3> <form action="join.jsp" name="joinForm"> <input name="email" id="email" value=<%=email%>></input> <input type=submit value="submit"> </form> </body> </html> Figure 2. In a simple request and response, the JSP file sets the data, controls the flow to the next page, and creates the HTML
|
For Further Reading,