初学者,记录学习的点点滴滴;
验证码没搞出来,有点累,头疼! 希望有大神指导,帮我搞一下这验证码。
总结一下吧:
注册:其实就是在servle中t,验证从jsp获取的数据
1.用户输入是否为空,为空则显示用户名不能为空,
2.如果已经被注册过了,就显示已经注册过,请重新填写用户名。
3.密码是否为空,为空则显示不能为空。
登录:
验证从数据库获取的数据是否与表单获取的数据相同;
不同则显示,用户名或者密码错误;
其实都很简单。第一次写比较麻烦而已,我就是练练手而已。
1.User实体类
package com.entity; //映射数据库中表的字段名 public class User { private int id; private String userName; private String name; private String sex; private String pwd; public User() { super(); // TODO Auto-generated constructor stub } public User( String name,String userName, String pwd,String sex) { super(); this.userName = userName; this.name = name; this.sex = sex; this.pwd = pwd; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((sex == null) ? 0 : sex.hashCode()); result = prime * result + ((userName == null) ? 0 : userName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (id != other.id) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (sex == null) { if (other.sex != null) return false; } else if (!sex.equals(other.sex)) return false; if (userName == null) { if (other.userName != null) return false; } else if (!userName.equals(other.userName)) return false; return true; } @Override public String toString() { return "User [id=" + id + ", userName=" + userName + ", name=" + name + ", sex=" + sex + "]"; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } }2.数据库操作的接口和实现类
package com.dao; import java.sql.SQLException; import com.entity.User; //与数据库有关的操作的接口 public interface UserDao { //注册用户 public void add(User user) throws ClassNotFoundException, SQLException; //用户登录 public User findByUser(String userName) throws SQLException, ClassNotFoundException; }
package com.dao; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.entity.User; import com.mysql.jdbc.PreparedStatement; import com.util.DBUtils; public class UserDaoImpl implements UserDao { //用户增加 @Override public void add(User user) throws ClassNotFoundException, SQLException { // TODO Auto-generated method stub Connection conn=DBUtils.getConn(); Statement st=conn.createStatement(); String sql="insert into t_user (name,userName,pwd,sex) values('"+user.getName()+"','"+user.getUserName()+"','"+user.getPwd()+"','"+user.getSex()+"')"; st.executeUpdate(sql); DBUtils.CloseConn(conn); } @Override public User findByUser(String userName) throws SQLException, ClassNotFoundException { // TODO Auto-generated method stub Connection conn=DBUtils.getConn(); String sql="select * from t_user where userName=?"; PreparedStatement ps=(PreparedStatement) conn.prepareStatement(sql); ps.setString(1, userName); ResultSet rs=ps.executeQuery(); User u = null; while(rs.next()){ int id=rs.getInt(1); String name=rs.getString(2); String pwd=rs.getString(3); String sex=rs.getString(4); u=new User(); u.setId(id); u.setName(name); u.setPwd(pwd); u.equals(sex); } return u; } }
3.业务逻辑service接口和实现类
package com.service; import com.entity.User; public interface UserService { public User findByUser(String userName); public void add(User user); }
package com.service; import java.sql.SQLException; import com.dao.UserDao; import com.entity.User; public class UserServiceImpl implements UserDao { private UserDao dao ; public UserServiceImpl(UserDao dao) { super(); this.dao = dao; } //增加用户的service @Override public void add(User user) throws ClassNotFoundException, SQLException { // TODO Auto-generated method stub dao.add(user); } public UserDao getDao() { return dao; } public void setDao(UserDao dao) { this.dao = dao; } //查找用户的额service @Override public User findByUser(String userName) throws SQLException, ClassNotFoundException { // TODO Auto-generated method stub return dao.findByUser(userName); } }4.util工具类
package com.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DBUtils { //获取链接 public static Connection getConn() throws ClassNotFoundException{ Class.forName("com.mysql.jdbc.Driver"); Connection conn = null; try { conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test03?useUnicode=true&charactEncoding=gbk","root","1234"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return conn; } //关闭数据库 public static void CloseConn(Connection conn){ if(conn!=null){ try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
5.servletweb层,负责转发给jsp
package com.web; import java.io.IOException; import java.sql.SQLException; 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 com.dao.UserDaoImpl; import com.entity.User; import com.service.UserServiceImpl; @SuppressWarnings("serial") public class UserServlet extends HttpServlet { protected void service(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{ //编码设置 request.setCharacterEncoding("GBK"); response.setContentType("text/html;charset=gbk"); String uri=request.getRequestURI(); String path=uri.substring(uri.lastIndexOf("/"),uri.lastIndexOf(".")); UserServiceImpl service= new UserServiceImpl(new UserDaoImpl()); //根据叠取的请求名转发到对用的页面 if(path.equals("/regist")){ String userName=request.getParameter("userName").trim(); String name=request.getParameter("name"); String pwd=request.getParameter("pwd").trim(); String sex=request.getParameter("sex"); //根据用户名查找用户是否存在,如果存在给一个提示,继续留在注册界面 if(userName.isEmpty()){ request.setAttribute("regist_err","用户名不能为空"); request.getRequestDispatcher("regist.jsp").forward(request, response); }else if(pwd.isEmpty()){ request.setAttribute("regist_err1", "密码不能为空"); request.getRequestDispatcher("regist.jsp").forward(request, response); }else{ User user = null; try { user = service.findByUser(userName); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(user==null){ User u=new User(userName,name,pwd,sex); try { service.add(u); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } response.sendRedirect(request.getContextPath()+"/login.jsp"); }else{ request.setAttribute("regist_err", "用户名已经存在,请重新注册!"); request.getRequestDispatcher("regist.jsp").forward(request, response); } } }else if(path.equals("/login")){ String userName=request.getParameter("userName"); String pwd=request.getParameter("pwd"); User user = null; try { user = service.findByUser(userName); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(user!=null&&user.getPwd().equals(pwd)){ HttpSession session=request.getSession(); session.setAttribute("login_success",user); response.sendRedirect(request.getContextPath()+"/index.jsp"); }else{ request.setAttribute("login_err","用户名或者密码错误"); request.getRequestDispatcher("/login.jsp").forward(request,response); } } } }
6.注册+登录页面+登录成功会跳的页面
<%@ page language="java" import="java.util.*" pageEncoding="GBK" contentType="text/html; charset=GBK"%> <% 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>用户注册</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>欢迎来到澳门博彩用户注册页面</h1> <form action="regist.do" method="post"> <table> <tr><td>姓名:</td><td><input type="text" name="userName"/></td> <% String str=(String)request.getAttribute("regist_err"); String str1=(String)request.getAttribute("regist_err1"); %> <td><%=str==null?"":str%><td> </tr> <tr><td>邀请码:</td><td><input type="text" name="name"/></td></tr> <tr><td>密码:</td><td><input type="text" name="pwd"/></td><td><%=str1==null?"":str1%><td></tr> <tr><td>性别: </td><td>男:<input type="radio" name="sex" value="M" checked="checked"/>女:<input type="radio" name="sex" value="W"/></td></tr> <tr><td> <input type="submit" value="提交"/></td></tr> </table> </form> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <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> <h1>欢迎来到澳门博彩用户登录页面</h1> <form action="login.do" method="post"> <table> <tr><td>用户名:</td><td><input type="text" name="userName"/></td> <td> <%=request.getAttribute("login_err")==null?"":request.getAttribute("login_err") %></td> </tr> <tr><td>密码:</td><td><input type="text" name="pwd"/></td></tr> <tr><td> <input type="submit" value="提交"/></td></tr> </table> </form> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%> <% 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"> --> </head> <body> This is my JSP page. <br> <h1> 来玩呀,充100送100!、、、、、、</h1> </body> </html>7.web,xml和sql
<?xml version="1.0" encoding="GBK"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <servlet> <servlet-name>myCode</servlet-name> <servlet-class>com.web.CheckCodeServlet</servlet-class> </servlet> <servlet> <servlet-name>userServlet</servlet-name> <servlet-class>com.web.UserServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>userServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>myCode</servlet-name> <url-pattern>/checkCode</url-pattern> </servlet-mapping> </web-app>
create database test03; create table t_user( id int primary key auto_increment, name varchar(20), userName varchar(20), pwd varchar(20), sex varchar(2) ); select * from t_user;