【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">
${ssage }<br>
<form action="login-check" method="post">
⽤户名:<input type="text" name="username"/><br>
<br>
密码:    <input type="text" name="password"/><br>
<input type="checkbox" name="check" value="check"/>⾃动登录<br><br>
web端登录
<input type="submit" value="提交"/>        
<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;
Connection();
}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();
if(cookies!=null){
for(int i=0;i<cookies.length;i++){
cookie=cookies[i];
Name().equals("username"))
Value();
Name().equals("password"))
Name().equals("password"))
Value();
}
if(flag){
response.sendRedirect("choose.jsp?username="+String()+"再次登录");
}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(Parameter("username"));
pstmt.setString(Parameter("password"));
ResultSet uteQuery();
()){
flag=true;
}
}catch(SQLException e){
e.printStackTrace();
}
String Parameter("username").trim();//trim()去掉⽤户名字符串的头尾两端空格
String Parameter("password").trim();
if(!flag){
message="⽤户名或密码不正确,请重试!";
response.sendRedirect("login.jsp");
}else{
if((Parameter("check")!=null&&Parameter("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="+String());
}
}
}
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 ElementById("username");
var url="validation.do?username="+escape(username.value);
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function handleStateChange(){
adyState==4){
if(xmlHttp.status==200){
var ElementsByTagName("message")[0].firstChild.data;
var ElementById("results");
messageArea.innerHTML="<p>"+message+"</p>";
}
}
}
</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>
*密码:    <input type="text" id="password" name="password" size="20"><br>
<br>
<input type="submit" name="submit" value="提交">         <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;
Connection();
}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 Parameter("username");
String sql="SELECT * FROM user WHERE username=?";
try{
PreparedStatement pstmt=dbconn.prepareStatement(sql);
pstmt.setString(1, username);
ResultSet uteQuery();
())
message="该⽤户名已被使⽤,请更换其他⽤户名!";
}catch(SQLException sqle){
System.out.println(sqle);
}
PrintWriter Writer();
out.println("<response>");
out.println("<message>"+message+"</message>");
out.println("</response>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { // TODO Auto-generated method stub
response.setContentType("text/html;charset=utf-8");
String Parameter("username");
String Parameter("password");
try{
String sql="INSERT INTO user VALUES(?,?)";
PreparedStatement pstmt=dbconn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
uteUpdate()>0)
{
JOptionPane.showMessageDialog(null,"注册成功!");
}catch(SQLException e){
System.out.println(e);
}
}
}
⼆、运⾏结果截图
1.登录界⾯
2.数据库⾥已存在Wangqiang所以提⽰"该⽤户名已被使⽤,请更换其他⽤户名!"
3.数据库⾥不存在Wangmei,所以提⽰"该⽤户名可以被使⽤"

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。