Java Reference
In-Depth Information
Example 18−4: login.jsp (continued)
<%! // Begin declaration block
// This method does very simple password verification. In a real application,
// this method would probably check a database of passwords.
public boolean verify(String username, String password) {
// Accept any username as long as the password is "java"
return ((username!=null) && (password!=null) && password.equals("java"));
}
%> <%-- End declaration block --%>
<%--
The next block of code is between <% and %>, which mark it as a "scriptlet".
When the JSP page is compiled, this code becomes part of the service()
method of the servlet. Scriptlet blocks are intermixed with HTML tags which
are also compiled into the service() method and are output literally by the
servlet. Notice how this scriptlet ends in the middle of an else block.
The HTML tags that follow it form part of the else{} block, and the block is
closed in a scriptlet that comes later in the file.
--%>
<% // Begin scriptlet
// This request parameter is required. It specifies what should be
// displayed if the login attempt is successful
String nextPage = request.getParameter("nextpage");
// This request parameter specifies a title for the login page
String title = request.getParameter("title");
if (title == null) title = "Please Log In"; // If not specified, use a default
// Look for username and password parameters in the request
String username = request.getParameter("username");
String password = request.getParameter("password");
// If the username and password are defined and valid, then store
// the username in the session, and redirect to the specified page
// We do this without displaying any content of our own.
if ((username != null) && (password != null) && verify(username, password)) {
session.setAttribute("username", username);
response.sendRedirect(nextPage);
}
else {
// Otherwise, we're going to have to display the login screen.
// If the username and password properties are totally undefined,
// then this is the first time, and all we display is the screen.
// Otherwise, if they are defined, then we've just had a failed login
// attempt, so display an additional "please try again" message.
String message = "";
if ((username != null) || (password != null)) {
message = "Invalid username or password. Please try again";
}
%>
<%-- This is the body of the else block started above. It displays --%>
<%-- the login page. It is straight HTML with only a few Java --%>
<%-- expressions contained in <%= %> tags. It also contains tags --%>
<%-- from a custom tag library, the subject of a later example --%>
<head><title>Login</title></head>
Search WWH ::




Custom Search