JBuilder2005 actual JSP switching control (3)
Author:Eve Cole
Update Time:2009-07-02 17:10:13
Since switch.jsp is specified as the response JSP file through the action attribute in the login.jsp form, when the user selects the login user in login.jsp and enters the password to submit the form, the client will send an HTTP request to the server, and the server That is, call switch.jsp to respond to this request.
The data of the username and password components in the form will be passed to the server's switch.jsp through an HTTP request. The server will encapsulate this information in the request object and pass it to switch.jsp, so switch.jsp can be retrieved through request.getParameter(String paraName) Get these two values.
String userId = request.getParameter("userId"); String password = request.getParameter("password"); |
Imagine if the form of login.jsp has more than 10 data components, its value must be obtained through the corresponding number of request.getParameter() methods in switch.jsp. In addition, if the data is not a field string type, but an integer or floating point number, since the values returned by the request.getParameter() method are all Strings, type conversion must be performed. This work is not only tedious, but also error-prone.
JSP allows you to receive web form data through Bean in a mapping manner. Bean maps form data according to this rule: Bean attribute name = form data component name, that is, all form data fields with the same Bean attribute name are automatically filled in the Bean. , and complete the data type conversion. For example, there are two data components in the login.jsp form, one is named userId and the other is password. Define a User.java Bean with the same name of userId and password attributes. This Bean will automatically receive the two data components in the form. Data component value.
Write User.java
Let's first write the User.java Bean and create User.java in the project. The code is as follows:
Code Listing 7 User.java
1. package bookstore; 2. 3. public class User 4. { 5. private String userId;//userId 6. private String password;//password 7. private String userName;//username 8. public String getPassword() { 9. return password; 10. } 11. public String getUserId() { 12. return userId; 13. } 14. public String getUserName() { 15. return userName; 16. } 17. public void setPassword(String password) { 18. this.password = password; 19. } 20. public void setUserId(String userId) { 21. this.userId = userId; twenty two. } 23. public void setUserName(String userName) { 24. this.userName = userName; 25. } 26. } |
In addition to the two attribute names userId and password, there is also a username attribute userName. The value of this attribute is not received from the login.jsp form. When the username and password are verified correctly, the username is obtained from the data table T_USER table and stored in this Properties so that they can be referenced elsewhere, save and compile this class.
hint:
You can quickly create User.java code through JBuilder's Bean Express tool. Under normal circumstances, you should create Bean properties through Bean Express. This not only automatically generates get/set property access methods, but also ensures Bean naming conventions. . |
Write page program
After creating the Bean of User.java, we proceed to create switch.jsp and reference this Bean in switch.jsp.
Start the Create JSP wizard through File->New..->Web->double-click the JSP icon.
1. Specify switch.jsp name
Figure 10 Specify the name of switch.jsp |
Keep pressing Next to get to step 3 of the wizard.
2. Reference User.java Bean
Figure 11 Specify Bean referenced in JSP |
Click the Add Bean... button to pop up the Select a Class dialog box. Select the bookstore.User class in the dialog box, as shown in the following figure:
Figure 12 Select class as Bean |
After pressing OK, return to the dialog box in step 3 of the wizard. At this time, there is an additional row of records in the Bean list of the dialog box. You can specify a name for the Bean in the ID column and specify the scope of the Bean in the Scope, as shown in the figure below. Show:
Figure 13 Reference to a Bean |
We named User's Bean userBean and set its scope to the page domain. The page domain is the page scope and is available within the scope of the current page. When the JSP returns a response or the request is transferred to other JSP pages, it is no longer available. The other three scopes are described as follows:
·Request scope: When a request is generated, it is valid within the scope until the response is returned. For example, a Bean declared as request scope in a.jsp, when a.jsp transfers the request to the b.jsp page through <jsp:forward> It is still available in the middle of the year.
·Session scope: It is available within the cycle of the user session. The session cycle is from when the user logs in to the system until he logs out of the system.
·Application scope: This scope is the longest, indicating that the web container is valid until it is started until it is closed.
Press Next to go to the next step.
3. Set running configuration items
In the last step of the wizard, you can generate a runtime configuration item for the created JSP. Although the wizard sets create a runtime configuration item as the default option, I think this is not a reasonable default value. It is recommended to cancel the create a runtime configuration setting. item, do not create a JSP run configuration item, as shown in the following figure:
Press the Finish button to create the switch.jsp file with the following code:
Code Listing 8 switch.jsp created by the wizard
1. <%@ page contentType="text/html; charset=GBK" %> 2. <html> 3. <head> 4. <title> 5.switch 6. </title> 7. </head> 8. <jsp:useBean id="userBean" scope="page" class="bookstore.User" /> 9. <jsp:setProperty name="userBean" property="*" /> 10. <body bgcolor="#ffffff"> 11. <h1> 12. JBuilder Generated JSP 13. </h1> 14. </body> 15. </html> |
Line 8 is the JSP tag that references the Bean. Line 9 fills the Bean's attribute values with the form data, that is, fills the request parameters into the Bean's attributes by name matching, and completes type conversion at the same time (only basic data types or The conversion can only be completed if the constructor supports it). After executing line 9, the userId and password attributes in userBean will be set to the values of the username and password sent in the login.jsp page.
Because switch.jsp is only used for control and does not need to display content to the client, we remove the HTML code in switch.jsp and adjust switch.jsp to:
Code Listing 9 switch.jsp after removing static HTML code
1. <%@ page contentType="text/html; charset=GBK" %> 2. <jsp:useBean id="userBean" scope="page" class="bookstore.User" /> 3. <jsp:setProperty name="userBean" property="*" /> |
Provide a Scriptlet in switch.jsp to send the userId and password to the database and compare them with the users in the T_USER table to see if they are legitimate users, and redirect to different pages based on the verification results. The final code of switch.jsp looks like this:
Code Listing 10 Final switch.jsp
1. <%@page contentType="text/html; charset=GBK"%> 2. <%@page import="bookstore.*"%> 3. <%@page import="java.sql.*"%> 4. <jsp:useBean id="userBean" scope="session" class="bookstore.User"/> 5. <jsp:setProperty name="userBean" property="*"/> 6.<% 7. Connection conn = null; 8. try { 9. conn = DBConnection.getConnection(); 10. PreparedStatement pStat = conn.prepareStatement( 11. "select USER_NAME from T_USER where USER_ID=? and password = ?"); 12. pStat.setString(1, userBean.getUserId()); 13. pStat.setString(2, userBean.getPassword()); 14. ResultSet rs = pStat.executeQuery(); 15. if (rs.next()) { //Password is correct 16. userBean.setUserName(rs.getString(1));//Set user name 17. session.setAttribute("ses_userBean", userBean);//Put userBean into the Session object 18. %><jsp:forward page=" welcome.jsp "></jsp:forward> 19. <%} else { //Wrong password%> 20. <jsp:forward page="fail.jsp"></jsp:forward> 21.<% 22. }} finally { 23. if(conn != null) conn.close(); twenty four. } 25. %> |
·Introduce the classes needed in the Scriptlet code in lines 2 to 3.
·Lines 7 to 14 of the code send query SQL statements to the database and return the results.
·Line 15 indirectly determines whether the user password is correct by checking the number of records in the result set.
· Lines 16 to 18 are the response codes for correct user passwords. First, fill the userBean's userName attribute value with the USER_NAME attribute of the result set, then put the userBean object into the Session, and finally turn to the welcome.jsp page.
·When the user enters an incorrect password, there will be no record in the result set. At this time, rs.next() returns false, and the program moves to line 20. The code on line 20 redirects the page to the incorrect password input processing page fail.jsp.
·The code in lines 22 to 24 is used to close the database connection.
Maybe you have discovered that although lines 9~21 will throw SQLException, we do not have a corresponding exception catching block. In a standard Java program, it will cause a compile-time error, but in JSP, it can be compiled sequentially. This is because the JSP page itself catches all exceptions thrown in the page.
Assume that there is an error in the SQL query statement on line 11, such as the user table name is mistakenly written as User (correctly T_USER). When switch.jsp is called, a SQLException will be thrown on line 14, and switch.jsp will display The tracking information page of the exception stack trace is as shown below:
Figure 14 The terrible error handling page |
The error handling page shown in the picture above can be described as green-faced, ferocious, and very unfriendly. This kind of error reporting page may be suitable for developers because it provides a lot of error tracking information, but it is impossible for end users to accept this kind of error page. A rude error page. JSP allows you to specify a JSP page specifically for handling errors through <%@ page errorPage%>, so that errors can be displayed in a friendly and intuitive form. In the next section, we will create a JSP page for error handling. After creation, we will specify the error handling JSP page for switch.jsp.