注册和登录页面:
注册页面代码如下:
要求实现非空验证,当注册时输入用户名时,判断用户名是否存在,如存在则提示,不存在,可注册,将信息插入数据库
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.12.4.js"></script>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript">
function nameLeave(){
var path="<%=request.getContextPath() %>";
var uname=$("#uname").val();
if(uname==null ||uname==""){
$("#nameid").html("用户名不能为空!");
}else{
$.post(
"jsp/Test.jsp",
{"uname":uname},
function(result){
$("#nameid").html(result);
});
}
}
function pwdLeave(){
var pwd=$("#pwd").val();
if(pwd==null ||pwd==""){
$("#pwdid").html("密码不能为空!");
}else{
$("#pwdid").html("");
}
}
</script>
</head>
<body>
<form action="<%=request.getContextPath() %>/servlet/LoginServlet" method="post">
<table >
<tr>
<td>用户名:</td>
<td><input type="text" name="uname" id="uname" onblur="nameLeave();"/>
<span id="nameid" ></span></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="pwd" id="pwd" onblur="pwdLeave();"/>
<span id="pwdid" ></span></td>
</tr>
<tr>
<td > <input type="submit" value="注册"/></td>
<td > <a href="<%=request.getContextPath() %>/jsp/login.jsp" name="登录">登录</a></td>
</tr>
</table>
</form>
</body>
</html>
登录页面:
实现与数据库连接,如果有该用户信息,则登录成功,进入欢迎页面。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="<%=request.getContextPath() %>/servlet/LoginServlet" method="post">
<table >
<tr>
<td>用户名:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr><td colspan="2" >
<%
Object object=request.getAttribute("mess");
if(object!=null){
String mess =object.toString();
out.print(mess);
}
%>
</td></tr>
<tr>
<td > <a href="<%=request.getContextPath() %>/jsp/registration.jsp" name="注册">注册</a></td>
<td > <input type="submit" value="登录"/></td>
</tr>
</table>
</form>
</body>
</html>
完成注册页面用户已存在的ajax验证jsp页面:
<%@page import="java.io.PrintWriter"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="cn.com.userService.UserService" %>
<%@ page import="cn.com.userServiceImpl.UserServiceImpl" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<% request.setCharacterEncoding("utf-8");
String userName=request.getParameter("uname"); response.setContentType("text/html;charset=UTF-8");
PrintWriter writer= response.getWriter();
UserService uservice=new UserServiceImpl();
boolean flag= uservice.selectSQL(userName);
if(flag){
writer.write("用户名已存在");
}else{
writer.write("用户名可用");
}
writer.flush();
writer.close();
%>
以下是java代码,连接数据库及servlet等页面。
BaseDao代码:通过数据源连接数据库-数据库的增删改查方法:
package cn.com.userDao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class BaseDao {
Connection connection=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
//连接数据库的方法
public boolean getConnection1(){
try {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/users";
String user="root";
String password="abc12345";
connection=DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
//用数据源连接数据库
public boolean getConnection(){
//初始化上下文
try {
Context cxt=new InitialContext();
//获取与逻辑名称相关联的数据源对象
DataSource ds=(DataSource)cxt.lookup("java:comp/env/jdbc/users");
connection=ds.getConnection();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
//数据库的增删改
public int executeSql(String sql,Object...params){
int updateRows=0;
if( this.getConnection()){
try {
pstmt=connection.prepareStatement(sql);
for(int i=0;i<params.length;i++){
pstmt.setObject(i+1, params[i]);
}
updateRows= pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
return updateRows;
}
//遍历数据库
public ResultSet selectsql(String sql,Object[] params){
if(this.getConnection()){
try {
pstmt=connection.prepareStatement(sql);
for(int j=0;j<params.length;j++){
pstmt.setObject(j+1, params[j]);
}
rs=pstmt.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
}
return rs;
}
//关闭资源
public boolean closeSource(){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
if(pstmt!=null){
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
return true;
}
}
Dao层接口代码:
package cn.com.userDao;
public interface UserDao {
//用户注册查找数据库,有无此用户
public boolean selectSQL(String name);
//用户登录,判断用户名和密码是否正确
public String selectsql(String name);
//用户注册成功,用户信息插入数据库
public boolean executeSQL(String uname,String pwd);
}
继承BaseDao和实现UserDao接口的实用类
package cn.com.userDaoImpl;
import java.sql.ResultSet;
import java.sql.SQLException;
import cn.com.userDao.BaseDao;
import cn.com.userDao.UserDao;
public class UserDaoImpl extends BaseDao implements UserDao{
//用户注册,根据用户名查找数据库,有无此用户
public boolean selectSQL(String name) {
boolean flag=false;
String sql="SELECT username FROM users WHERE username=?";
Object[] params={name};
ResultSet rs= this.selectsql(sql, params);
try {
//如果查找有该用户名,返回true;
if(rs.next()){
flag=true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.closeSource();
return flag;
}
//用户登录,判断用户名和密码是否正确
public String selectsql(String name){
String password=null;
String sql="SELECT password FROM users WHERE username=?";
Object[] params={name};
ResultSet rs= this.selectsql(sql, params);
try {
if(rs.next()){
password= rs.getString(1);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.closeSource();
return password;
}
//用户注册成功,用户信息插入数据库
public boolean executeSQL(String uname, String pwd) {
boolean flag=false;
String sql="INSERT INTO users(username,PASSWORD) VALUES (?,?) ";
Object[] params={uname,pwd};
int i=this.executeSql(sql, params);
if(i>0){
flag=true;
}
this.closeSource();
return flag;
}
}
逻辑处理层接口:
package cn.com.userService;
//处理逻辑层接口
public interface UserService {
//用户注册查找数据库,有无此用户
public boolean selectSQL(String name);
//用户登录,判断用户名和密码是否正确
public boolean selectsql(String name,String password);
//用户注册成功,用户信息插入数据库
public boolean executeSQL(String uname, String pwd);
}
逻辑处理层接口实现类:
package cn.com.userServiceImpl;
//处理逻辑层接口实现类
import cn.com.userDao.UserDao;
import cn.com.userDaoImpl.UserDaoImpl;
import cn.com.userService.UserService;
public class UserServiceImpl implements UserService{
private UserDao userDao;
public UserServiceImpl (){
userDao=new UserDaoImpl();
}
//用户注册,根据用户名查找数据库,有无此用户
public boolean selectSQL(String name) {
return userDao.selectSQL(name);
}
///用户登录,判断用户名和密码是否正确
public boolean selectsql(String name,String password) {
boolean flag=false;
String pwd=userDao.selectsql(name);
if(pwd.equals(password)){
flag=true;
}
return flag;
}
//用户注册成功,用户信息插入数据库
public boolean executeSQL(String uname, String pwd){
return userDao.executeSQL(uname, pwd);
}
}
servlet类:连接数据库与jsp页面
package cn.school.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import cn.com.userService.UserService;
import cn.com.userServiceImpl.UserServiceImpl;
public class LoginServlet extends HttpServlet {
private UserService uservice;
//用户登录验证
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String userName=request.getParameter("username");
String password=request.getParameter("password");
if(userName!=null){
uservice=new UserServiceImpl();
boolean flag=uservice.selectsql(userName, password);
if(flag ){
HttpSession session=request.getSession();
session.setAttribute("mess", "欢迎"+userName);
response.sendRedirect("/login/jsp/welcome.jsp");
}else{
request.setAttribute("mess","用户名或者密码错误");
request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
}
}
// request.setCharacterEncoding("utf-8");
String name=request.getParameter("uname");
String pwd=request.getParameter("pwd");
if(name!=null && pwd!=null){
uservice=new UserServiceImpl();
boolean flag= uservice.executeSQL(name, pwd);
if(flag){
HttpSession session=request.getSession();
session.setAttribute("mess", "欢迎"+name);
response.sendRedirect("/login/jsp/welcome.jsp");
}else{
response.sendRedirect("/jsp/registration.jsp");
}
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
//用户注册验证
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
在实现页面注册和登录过程主要明白代码运转流程,首先在注册时,也通过连接数据库,查找有无此用户名信息,既调用数据库的查找方法,有则不能注册,无才可以注册。注册的过程就是将用户信息插入数据库的过程,调用数据库的插入方法。
而登录过程简单来说查找用户信息的过程,用户名和密码匹配即可进入欢迎页面。
而实现非空验证和用户信息验证通过ajax就可以完成。