注册登录系统(jsp+servlet)

package webdemo;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DBServlet extends HttpServlet {
	//用于连接数据库的Connection对象
	protected java.sql.Connection conn = null;
	//执行各种SQL语句的方法
	protected java.sql.ResultSet execSQL(String sql,Object...args)
			throws Exception
	{
		//建立PreparedStatement对象
		java.sql.PreparedStatement pStmt = conn.prepareStatement(sql);
		//为pSmt 对象设置SQL参数值
		for(int i=0;i<args.length;i++){
			pStmt.setObject(i+1, args[i]);  //设置SQL参数集
		}
		pStmt.execute();   //执行SQL语句
		return pStmt.getResultSet();
	}

	// 核对用户输入的验证码是否合法
	protected boolean checkValidationCode(HttpServletRequest request,String validationCode){
		String validationCodeSession = (String) request.getSession().getAttribute("validation_code");

		if(validationCodeSession == null){         //获得验证码是null的话              //设置result.jsp需要的结果信息
			request.setAttribute("info", "验证码过期");
			//设置login.jsp需要的错误信息
			request.setAttribute("codeError","验证码过期");
			return false;
		}
		if(validationCode.equalsIgnoreCase(validationCodeSession)==false){//两个验证码比较
			request.setAttribute("info", "验证码过期");

			request.setAttribute("codeError","验证码过期");
			return false;
		}
		return true;
	}

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try{
			if(conn == null){
				//创建上下文对象
				javax.naming.Context ctx = new javax.naming.InitialContext();
				//获取数据源
				javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup("java:/comp/env/jdbc/webdb");
				conn = ds.getConnection();  //为connection赋值
			}
		}catch (Exception e)
		{}
	}

	@Override
	public void destroy() {
		try{
			if(conn!=null){
				conn.close();
			}
		}catch(Exception e)
		{}
	}

}

另一种写法:

Connection cn=null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url="jdbc:mysql://localhost:3306/t_user?useUnicode=true&characterEncoding=GBK";
String user="root";
 String password="root";
 cn=DriverManager.getConnection(url,user,password);

在Tomcat的Server.xml中配置

<Context path="/webdemo" docBase="webdemo" debug="0">
      <Resource name="jdbc/webdb" auth="Container"
               type="javax.sql.DataSource"
               driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/webdb?characterEncoding=UTF-8"
               username="root"
               password="1234"
               maxActive="200"
               maxIdle="50"
               maxWait="3000"/>
</Context>

Register继承DBServlet  

package webdemo;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Register extends DBServlet {

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String userName = null;

		if(request.getParameter("login")!=null){
			response.sendRedirect("/webdemo/login.jsp");//重定向写绝对路径
			return;
		}

		try{
			super.service(request, response); //打开数据库

			userName = request.getParameter("username");
			String password = request.getParameter("password");
			String email = request.getParameter("email");
			String validationCode = request.getParameter("validation_code");

			if(userName==null||password==null||validationCode==null){
				return;
			}
			if(userName.equals("")||password.equals("")||validationCode.equals("")){
				return;
			}

			//进行编码转换,以支持中文用户名
			userName = new String(userName.getBytes("ISO-8859-1"),"UTF-8");

			request.setAttribute("page", "/webdemo/register.jsp");//requestScope里面可以调用 绝对地址   跳转register.jsp

			if(!checkValidationCode(request,validationCode)){
				return;
			}
			email = (email == null)?"":email;

			String passwordMD5 = webdemo.Encrypter.md5Encrypt(password);

			String sql = "insert into t_users(user_name,password_md5,email) values(?,?,?)";

			execSQL(sql,userName,passwordMD5,email);

			request.setAttribute("info", "用户注册成功!");
		}catch(Exception e){
			System.out.println(e.getMessage());
			request.setAttribute("info", userName+"已经被使用!");
		}
		finally{
			RequestDispatcher rd =request.getRequestDispatcher("/result.jsp");
			rd.forward(request, response);
		}
	}

}

 response.sendRedirect("/webdemo/login.jsp");//重定向写绝对路径

 request.setAttribute("page", "/webdemo/register.jsp");//requestScope里面可以调用 绝对地址 跳转register.jsp

