jsp+servlet+JavaBean+MySQL实现登陆实例

时间:2022-05-11 15:11:03

jsp+servlet+JavaBean+MySQL实现登陆实例

运行环境:

jdk8.0

eclipse4.0

tomcat7.0

Windows2007

需要的jar包是:jsp+servlet+JavaBean+MySQL实现登陆实例mysql-connector-java-5.1.28.jar

①:首先创建在MySQL中创建一张tusers表

DROP TABLE IF EXISTS `tusers`;
CREATE TABLE `tusers` (
  `username` varchar(20) NOT NULL,
  `userid` int(20) NOT NULL AUTO_INCREMENT,
  `password` varchar(20) NOT NULL,
  PRIMARY KEY (`userid`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

然后在其中插入一个用户:用户名:admin  密码:admin
-- ----------------------------
-- Records of tusers
-- ----------------------------
INSERT INTO `tusers` VALUES ('admin', '1', 'admin');

②、在eclipse中创建一个web工程,其工程目录格式如下图:

jsp+servlet+JavaBean+MySQL实现登陆实例

1、在WebContent下创建其登陆页面及其相关的登陆成功页面和登陆失败页面:login.jsp、success.jsp、error.jsp

login.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>登陆</title>
<script type="text/javascript">
function check(form){
//取得form1中username的值并判断是否为空
if(document.forms.form1.username.value==""){
alert("请输入用户名");
document.forms.form1.username.focus();
return false;
}
if(document.forms.form1.password.value==""){
alert("请输入密码");
document.forms.form1.password.focus();
return false;
}
}
</script>
</head>
<body>
<form action="LoginServlet" method="post" name="form1">
<label>username</label>
<input type="text" name="username" />
<label>password</label>
<input type="password" name="password" />
<input type="submit" name="submit" onclick="return check(this);" value="登陆" />
<input type="reset" name="reset" value="重置" />
</form>


</body>
</html>

success.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"  
    pageEncoding="utf-8"%>  
<jsp:useBean id="user" class="model.Tusers" scope="request"/>  
<jsp:setProperty name="user" property="*"/>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
<title>Insert title here</title>  
</head>  
<body>  
<%   
    session.setAttribute("user",user);  
    String username=user.getUsername();  
 %>  
   
 <%=username %>,欢迎您来到成功页面!<br>  
 您的IP是:<%=request.getRemoteAddr() %><br>  
你的主机是:<%=request.getRemoteHost() %><br>  
你使用的协议是:<%=request.getProtocol() %><br>  
你目前的地址是:<%=request.getRealPath("/") %>  
你的主机端口是:<%=request.getRemotePort() %>  
</body>  
</html>  

error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h6>ERROR</h6>
</body>
</html>

2、在model包中创建tusers表的实体类:Tusers.java

package model;


public class Tusers {
    private Integer userid;


    private String username;


    private String password;


    public Integer getUserid() {
        return userid;
    }


    public void setUserid(Integer userid) {
        this.userid = userid;
    }


    public String getUsername() {
        return username;
    }


    public void setUsername(String username) {
        this.username = username;
    }


    public String getPassword() {
        return password;
    }


    public void setPassword(String password) {
        this.password = password;
    }
}

3、在util包中创建一个DBConn封装类来链接MySQL:DBConn.java

package util;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class DBConn {
public static String driver;//定义驱动
public static String url;//定义链接URL

public static String username;//定义数据库用户名
public static String password;//定义数据库密码
public static Connection connection;//定义链接
public static Statement statement;//定义statement
public static ResultSet result;//定义结果集

//设置connection
static{
driver="com.mysql.jdbc.Driver";
url="jdbc:mysql://localhost:3306/test?characterEncoding=utf-8";
username="test";
password="test";
try {
Class.forName(driver);

connection=DriverManager.getConnection(url,username,password);
System.out.println("链接成功--------------------------------");

} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(SQLException ex){
ex.printStackTrace();
}


}
 
    public DBConn(){     
        this.connection=this.getConn();  
    }     
  
    public Connection getConn(){     
        return this.connection;     
    } 
  
    public void doInsert(String sql) {     
     try {     
    statement = connection.createStatement();     
         int i = statement.executeUpdate(sql);     
     } catch(SQLException sqlexception) {     
         System.err.println("db.executeInset:" + sqlexception.getMessage());     
     }finally{     
              
     }     
 }     
 
 public void doDelete(String sql) {     
     try {     
    statement = connection.createStatement();     
         int i = statement.executeUpdate(sql);     
     } catch(SQLException sqlexception) {     
         System.err.println("db.executeDelete:" + sqlexception.getMessage());     
     }     
 }     
 public void doUpdate(String sql) {     
     try {     
    statement = connection.createStatement();     
         int i = statement.executeUpdate(sql);     
     } catch(SQLException sqlexception) {     
         System.err.println("db.executeUpdate:" + sqlexception.getMessage());     
     }     
 }     
    
 public ResultSet doSelect(String sql) {     
     try {  
         connection=DriverManager.getConnection(url,username,password);  
         statement = connection.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,java.sql.ResultSet.CONCUR_READ_ONLY);       
         result = statement.executeQuery(sql);   
         System.out.println("取得结果集");  
     } catch(SQLException sqlexception) {     
         System.err.println("db.executeQuery: " + sqlexception.getMessage());     
     }     
     return result;     
 }     
 /**   
  *关闭数据库结果集,数据库操作对象,数据库链接
    @Function: Close all the statement and conn int this instance and close the parameter ResultSet   
    @Param: ResultSet   
    @Exception: SQLException,Exception   
   **/    
  public void close(ResultSet rs) throws SQLException, Exception {     
 
    if (rs != null) {     
      rs.close();     
      rs = null;     
    }     
 
    if (statement != null) {     
    statement.close();     
    statement = null;     
    }     
 
    if (connection != null) {     
    connection.close();     
    connection = null;     
    }     
  }     
 
  /**   
   *关闭数据库操作对象,数据库连接对象     
   * Close all the statement and conn int this instance   
   * @throws SQLException   
   * @throws Exception   
   */    
  public void close() throws SQLException, Exception {     
    if (statement != null) {     
    statement.close();     
    statement = null;     
    }     
 
    if (connection != null) {     
    connection.close();     
    connection = null;     
    }     
  }     
  public static void main(String[] args){
 DBConn db=new DBConn();
 db.getConn();
 ResultSet rs=db.doSelect("select userid,username,password from tusers where username='admin'");
 try{
 while(rs.next()){
 System.out.println(rs.getInt(1));
 System.out.println(rs.getString(3));
 }
 }catch(SQLException e){
 e.printStackTrace();
 }
  }

}

4、在model包下创建一个类来对 登陆用户进行判断:CheckUser.java

package model;


import java.sql.ResultSet;
import java.sql.SQLException;


import util.DBConn;


public class CheckUser {
public boolean checkUser(Tusers user){
if(user.getUsername().equals("") || user.getUsername()!=null){
ResultSet rs=null;
DBConn db=new DBConn();
rs=db.doSelect("select userid,username,password from tusers where username='"+user.getUsername()+"'");
try{
while(rs.next()){
if(user.getPassword().equals("")|| user.getPassword()!=null){
rs=db.doSelect("select userid,username,password from tusers where  password="+user.getPassword());
return true;
}
}
}catch(SQLException e){
e.printStackTrace();
}

}
return false;
}


}

5、在controller中创建一个servlet:LoginServlet.java

package controller;


import java.io.IOException;


import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import model.CheckUser;
import model.Tusers;


/**
 * Servlet implementation class LoginServlet
 */
@WebServlet(name = "LoginServlet1", urlPatterns = { "/LoginServlet1" })
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

       
    /**
     * @see HttpServlet#HttpServlet()
     */
   /* public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
*/
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}


/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//设置HTTP响应的文档类型,此处为Text/html,如果更改为application\msword则设置为word文档格式  
        response.setContentType("text/html");  
        //设置响应所采用的编码方式  
        response.setCharacterEncoding("utf-8");  
Tusers user=new Tusers();
String userid=request.getParameter("userid");
String username=request.getParameter("username");
String password=request.getParameter("password");
user.setUsername(username);
user.setPassword(password);
CheckUser ck=new CheckUser();
boolean bool=ck.checkUser(user);

String forward;
if(bool){
forward="success.jsp";
}
else{
forward="error.jsp";
}
RequestDispatcher rd=request.getRequestDispatcher(forward);
rd.forward(request, response);

}


}

6、然后在web.xml中配置servlet:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>authority</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>controller.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
</web-app>其中login.jsp中的action中的值要和url-pattern的值相对应

到此这个简单的登陆案例就完成了,比较简单吧。如果用到spring+springmvc+mybatis结合一起那就更简单了。这个项目这是为了熟悉一下链接数据库的那块代码。