【JSP基础】JSP实现登录注册界面
2015-07-29 11:36
861 查看
初学者,很多迷惑,把自己写的东西记录下来,希望帮到各位以外,也希望自己有迷惑的时候再回来看一看,解除迷惑。
首先是JAVAbeen:
之后,我们需要建立一个与之对应的数据库表,这里用的是mysql数据库,
所以我们要在WEB-INT/lib路径下导入与数据库连接的jre包,这里用的是:
做好准备工作之后,就开始我们的工程了。
写一个与数据库连接的class。
接着,需要建立我们完成登录所用的两个方法,首先写一个接口,这样会让代码更规范,执行效率更高。
然后就是实现这个接口的类:(登录和注册需要的两个方法)
完成之后开始写登录的jsp网页:登录这里用到了关于验证码的东西,验证码先不解释,最后解释。
建立jsp后,需要建立一个servlet去接收form表单传来的数据。
通过post方法接收来自网页的消息。这里post方法与get方法是有区别的,get方法常用语小于2k内容的信息传递。
然后建立注册的jsp:
与登陆一致,需要建立相应的servlet去接收消息,:
这样登录和注册页面就可以完成了。这里再说一下关于验证码的问题。
验证码用于恶意登录。
刚刚在登录页面我们已经写了它的界面,这里需要建立一个相应的servlet他就可以正常运行了。
最后把工程截图发上来。
首先是JAVAbeen:
public class User { protected int username; protected String password; protected String code; public int getUsername() { return username; } public void setUsername(int username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getCode() { return code; } public void setCode(String tell) { this.code = code; }
之后,我们需要建立一个与之对应的数据库表,这里用的是mysql数据库,
所以我们要在WEB-INT/lib路径下导入与数据库连接的jre包,这里用的是:
做好准备工作之后,就开始我们的工程了。
写一个与数据库连接的class。
public class DBOperator { protected final static String driver = "com.mysql.jdbc.Driver"; protected final static String url = "jdbc:mysql://localhost:3306/当前所要使用的数据库名"; static { try { Class.forName(driver); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } public static Connection getconnection( ){ Connection conn = null; try { conn= (Connection) DriverManager.getConnection(url,"root","root");//只是mysql进入的用户名和密码。 } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return conn; } public static void close (Statement st, ResultSet rs, Connection conn ){ try { if(st!=null){ st.close(); } if (rs!=null){ rs.close(); } if(conn!=null){ conn.close(); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } public static void close(PreparedStatement pst, Connection conn){ try { if(pst!=null){ pst.close(); } if(conn!=null){ conn.close(); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }
接着,需要建立我们完成登录所用的两个方法,首先写一个接口,这样会让代码更规范,执行效率更高。
public interface UserManager { public boolean add( User u); public boolean addm( int username ,String password); }
然后就是实现这个接口的类:(登录和注册需要的两个方法)
public class UserManagerImpl implements UserManager{ @Override public boolean add(User u) { // TODO Auto-generated method stub boolean flag = false; Connection conn = null; PreparedStatement pst = null; try { conn = DBOperator.getconnection(); String sql = "insert into t_users (username,password,code) value(?,?,?)"; pst = (PreparedStatement) conn.prepareStatement(sql); pst.setInt(1, u.getUsername()); pst.setString(2, u.getPassword()); pst.setString(3, u.getCode()); int rows = pst.executeUpdate(); if(rows>0){ flag= true; } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ DBOperator.close(pst, conn); } return flag; } @Override public boolean addm(int username, String password) { // TODO Auto-generated method stub boolean flag = false; Connection conn = null; Statement st = null; ResultSet rs = null; try { conn = DBOperator.getconnection(); String sql = "select * from t_users where username="+username; st = (Statement) conn.createStatement(); rs = (ResultSet) st.executeQuery(sql); while(rs.next()){ if (rs.getString("password").equals(password)){ flag = true; } } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ DBOperator.close(st, rs, conn); } return flag; } }
完成之后开始写登录的jsp网页:登录这里用到了关于验证码的东西,验证码先不解释,最后解释。
<%@ 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 'index.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 reLoadCode(){ var t = new Date().getTime(); document.getElementById("imagecode").src ="ImageServlet?t="+t; } </script> </head> <body> <form action="addm" method="post" align="center"> <cneter><h1>登录</h1></cneter> <b>用户名:</b><input type="text" name="Username" style="width: 193px; "><br> <p></p> <b>密 码:</b><input type="password" name="Password" style="width: 193px; "><br> <p></p> 验证码:<input name="Checkcode" type="text" style="width: 193px; "> <img alt="验证码" src="ImageServlet" id="imagecode"> <a href="javaScript:reLoadCode()">看不清</a> <br> <font size="+1" > <p> <input name="submit" type="submit" class="button" style="width:200px; height:35px " value="登录" /> </p> <p> <font size="-1" color="#000099"><a href="zhuce.jsp">注册</a> </font> </p> </font> </form> </body> </html>
建立jsp后,需要建立一个servlet去接收form表单传来的数据。
public class addm extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); int un = Integer.parseInt(request.getParameter("Username")); String pswd = request.getParameter("Password"); String checkcode = request.getParameter("Checkcode"); String pickcode = (String) request.getSession().getAttribute("piccode"); UserManager um = new UserManagerImpl(); User u = new User(); boolean flag= false; try { flag = um.addm(un, pswd); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } if(flag&&checkcode.equals(pickcode)){ response.sendRedirect("logchegngong.jsp"); } } }
通过post方法接收来自网页的消息。这里post方法与get方法是有区别的,get方法常用语小于2k内容的信息传递。
然后建立注册的jsp:
<%@ 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 'zhuce.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> <h1 align="center">注册新用户</h1> <hr/> <form action="add" method="post" align="center" > 用户名:<input name="Username" type="text"/><br/> <p></p> 密 码:<input name="Password" type="password"/><br/> <p></p> 验证码:<input name="Code" type="text"><br/> <p></p> <input type="submit" style="width:80px; height:35px "value="注册" /> </form> <a href="index.jsp">返回 </a> </body> </html>
与登陆一致,需要建立相应的servlet去接收消息,:
public class add extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); int username = Integer.parseInt(request.getParameter("Username")); String pswd = request.getParameter("Password"); String code = request.getParameter("Code"); UserManager um =new UserManagerImpl(); User u = new User(); u.setUsername(username); u.setPassword(pswd); u.setCode(code); boolean flag= false; try { flag = um.add(u); if(flag==true){ response.sendRedirect("index.jsp"); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } }
这样登录和注册页面就可以完成了。这里再说一下关于验证码的问题。
验证码用于恶意登录。
刚刚在登录页面我们已经写了它的界面,这里需要建立一个相应的servlet他就可以正常运行了。
public class ImagerServelt extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1、BufferedImage图像数据缓冲区 BufferedImage bi = new BufferedImage(70, 40, BufferedImage.TYPE_INT_RGB); //2、Graphics绘制图片 Graphics g = bi.getGraphics(); //3、Color获取颜色 Color c = new Color(80,10,50); g.setColor(c); g.fillRect(0, 0, 70, 40); char ch[] = "ABCDEFGHIJK123456789".toCharArray(); StringBuffer sb = new StringBuffer(); //4、Random生成随机数 Random r = new Random(); for (int i = 0; i < 4; i++) { int index = r.nextInt(ch.length); g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255))); g.drawString(ch[index]+"", i*15+3, 20); sb.append(ch[index]); } request.getSession().setAttribute("piccode", sb.toString()); ImageIO.write(bi, "JGP", response.getOutputStream()); } }
最后把工程截图发上来。
相关文章推荐
- js数组去重的方法汇总
- JS中prototype详解
- JavaScript学习要点(十一)
- Js解决ie6不支持fixed的方法
- 浅谈JavaScript的Polymer框架中的behaviors对象
- 常用js操作:
- 原生Js封装的产品图片360度展示
- JavaScript中的cacheStorage使用详解
- Js动态获取iframe子页面的高度总结
- JSP的基本构成详解
- JS - 跳转页面
- jsp预览本地上传图片
- Javascript offsetLeft详情
- jstack(查看线程)、jmap(查看内存)和jstat(性能分析)命令
- js 正则表达式之test函数讲解
- 浅谈Javascript数组的使用
- JS - 提示是否删除
- JSP入门
- SiteMesh在JSP中的页面装饰
- 浅谈Javascript数组索引