register.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>
<title>注册系统</title>
<script type="text/javascript">
	function refresh(){
		var img = document.getElementById("img_validation_code");
		var time= new Date().getTime();
		//refresh 验证码重新输出
		img.src="<%= request.getContextPath()%>/servlet/ValidationCode?d="+time;
	}
	function checkEmail(email){
		var email = email.value;
		var pattern = /^([a-zA-Z0-9._-])[email protected]([a-zA-Z0-9._-])+(\.[a-zA-Z0-9._-])+/;

		flag = pattern.test(email);

		if(!flag){
			alert("email格式不正确!");
			email.focus();
			return false;
		}
		return true;
	}
	function checkRegister(){
		var username = document.getElementById("username");
		if(username.value == ""){
			alert("必须输入用户名!");
			username.focus();
			return;
		}

		var password = document.getElementById("password");
		if(password.value == ""){
			alert("必须输入密码!");
			password.focus();
			return;
		}

		var repassword = document.getElementById("repassword");
		if(repassword.value != password.value){
			alert("输入的密码不一致!");
			repassword.focus();
			return;
		}

		var email = document.getElementById("email");
		if(email.value != ""){
			if(!checkEmail(email)){
				return;
			}
		}

		var validation_code = document.getElementById("validation_code");
		if(validation_code.value == ""){
			alert("验证码必须输入");
			validation_code.focus();
			return;
		}
		register_form.submit();  //提交用户注册信息
	}
</script>
</head>
<body>
<form name="register_form" action="/webdemo/servlet/Register" method="post">
	<span class="require">*</span>用户名:
	<input type="text" id="username" name="username" size="30" maxLength="30"/><div/>
	<span class="require">*</span>密码:
	<input type="password" id="password" name="password" size="30" maxLength="30"/><div/>
	<span class="require">*</span>请再次输入密码:
	<input type="password" id="repassword" name="repassword" size="30" maxLength="30"/><div/>
	邮箱地址:
	<input type="text" id="email" name="email" size="30" maxLength="30"/><div/>
	<span class="require">*</span>验证码:
	<input type="text" id="validation_code" name="validation_code" style="width:60px;margin-top:2px" size="30" maxLength="30"/>
	<img id="img_validation_code" src="<%= request.getContextPath()%>/servlet/ValidationCode"/>
	<input type="button" value="刷新" onclick="refresh()"/><div/>
	<input type="button" value="注册" onclick="checkRegister()"/>
	<input type="submit" value="登录" name="login"/>
</form>
</body>
</html>

 img.src="<%= request.getContextPath()%>/servlet/ValidationCode?d="+time;//验证码刷新

register_form.submit(); //提交用户注册信息

 Login继承DBServlet

package webdemo;

import java.io.IOException;
import java.sql.ResultSet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Login extends DBServlet {

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		if(request.getParameter("register")!=null){
			response.sendRedirect("/webdemo/register.jsp");
			return;
		}
		String page = "/login.jsp";
		String userName = "";
		try{
			super.service(request, response);
			userName = request.getParameter("username");

			String password = request.getParameter("password");

			String validationCode = request.getParameter("validation_code");

			if(userName == null||password == null||validationCode == null){
				return;
			}
			if(userName.equals("")||password.equals("")||validationCode.equals("")){
				return;
			}
			userName = new String(userName.getBytes("ISO-8859-1"),"utf-8");

			if(!checkValidationCode(request,validationCode)){
				return;
			}
			String sql = "select user_name,password_md5 from t_users where user_name = ?";

			ResultSet rs = execSQL(sql, new Object[] { userName });
			if(rs.next() == false){
				request.setAttribute("userError", userName+"不存在");
			}
			else{
				String passwordMD5 = webdemo.Encrypter.md5Encrypt(password);
				if(!rs.getString("password_md5").equals(passwordMD5)){
					request.setAttribute("passwordError", "密码不正确");
				}
				else{
					page = "/main.jsp";
				}
			}
		}catch(Exception e){

		}
		finally{
			request.setAttribute("username", userName);
			RequestDispatcher rd = request.getRequestDispatcher(page);
			rd.forward(request, response);
		}
	}

}

login.jsp

