Wednesday, October 21, 2009

JSP - gather, process, store, and use session variables

<!-- 
just a typical html form 
This is the "theform.jsp" page 
--> 
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
   "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
    <head><title>enter form data</title></head> 
    <body> 
    <form method="post" action="formSaver.jsp"> 
        Username: <input type="text" name="username" /><br /> 
        Cool Factor: <input type="text" name="coolfactor" /><br /> 
        <input type="submit" value="submit" /> 
    </form> 
    </body> 
</html> 
 
 
<!-- 
    this page grabs the form data and 
    and (with the help of the UserFormBean class) 
    places the items as session data. 
--> 
 
<!-- the useBean taq is where this jsp page loops in the real classes --> 
<jsp:useBean id="userform" class="userform.UserFormBean" scope="session"/>
<!-- the setProperty tag sends * (all) the property data to userform --> 
<jsp:setProperty name="userform" property="*"/>
<html> 
    <head><title>Form Saver</title></head> 
    <body> 
        <p>Your data has been placed in a session!</p> 
        <p>Try visiting this <a href="unrelatedPage.jsp">unrelated page!</a></p> 
    </body> 
</html> 
 
 
<!-- this is the unrelated page that will pull 
    and display the session data --> 
<!-- this loops in the session data we'll utilize --> 
<jsp:useBean id="userform" class="userform.UserFormBean" scope="session"/>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
   "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
    <head><title>an unrelated page</title></head> 
    <body> 
       <%= userform.getUsername() %> | <%= userform.getCoolfactor() %> 
    </body> 
</html> 

/* 
 * This is the actual java class "UserFormBean" 
 * that processes and stores the data. 
 * 
 * Notice that the set methods use 
 * the same names as the form name data! 
 * 
 * */ 
package userform;
 
public class UserFormBean {
    String username;
    String coolfactor;
 
    public void setUsername(String value) {
        username = value;
    }
    public void setCoolfactor(String value) {
        coolfactor = value;
    }
    public String getUsername() {
        return username;
    }
    public String getCoolfactor() {
        return coolfactor;
    }
}
 
 

No comments:

Post a Comment