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