4.JSP access database

JSPS are Java code nested in HTML, so Java code can be written in JSPS (<%… % >)

Guide operation:

  • 2. Right-click the Jar: Build Path -> Add to Build Path
  • Web project: Copy jar to web-INF /lib

Core: is the Java JDBC code, copy to JSP <%… % >

Error: The import Xxx cannot be resolved

A. Right-click the project -> Build path, delete libary or Lib, and import b again. Clear various caches: right-click project ->Clean Tomcat… Clean (project-clean or tomcat directory to delete the work subdirectory) c. Delete tomcat, decompress and configure tomcat again, and restart computer D. If a class does not have a package before, it is added to the package

Just now we moved the JSP login code to logindao.java; The LoginDao class is called a JavaBean. JavaBean functions: a. Reduced JSP complexity b. Improved code reuse (LoginDao can be used to log in anywhere in the future)

A JavaBean class that meets the following two criteria is called a JavaBean A. public class. All attributes (if any) are private and provide set/get (if Boolean get can be replaced with is)

Java is divided into two categories: a. Javabeans that encapsulate business logic (Logindao.java encapsulates Login logic) Logic can encapsulate JDBC code in JSP into login.java class (login.java)

Login Login = new Login(uname,upwd); Login Login = new Login(uname,upwd); // The Login object encapsulates two pieces of data (username and password)

A JavaBean that encapsulates data corresponds to a table (Login(Name, PWD)) in the database. A JavaBean that encapsulates business logic is used to operate on a JavaBean that encapsulates data

Javabeans can simplify code (JSP -> JSP + Java) and provide code reuse (logindao.java).

public void sleep(String name,String place, int time)

{

}

Public void sleep(Person per) {per.getName() per.getPlace()… }



Case: Determine login user information, use javabean,

Login. Java in the entity class uses the data principle of Javabean, LoginDao uses the logic principle of Javabean

Entity class com. XDR. The entity – Login. Java

package com.xdr.entity;

public class Login {
	private int id ; 
	private String name;
	private String pwd ;
	
	public Login(a) {}public Login(int id, String name, String pwd) {
		this.id = id;
		this.name = name;
		this.pwd = pwd;
	}
	public Login( String name, String pwd) {
		this.name = name;
		this.pwd = pwd;
	}
	public int getId(a) {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName(a) {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPwd(a) {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd; }}Copy the code

Example: com. XDR. The entity – Person. Java

package com.xdr.entity;

public class Person {/ / entity class
	private int id ; 
	private String name;
	private boolean isChina ;
	public int getId(a) {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName(a) {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public boolean isChina(a) {// Boolean isXxx() is equivalent to getXxx();
		return isChina;
	}
	public void setChina(boolean isChina) {
		this.isChina = isChina; }}Copy the code

com.xdr.dao-Login.java

package com.xdr.dao;
import com.xdr.entity.*;
import java.sql.*;


public class LoginDao {
// public int login(String name,String PWD)//1: the login is successful. 0: the login fails (the user name or password is incorrect) -1: the system is abnormal
	public int login(Login login)0: the login fails (the user name or password is incorrect). -1: the system is abnormal
	{
		String URL = "jdbc:mysql://localhost:3306/login";
		String USERNAME = "root";
		String PWD = "123456";
		Connection connection = null;
		Statement stmt = null;
		ResultSet rs = null ; 
		try {
			// a. Import the driver and load the specific driver class
			Class.forName("com.mysql.jdbc.Driver");// Load the specific driver class
			B. Establish a connection with the database
			connection = DriverManager.getConnection(URL, USERNAME, PWD);
			// c. Send SQL, execute (query)
			stmt = connection.createStatement();
			
		//	String name = request.getParameter("uname") ;
		//	String pwd = request.getParameter("upwd") ;
			
			String sql = "select count(*) from login where uname='"+login.getName()+"' and upwd ='"+login.getPwd()+"'" ;
			rs = stmt.executeQuery(sql); // The return value indicates how many items of data are added, deleted, or modified
			// d
			int count = -1;
			if(rs.next()) {
				count = rs.getInt(1); }// if(count>0) {
// out.println(" login successfully!" );
// }else {
// out.println(" login failed!" );
/ /}
			return count ;

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return -1 ;
		} catch (SQLException e) {
			e.printStackTrace();
			return -1 ;
		} catch(Exception e) {
			e.printStackTrace();
			return -1 ;
		}
		finally {
			try {
				if(rs! =null) rs.close(); 
				 if(stmt! =null) stmt.close();// object. Method
				 if(connection! =null)connection.close();
			}catch(SQLException e) { e.printStackTrace(); }}}}Copy the code

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"% > <! DOCTYPE html> <html> <head> <meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="check.jsp" method="post"> User name: <input type="text" name="uname"/><br/> Password: <input type="password" name="upwd" /><br/>
		<input type="submit"  value="Login" /><br/>
	</form>
</body>
</html>
Copy the code

check.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="com.xdr.dao.LoginDao" %>
<%@ page import="com.xdr.entity.*"% > <! DOCTYPE html> <html> <head> <meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		String name = request.getParameter("uname");
		String pwd = request.getParameter("upwd");
		Login login = new Login(name,pwd) ;
		
		
		LoginDao dao = new LoginDao();
		int result = dao.login(login);
		if(result>0){
			out.print("Successful landing.");
		}
		else if(result==0){
			out.print("Wrong username or password");
		}else{
			out.print("System exception!");
		}
	%>
</body>
</html>
Copy the code

Table Original data:





Login page, enter the correct information





Input incorrect information: