First, use a JavaBean to encapsulate the database operation, which is the model in MVC
Jdbcbean.java
package data;import java.sql.*;p ublic class Jdbcbean {private String dbdriver= " Com.mysql.jdbc.Driver "; Private String dburl= "Jdbc:mysql://localhost:3306/test"; Private String dbuser= "root"; Private String dbpassword= "686175"; Public Connection Conn=null; Public ResultSet Rs=null; Public ResultSet query (String sql) throws exception{try{Class.forName (dbdriver); Conn=drivermanager.getconnection (Dburl,dbuser,dbpassword); Statement stmt=conn.createstatement (); Rs=stmt.executequery (SQL); Return RS; } catch (SQLException e) {System.out.println (E.getmessage ()); } return null; public void update (String sql) throws exception{try{Class.forName (dbdriver); Conn=drivermanager.getconnection (Dburl,dbuser,dbpassword); Statement stmt=conn.createstatement (); Stmt.executeupdate (SQL); Stmt.close (); Conn.close (); } catch (SQLException e) {System.out.println (E.getmessage ()); } }}
In the SRC data package There is also a controller servlet, which is used to handle the operation of the connection database, the database used in the project is MySQL
Loginservlet.java
Package Data;import Java.io.ioexception;import Java.sql.resultset;import javax.servlet.requestdispatcher;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public class LoginServlet Extends HttpServlet {public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servlete Xception, IOException {String tojsp= ""; Request.setcharacterencoding ("GBK"); Response.setcontenttype ("text/html; CHARSET=GBK "); String Username=request.getparameter ("username"); String password=request.getparameter ("password"); String sql= "SELECT * from user where username= '" +username+ "'" + "&&password= '" +password+ "'"; Jdbcbean jdbc=new Jdbcbean () try{resultset rs=jdbc.query (SQL), if (Rs.next ()) {tojsp= "success.jsp";} else{tojsp= "error.jsp";} Rs.close ();} catch (Exception e) {System.out.println ("query exception occurred");} RequestDispatcher Rd=request.getrequestdispatcher (tojsp); Rd.forward (requesT, response);} public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexceptio n {doPost (request,response); }}
Next is a JSP-written view that shows the page action
Login Page login.jsp
<%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%>Login Success Page success.jsp<%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%>
If the login user name and password are not on the database, the login error page is displayed error.jsp<%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%>
Enter user name Ming, password Ming
Enter user name Lin, password li
Full Code Package: http://download.csdn.net/detail/u011731233/8093745
JSP connection database operations written in MVC mode