<%@ page language="java" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>登录系统</title>
<script type="text/javascript">
	function refresh(){
		var img = document.getElementById("img_validation_code");
		var time= new Date().getTime();
		//refresh 验证码重新输出
		img.src="<%= request.getContextPath()%>/servlet/ValidationCode?d="+time;
	}
	function checkLogin(){
		var username = document.getElementById("username");
		if(username.value == ""){
			alert("必须输入用户名!");
			username.focus();
			return;
		}

		var password = document.getElementById("password");
		if(password.value == ""){
			alert("必须输入密码!");
			password.focus();
			return;
		}

		var validation_code = document.getElementById("validation_code");
		if(validation_code.value == ""){
			alert("验证码必须输入");
			validation_code.focus();
			return;
		}
		login_form.submit();  //提交用户注册信息
	}
</script>
</head>
<body>
<form name="login_form" action="/webdemo/servlet/Login" method="post">
	用户名:
	<input type="text" id="username" value="${requestScope.username }" class="input_list" name="username" size="30"
		maxLength="30"/>
	<font color="#FF0000">${requestScope.userError }</font><div/>
	密码:
	<input type="password" id="password" class="input_list" name="password" size="30" maxLength="30"/>
	<font color="#FF0000">${requestScope.passwordError }</font><div/>
	验证码:
	<input type="text" id="validation_code" name="validation_code" style="width:60px;margin-top:2px" size="30"
		maxLength="30"/>
	<img id="img_validation_code" src="<%= request.getContextPath()%>/servlet/ValidationCode"/>
	<input type="button" value="刷新" onclick="refresh()"/>
	<font color="#ff0000">${requestScope.codeError }</font><div/>
	<input type="button" value="登录" name="login" onclick="checkLogin()"/>
	<input type="submit" value="注册" name="register"/>
</form>
</body>
</html>

ValidationCode

package webdemo;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ValidationCode extends HttpServlet {
	private static String codeChars =
			"%#23456789qwaszxerdfcvtgbnhyujmkioplZAQWSXCDERFVBGTYHNMJUIKLOP";
	private static Color getRandomColor(int minColor,int maxColor){
		Random random = new Random();
		//保存minColor 最大不会超过255
		if(minColor > 255){
			minColor = 255;
		}
		if(maxColor > 255){
			maxColor = 255;
		}

		int red = minColor + random.nextInt(maxColor-minColor);
		int green = minColor + random.nextInt(maxColor-minColor);
		int blue = minColor +random.nextInt(maxColor-minColor);
		return new Color(red,green,blue);
	}
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int charsLength = codeChars.length();

		//下面三句关闭客户端浏览器的缓冲区
		response.setHeader("ragma","No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires",0);

		//设置图形验证码的长和宽
		int width=90,height=20;
		BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		//获得用于输出文字的Graphics对象
		Graphics g = image.getGraphics();
		Random random=new Random();
		g.setColor(getRandomColor(180,250));
		g.fillRect(0, 0, width, height);

		g.setFont(new Font("Times New Roman",Font.ITALIC,height));
		g.setColor(getRandomColor(120,180));

		StringBuilder validationCode = new StringBuilder();

		String[] fontNames = {"Times New Roman","Book antiqua","Arial"};

		for (int i=0;i<3+random.nextInt(3);i++){
			g.setFont(new Font(fontNames[random.nextInt(3)],Font.ITALIC,height));

			char codeChar=codeChars.charAt(random.nextInt(charsLength));
			validationCode.append(codeChar);

			g.setColor(getRandomColor(10,100));

			g.drawString(String.valueOf(codeChar), 16*i+random.nextInt(7), height-random.nextInt(6));
		}

		HttpSession session = request.getSession();    //session存储验证码

		session.setMaxInactiveInterval(5*60);

		session.setAttribute("validation_code", validationCode.toString()); //在注册页面使用 用session在图上打印

		g.dispose();
		OutputStream os = response.getOutputStream();
		ImageIO.write(image, "JPEG", os);
	}

}

 

  

  

  

时间: 2024-10-28 20:10:49

注册登录系统(jsp+servlet)的相关文章

一个基于Unix套接字的注册登录系统

