JSP training (7) -- use JDBC for dynamic verification and MVC for Data Query

Source: Internet
Author: User

Objective: To understand the basic process of connecting JDBC to a database and to query data using JDBC. Main Content: L on the basis of the previous instance, connect to the database to complete the user login function, and introduce the basic usage of JDBC; l display all user information to further introduce JDBC usage and query result processing. 1. Abbreviation of JDBC concept Java database connectivity, used to connect Java applications and standard interfaces of various relational databases. For programmers, connecting to any database is the same. 2. What preparations do I need to develop applications using JDBC? Install the database, including creating database tables. Obtain the JDBC driver of the database based on the database type. Different database management systems need different JDBC drivers, and different versions of the database management system needs the driver may be different; here using the Oracle database, the driver needs to be placed in the WEB-INF/lib. Database Information: IP address of the database, service port number, database name, and username and password used to connect to the database. 3. Example: Use a database to verify user logon information. You must modify the methods used to verify user information in user. java. 1) added an import statement before the class: Import Java. SQL. *; 2) the added check method is as follows: public Boolean check () {/* If (username = NULL | userpass = NULL) return false; If (username. equals ("zhangsan") & userpass. equals ("Lisi") {return true;} else {return false;} */connection con = NULL; statement stmt = NULL; resultset rs = NULL; Boolean B = true; try {// specifies the driver class required to connect to the database. forname ("oracle. JDBC. driver. oracledriver "); // creation and quantity Connection between databases // modify myserver to the IP address of the database server, and mydb to the database name con = drivermanager. getconnection ("JDBC: oracle: thin :@ myserver: 1521: mydb", "Scott", "Tiger "); // compile the SQL statement string SQL = "select * From usertable where username = '" + username + "' and userpass = '" + userpass + "'"; system. err. println (SQL); // create a statement object for executing the SQL statement stmt = con. createstatement (); // run the SQL statement to obtain the result set rs = stmt.exe cutequery (SQL); // judge whether there is data in RS if (RS. next () B = tr UE; else B = false;} catch (exception e) {system. Out. println (E. getmessage ();} finally {// close related object if (RS! = NULL) Try {Rs. Close ();} catch (exception ee) {}if (stmt! = NULL) Try {stmt. Close ();} catch (exception ee) {}if (con! = NULL) Try {con. Close () ;}catch (exception ee) {}} return B ;}4. you can log on using the username and password in the database when running the test. 5. When sending query results to pages, the client needs to obtain and display data from the server, because the data query is completed by the JavaBean, and the call to the JavaBean is completed by the servlet, servlet can get the query results, but the display information is completed by the JSP page. How to pass the query information in servlet to the JSP page? We have introduced that information can be transmitted through requests, sessions, and applications. Because Servlet and JSP can be in the same request, all three objects can be used. However, because session and application are stored for a long time, it is easy to waste server resources. Therefore, request storage is usually used. The following describes how to use the function of querying and displaying all information. The work to be done is as follows: l add a method to query all user information in user. Java; l write a controller to query all user information; l write a JSP page to display information. 6. In user. the following describes how to add a method in Java to query all user information: Public arraylist getalluser () {connection con = NULL; statement stmt = NULL; resultset rs = NULL; arraylist users = new arraylist (); try {// specifies the driver class required to connect to the database. forname ("oracle. JDBC. driver. oracledriver "); // establish a connection with the database. Con = drivermanager. getconnection ("JDBC: oracle: thin :@ myserver: 1521: mydb", "Scott", "Tiger "); // compile the SQL statement for querying database information string SQL = "select * From usertable "; // Create a statement object for executing the SQL statement stmt = con. createstatement (); // run the SQL statement to obtain the result set rs = stmt.exe cutequery (SQL); // traverse the result set while (RS. next () {string username = Rs. getstring (1); string userpass = Rs. getstring (2); // Java. util. date Birthday = Rs. getdate (3); // int age = Rs. getint (4); User user = new user (); User. setusername (username); User. setuserpass (userpass); users. add (User) ;}} catch (exception e) {system. out. PR Intln (E. getmessage ();} finally {// close related object if (RS! = NULL) Try {Rs. Close ();} catch (exception ee) {}if (stmt! = NULL) Try {stmt. Close ();} catch (exception ee) {}if (con! = NULL) Try {con. close ();} catch (exception ee) {}} return users;} Java must be introduced before the class. util package, the Code is as follows: Import Java. util. *; 7. Write the Controller Code as follows: Package servlet; import Java. io. *; import javax. servlet. *; import javax. servlet. HTTP. *; import JavaBean. *; import Java. util. *; public class getalluser extends httpservlet {public void doget (httpservletrequest request, httpservletresponse response) throws ioexception, servletexception {// Step 1: obtain user input information, which is not required here // Step 2: Call JavaBean user = new user (); arraylist users = NULL; users = user. getalluser (); // Step 3: Pass the value request. setattribute ("users", users); // Step 4: Select an interface to respond to the user string forward = "userlist. JSP "; requestdispatcher RD = request. getrequestdispatcher (forward); Rd. forward (request, response);} public void dopost (httpservletrequest request, httpservletresponse response) throws ioexcepti On, servletexception {doget (request, response) ;}} assume that userlist. jsp is used to respond to the user. 8. Configure the Controller on the web. add the following code to XML: <servlet> <servlet-Name> getalluser </servlet-Name> <servlet-class> servlet. getalluser </servlet-class> </servlet> <servlet-mapping> <servlet-Name> getalluser </servlet-Name> <URL-pattern>/getalluser </url-Pattern> </servlet-mapping> 9. Compile userlist. JSP response <% @ page contenttype = "text/html; charset = gb2312" %> <% @ taglib prefix = "C" uri = "http://java.sun.com/jsp/jstl/core" %> <C: foreach Var = "us Er "items =" $ {users} "> User name: $ {user. username} password: $ {user. userpass} <br> </C: foreach> here, the C: foreach label is used for loop processing. Items indicates the set of loop traversal. var declares the cyclic variable, indicating an element in the set. The loop body displays user information through expression language. 10. Run the test http: // 127.0.0.1: 8080/ch7/getalluser.

 

Reference material: Basic tutorial on Java Web Programming

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.