JSP uses JDBC to complete dynamic verification and MVC to complete data query
- 2021-08-12 03:17:42
- OfStack
This paper gives an example of JSP using JDBC to complete dynamic verification and MVC to complete data query. Share it for your reference. The details are as follows:
1. Objectives:
Master the basic process of JDBC linking database;
② Master the use of JDBC for data query.
2. Main contents:
On the basis of the previous example, the user login function is completed by connecting the database, and the basic usage of JDBC is introduced;
Secondly, the usage of JDBC and the processing of query results are introduced by displaying all user information.
1. JDBC concept
Abbreviation for Java Database Connectivity, used to connect Java applications to the standard interface of 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;
According to the type of the database, get the JDBC driver of the database. Different database management systems need different JDBC drivers, and different versions of database management systems need different drivers; The Oracle database is used here, and the driver needs to be placed under WEB-INF/lib.
Database related information: IP address of the database, port number of the service, database name, user name and password for connecting to the database.
3. Example: Use database to verify user login information.
You need to modify the method of validating user information in User. java.
1) Added an import statement to the front of 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{
// Indicate the drivers needed to connect to the database
Class.forName("oracle.jdbc.driver.OracleDriver");
// Establish a connection with the database
// myserver Modify to database server IP , mydb Is the database name
con = DriverManager.getConnection("jdbc:oracle:thin:@myserver:1521:mydb","scott","tiger");
// Object for querying database information SQL Statement
String sql="select * from usertable where username='"+username+"' and userpass='"+userpass+"'";
System.err.println(sql);
// Creates a statement object for executing SQL Statement
stmt = con.createStatement();
// Execute SQL Statement to get the result set
rs = stmt.executeQuery(sql);
// Judge rs Is there data in
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 in using the user name and password in the database.
5. Pass the query results to the page
Most of the time, the client needs to get data from the server and display it, because the query of data is completed by JavaBean, and the call to JavaBean is completed by Servlet, and the query results can be obtained in Servlet, but the display information is completed by JSP page. How to transfer the query information in Servlet to JSP page?
The information can be passed through request, session, and application as described earlier, because Servlet and JSP can be in the same request, so all three objects can be used. But because session and application are stored for a long time, it is easy to waste server resources, so request is usually used for storage.
The following describes the specific usage through the function of querying and displaying all information. The work to be completed is as follows:
Add a method to query all user information in User. java;
(2) compiling a controller for inquiring all user information;
③ Write an JSP page that displays information.
6. Add methods to User. java
The method of querying all user information is as follows:
public ArrayList getAllUser()
{
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
ArrayList users = new ArrayList();
try{
// Indicate the drivers needed to connect to the database
Class.forName("oracle.jdbc.driver.OracleDriver");
// Establish a connection with the database
con = DriverManager.getConnection("jdbc:oracle:thin:@myserver:1521:mydb","scott","tiger");
// Object for querying database information SQL Statement
String sql="select * from usertable";
// Creates a statement object for executing SQL Statement
stmt = con.createStatement();
// Execute SQL Statement to get the result set
rs = stmt.executeQuery(sql);
// Traversing 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 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 users;
}
You need to introduce the java. util package before the class, and the 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
{
// No. 1 1 Step: Get the user's input information, which is not required here
// No. 1 2 Step: Call JavaBean
User user = new User();
ArrayList users=null;
users = user.getAllUser();
// No. 1 3 Step: Pass the value
request.setAttribute("users",users);
// No. 1 4 Step: Select 1 Interfaces respond to users
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);
}
}
It is assumed that userlist. jsp is used to respond to users.
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. 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}">
User name: ${user.username} Password: ${user.userpass} <br>
</c:forEach>
Here, the c: forEach tag is used for loop processing, items indicates the set that loops through, and var declares a loop variable that represents one element in the set. User information is displayed in expression language in the loop body.
10. Run the test
http://127.0.0.1:8080/ch7/getAllUser
I hope this article is helpful to everyone's JSP programming.