2016/5/5 今天,我参考<Unix网络编程-卷1>第5章的TCP回射客户/服务器程序写了一个简单的注册登录系统,其功能如下:(1)注册.客户端向服务器发送个人信息请求注册,服务器查询MySQL数据库以检查该客户是否已存在,若是则禁止注册,并返回“用户已存在,注册失败”的错误信息,否则将新用户信息添加到MySQL数据库,并返回“注册成功”的信息.(2)登录.客户端向服务器发送个人账号和密码等两项信息,服务器查询MySQL数据库以检查账号是否存在.账号和密码是否匹配,若不存在或不匹配则禁止登

php注册登录系统(一)-极简

序 登录注册系统是日常上网最普通的操作,我设了一个分类一步步完善注册登录系统,若有哪里错误请慧教 所用语言:php 数据库 :mysql 本次实现功能: 1.用户注册 2.用户登录 主要文件: 1 sql 在已有的数据库里创建user表,id,username,password三个字段 1 create table username( 2 id int(10) not null auto_increment, 3 username varchar(30), 4 password varchar(

(一)php注册登录系统-极简

序 登录注册系统是日常上网最普通的操作,我设了一个分类一步步完善注册登录系统,若有哪里错误请慧教 所用语言:php 数据库 :mysql 本次实现功能: 1.用户注册 2.用户登录 主要文件: 完整代码 1 sql 在已有的数据库里创建user表,id,username,password三个字段 create table user(id int(10) not null auto_increment,username varchar(30),password varchar(40),primar

MyEclipse2013和SQLserver2008简单的注册/登录/修改密码servlet实现

原文:MyEclipse2013和SQLserver2008简单的注册/登录/修改密码servlet实现 源代码下载地址:http://www.zuidaima.com/share/1550463723506688.htm      1.myEclipse2013 2.tomcat7.0 3.SQLserver2008 MyEclipse2013 "UTF-8" SQLserver2008 数据库为db_user,表为user 可以导入SQL文件,执行以下.也可以自己创建一个数据库和数

Java小项目之:校园注册登录系统!

相信很多学校都有自己的网站,而且还有学生课表成绩查询的系统,和教师端的操作系统.今天教大家做一个简单的注册登录系统! 代码展示: package com.entity; public class Teacher { private int id; private String name; private String sex; private int age; public Teacher(){ super(); } public Teacher(int id, String name) { s

基于javaweb人脸识别注册登录系统

---恢复内容开始--- 现在是2019年,人脸识别技术已经相当成熟了,百度自2017年发布人脸识别技术,已经被广泛应用,不管从现在的iphoneX掀起的面部解锁到手机应用端的各种人脸认证,这一技术已经悄然升息的方便了我们的生活,但是在web端注册登录缺很少用到刷脸登录,第一个最主要的原因可能是安全隐私方面人们对大数据时代的误解.不多废话,下面通过调用百度api来实现人脸注册及登录, Web端人脸识别主要有三个技术思路: 1.前端的人脸识别,例如使用Tensorflow.js, 2.后台人脸识别

注册登录系统2.0

延续上个系统的升级,相较1.0 版本,2.0 程序语句更简练. 1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 struct sj //构造账号,密码 5 { 6 char zh[20]; 7 char mm[20]; 8 }; 9 typedef struct sj sj ; 10 sj k={' '}; 11 void menu () // 开始菜单 12 { 13 printf(&qu

简单登录(jsp+servlet)

开发环境eclipse+tomcat8 1.先创建web project,项目名为RegisterSystem, 2.在WebRoot 目录下创建login.jsp文件,只需修改body中的内容,如下所示: <body>    <form action="login">    username:<input type="text" name="username"><br>    password:&

JSP+Servlet+JDBC+Mysql实现的博客系统

本文存在视频版本,请知悉 项目简介 项目来源于:https://gitee.com/nanpingping/jsp-blog 这次分享个人博客系统,界面简洁大气,功能齐全,是不可多得的比较容易的系统,非常适合毕业设计或者课程设计. 本系统基于JSP+Servlet+JDBC+Mysql.涉及技术少,易于理解,适合JavaWeb初学者学习使用. 难度等级:简单 技术栈 编辑器 IntelliJ IDEA 2019.1.1 (Ultimate Edition) 前端技术 基础:html+css+Ja