This article describes the JSP using JDBC to complete dynamic validation and the use of MVC to complete the data query method. Share to everyone for your reference. Specifically as follows:
First, the goal:
① Master the basic process of JDBC link database;
② Master using JDBC for data query.
Second, the main content:
① on the basis of the last instance, through connecting the database to complete the user login function, introduce the basic usage of JDBC;
② further describes the use of JDBC and the processing of query results by displaying all user information.
1. JDBC Concept
The abbreviation for Java Database connectivity, used to connect the standard interfaces between Java applications and various relational databases. For programmers, connecting to any database is the same.
2. What preparations are needed to develop applications using JDBC?
Install the database, including the creation of database tables;
Depending on the type of database, the JDBC driver for the database is obtained, and different database management systems require different JDBC drivers, and different versions of the database management system may require different drivers; The Oracle database is used here, and the driver needs to be placed in the web-inf/ Under Lib.
Database information: The IP address of the database, the port number of the service, the name of the database, the username and password to connect to the database.
3, Example: Use the database to authenticate the user login information.
You need to modify the method of validating user information in User.java.
1 Adds an import statement to the front of the class:
Copy Code code as follows:
2 The additional 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{//Indicates the driver required to connect to the database Class.forName ("Oracle.jdbc.driver.OracleDriver"); Establish a connection with the database//MyServer modification for database server Ip,mydb for database name con = drivermanager.getconnection ("Jdbc:oracle:thin: @myserver: 1521:
MyDB "," Scott "," Tiger ");
SQL statement that writes query database information String sql= "SELECT * from usertable where username= '" +username+ "' and userpass= '" +userpass+ "";
SYSTEM.ERR.PRINTLN (SQL);
Creates a statement object that executes the SQL statement stmt = con.createstatement ();
Execute the SQL statement to get the result set rs = stmt.executequery (SQL);
Determine if there is any data in RS if (Rs.next ()) B = true;
else B = false;
}catch (Exception e) {System.out.println (E.getmessage ()); finally{//Close related objects 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 log on using the user name and password in the database.
5, pass the query result to the page
Many times, the client needs to get the data from the server and display it, because the data query is completed by JavaBean, the call to JavaBean is done through the servlet, the servlet can get the results of the query, but the display information is completed by the JSP page, How do I pass the information of the query in the servlet to the JSP page?
As described earlier, you can pass information through request, session, and application because you can have the servlet and JSP in the same request, so 3 objects can be used. But because the session and application save time is relatively long, easy to cause the waste of server resources, so usually use request storage.
The following is an introduction to the specific usage by querying and displaying the functionality of all information. The work to be done is as follows:
① to add a method for querying all user information in User.java;
② to write a controller that queries all user information;
③ to write a JSP page that displays information.
6, add the method in the User.java
The following methods are used to query all user information:
Public ArrayList Getalluser () {Connection con = null;
Statement stmt = null;
ResultSet rs = null;
ArrayList users = new ArrayList ();
try{//Indicates the driver required to connect to the database Class.forName ("Oracle.jdbc.driver.OracleDriver");
Establish a connection to the database con = drivermanager.getconnection ("Jdbc:oracle:thin: @myserver: 1521:mydb", "Scott", "Tiger");
Write a SQL statement that queries database information String sql= "SELECT * from Usertable";
Creates a statement object that executes the SQL statement stmt = con.createstatement ();
Execute the SQL statement to get the result set rs = stmt.executequery (SQL);
Traversal 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 related objects 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 to users;
}
The Java.util package needs to be introduced before the class, and the code is as follows:
Copy Code code as follows:
7, write the 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
{/
/First step: Get user input information, no need
// Step two: Invoke JavaBean
User user = new user ();
ArrayList Users=null;
Users = User.getalluser ();
Step three: Transfer value
request.setattribute ("Users", users);
Fourth step: 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);
}
}
This assumes that userlist.jsp is used to respond to the user.
8. Configuration Controller
Add the following code to the 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, write 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} ">
username: ${user.username} password: ${user.userpass} <br>
</c:forEach>
The C:foreach tag here is used for loop processing, and the items indicate the loop traversal of the collection, Var declares the loop variable, and represents an element in the collection. The loop body displays user information through an expression language.
10, run the test
Http://127.0.0.1:8080/ch7/getAllUser
I hope this article will help you with the JSP program design.