【JavaWeb】用户登录连接数据库实现自动登录和注册功能

连接数据库:C3P0
自动登录:COOKIE
注册:AJAX

一、代码

1.登录界面login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
<div align="center">
${sessionScope.message }<br>
<form action="login-check" method="post">
用户名:<input type="text" name="username"/><br>
<br>
密码:&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" name="password"/><br>
<input type="checkbox" name="check" value="check"/>自动登录<br><br>
<input type="submit" value="提交"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type = "button" value = "注册" onclick = "window.location.href = 'register.jsp'">
</form>
</div>
</body>
</html>

2.核验用户名和密码LoginCheckServlet.java
C3P0连接数据库详解见点击此处
使用cookie实现自动登录

@WebServlet("/login-check")
public class LoginCheckServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    String message=null;  
	Connection dbconn=null;
    DataSource dataSource = null;
    boolean flag=false;
    public void init() {
    	try {
    		  ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("hhh");
    	        dataSource = comboPooledDataSource;
    	        dbconn=dataSource.getConnection();
    	}catch(Exception e) {}
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		String value1="";
		String value2="";
		Cookie cookie=null;
		Cookie [] cookies=request.getCookies();
		if(cookies!=null) {
			for(int i=0;i<cookies.length;i++) {
				cookie=cookies[i];
				if(cookie.getName().equals("username"))
					value1=cookie.getValue();
				if(cookie.getName().equals("password"))
					value2=cookie.getValue();
			}
			if(flag) {
				response.sendRedirect("choose.jsp?username="+value1.toString()+"再次登录");
		}else {
			response.sendRedirect("login.jsp");
		}
	}else {
		response.sendRedirect("login.jsp");
	}
}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		try {
			String sql="select * from user where username = ? and password = ?";
			PreparedStatement pstmt=dbconn.prepareStatement(sql);
			pstmt.setString(1,request.getParameter("username"));
			pstmt.setString(2,request.getParameter("password"));
			ResultSet result=pstmt.executeQuery();
			while(result.next()) {
			flag=true;
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}	
		
		String username=request.getParameter("username").trim();//trim()去掉用户名字符串的头尾两端空格
		String password=request.getParameter("password").trim();
		if(!flag){
			message="用户名或密码不正确,请重试!";
			request.getSession().setAttribute("message",message);
			response.sendRedirect("login.jsp");
		}else {
			if((request.getParameter("check")!=null&&request.getParameter("check").equals("check"))) {//选了记住密码
				Cookie usernameCookie=new Cookie("username",username);
				Cookie passwordCookie=new Cookie("password",password);
				usernameCookie.setMaxAge(60*60*4);
				passwordCookie.setMaxAge(60*60*4);
				response.addCookie(usernameCookie);
				response.addCookie(passwordCookie);
			}
			response.sendRedirect("choose.jsp?username="+username.toString());
		}	
	}
}

3.注册界面register.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户注册</title>
<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest(){
	if(window.ActiveXObject){
		xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
	}else if(window.XMLHttpRequest){
		xmlHttp=new XMLHttpRequest();
	}
}

function validate(){
	createXMLHttpRequest();
	var username=document.getElementById("username");
	var url="validation.do?username="+escape(username.value);
	xmlHttp.open("GET",url,true);
	xmlHttp.onreadystatechange=handleStateChange;
	xmlHttp.send(null);
	}
	
	function handleStateChange(){
		if(xmlHttp.readyState==4){
			if(xmlHttp.status==200){
				var message=xmlHttp.responseXML.getElementsByTagName("message")[0].firstChild.data;
				var messageArea=document.getElementById("results");
				messageArea.innerHTML="

"+message+"

"
; } } } </script> </head> <body> <form action="validation.do" method="post"> <div align="center"> <br><br> <font size="4" color=red ><div id="results">请输入用户名和密码</div></font><br> *用户名:<input type="text" id="username" name="username" size="20"onblur="validate()";><br> <br> *密码:&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" id="password" name="password" size="20"><br> <br> <input type="submit" name="submit" value="提交">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="reset" name="reset" value="重置"> </div> </form> </body> </html>

4.ValidationServlet.java
光标移动到密码框里时显示用户名可否被使用的信息
点击提交将用户名和密码添加入数据库
注册成功则返回登录界面

@WebServlet(name="validationServlet",urlPatterns= {"/validation.do"})
public class ValidationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	Connection dbconn=null;
    DataSource dataSource = null;
public void init() {
	try {
		  ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("hhh");
	        dataSource = comboPooledDataSource;
	        dbconn=dataSource.getConnection();
	}catch(Exception e) {}
}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	response.setContentType("text/xml;charset=UTF-8");
	response.setHeader("Cache-Control", "no-cache");
	String message="该用户名可以被使用";
	String username=request.getParameter("username");
	String sql="SELECT * FROM user WHERE username=?";
	try {
		PreparedStatement pstmt=dbconn.prepareStatement(sql);
		pstmt.setString(1, username);
		ResultSet rst=pstmt.executeQuery();
		if(rst.next())
			message="该用户名已被使用,请更换其他用户名!";
	}catch(SQLException sqle) {
		System.out.println(sqle);
	}
	PrintWriter out=response.getWriter();
	out.println("");
	out.println(""+message+"");
	out.println("");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=utf-8");
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		try {
			String sql="INSERT INTO user VALUES(?,?)";
			PreparedStatement pstmt=dbconn.prepareStatement(sql);
			pstmt.setString(1, username);
			pstmt.setString(2, password);
			if(pstmt.executeUpdate()>0)
			 {
				JOptionPane.showMessageDialog(null, "注册成功!");
	request.getRequestDispatcher("login.jsp").forward(request,response);}
		}catch(SQLException e) {
			System.out.println(e);
		}	
	}
	}

二、运行结果截图

1.登录界面
【JavaWeb】用户登录连接数据库实现自动登录和注册功能_第1张图片
2.数据库里已存在Wangqiang所以提示"该用户名已被使用,请更换其他用户名!"
【JavaWeb】用户登录连接数据库实现自动登录和注册功能_第2张图片

3.数据库里不存在Wangmei,所以提示"该用户名可以被使用"
【JavaWeb】用户登录连接数据库实现自动登录和注册功能_第3张图片

你可能感兴趣的:(【JavaWeb】用户登录连接数据库实现自动登录和注册功能)