JSP uses JDBC for dynamic verification and MVC for data query. jdbcmvc

Source: Internet
Author: User

JSP uses JDBC for dynamic verification and MVC for data query. jdbcmvc

This example describes how to use JDBC to perform dynamic verification and use MVC to query data. Share it with you for your reference. The details are as follows:

I. Objectives:

① Master the basic process of connecting to the database through JDBC;
② Master the use of JDBC for data query.

Ii. Main content:

① On the basis of the previous instance, the user login function is completed by connecting to the database, and the basic usage of JDBC is introduced;
② Display all user information to further introduce JDBC usage and query result processing.

1. JDBC Concept

The abbreviation of Java Database Connectivity, used to connect Java applications to 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 the drivers required by different database management systems may be different; the Oracle database is used here, and the driver needs to be placed under 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:
Copy codeThe Code is as follows: 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 "); // establish a connection with the database // change 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 = true; else B = false;} catch (Exception e) {System. out. println (E. getMessage ();} finally {// close the 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. Run the test

You can use the username and password in the database to log on.

5. Pass query results to the page

In many cases, 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:

① Add a method to query all User information in User. java;
② Compile a controller to query all user information;
③ Compile the JSP page for displaying information.

6. Add methods in User. java

The following describes how 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 String SQL = "select * from usertable" for querying database information; // 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. println (e. getMessage ();} finally {// Close the 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 ;}

The java. util package needs to be introduced before the class. The Code is as follows:
Copy codeThe Code is as follows: import java. util .*;
7. Write a controller

The Code is 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: Get user input information, no need here // Step 2: Call JavaBean User 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 IOException, ServletException {doGet (request, response );}}

Assume that userlist. jsp is used to respond to the user.

8. Configure the Controller

Add the following code to Web. 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 the userlist. jsp response

<% @ Page contentType = "text/html; charset = gb2312" %> <% @ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %> <c: forEach var = "user" 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 loop variable, which indicates 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

I hope this article will help you with JSP program design.

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.