domainjavascript
package cn.code.domain; /* * 实体类 * */ public class User { private String username; private String password; private String verifyCode; @Override public String toString() { return "User [username=" + username + ", password=" + password + ", verifyCode=" + verifyCode + "]"; } public User(String username, String password, String verifyCode) { super(); this.username = username; this.password = password; this.verifyCode = verifyCode; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getVerifyCode() { return verifyCode; } public void setVerifyCode(String verifyCode) { this.verifyCode = verifyCode; } public User() { } }
daocss
package cn.code.dao; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import cn.code.domain.User; /** * 数据类 * */ public class UserDao { private String path="G:/users.xml"; public User findByUsername(String username){ /** * 获得Document * xpath查询 * 校验查询结果是否为null,若是为null,返回null; * 若是不为null,须要把Element封装到user对象中。 * */ SAXReader r = new SAXReader(); try{ Document document = r.read(path); Element element = (Element) document.selectSingleNode("//user[@username='"+username+"']"); if(element==null){return null;} User user = new User(); String attrUsername = element.attributeValue("username"); String attrPassword = element.attributeValue("password"); user.setUsername(attrUsername); user.setPassword(attrPassword); return user; }catch(Exception e){ throw new RuntimeException(e); } } public void add(User user){ /** * 获得document * 经过document获得root元素! * 将参数user转换成user标签 * 添加属性并赋值 * 保存document * */ SAXReader reader = new SAXReader(); try { Document document = reader.read(path); Element root = document.getRootElement(); Element userEle = root.addElement("user"); userEle.addAttribute("username", user.getUsername()); userEle.addAttribute("password", user.getPassword()); OutputFormat format = OutputFormat.createPrettyPrint(); // OutputFormat format = new OutputFormat("\t",true);//缩进,是否换行 // format.setTrimText(true);//清空全部换行跟缩进 XMLWriter writer = null; try { writer = new XMLWriter( new OutputStreamWriter( new FileOutputStream(path),"utf-8"),format); //注意字符编码,默认使用电脑默认编码保存,这里咱们使用utf-8; } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { writer.write(document); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (DocumentException e) { throw new RuntimeException(e); } } }
servicehtml
package cn.code.service; import cn.code.dao.UserDao; import cn.code.domain.User; public class UserService { private UserDao userDao = new UserDao(); public void regist(User user)throws UserException{ /** * 使用用户名去查询,若是返回null,完成添加 * 若是返回布市null,抛出异常! * */ User u = userDao.findByUsername(user.getUsername()); if(u!=null)throw new UserException("用户名"+user.getUsername()+"已经被注册!"); userDao.add(user); } public User login(User user) throws UserException { User u = userDao.findByUsername(user.getUsername()); if(u==null)throw new UserException("用户名不存在!"); if(!u.getPassword().equals(user.getPassword())){ throw new UserException("密码错误"); } return u; } }
package cn.code.service; public class UserException extends Exception { /** * */ private static final long serialVersionUID = 1L; public UserException() { super(); // TODO Auto-generated constructor stub } public UserException(String message) { super(message); // TODO Auto-generated constructor stub } }
servletjava
package cn.code.web.servlet; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.code.CommonUtils.CommonUtils; import cn.code.domain.User; import cn.code.service.UserException; import cn.code.service.UserService; public class RegistServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); /** * 封装表单数据(封装到user对象中) * */ User user = CommonUtils.toBean(request.getParameterMap(), User.class); /** * 表单校验 * */ String sessionVerifyCode = (String)request.getSession().getAttribute("session_vcode"); // if(!sessionVerifyCode.equalsIgnoreCase(user.getVerifyCode())){ // request.setAttribute("msg", "验证码不一致"); // request.setAttribute("user", user); // request.getRequestDispatcher("/regist.jsp").forward(request, response); // return; // } String username = user.getUsername(); String password = user.getPassword(); Map<String,String>errors = new HashMap<String, String>(); if(username==null||username.trim().isEmpty()){ errors.put("username", "用户名不能为空"); }else if(username.length()<3||username.length()>15){ errors.put("username", "请输入3-15为用户名"); } if(password==null||password.trim().isEmpty()){ errors.put("password", "用户名不能为空"); }else if(password.length()<3||password.length()>15){ errors.put("password", "请输入3-15为用户名"); } if(!sessionVerifyCode.equalsIgnoreCase(user.getVerifyCode())){ errors.put("msg", "验证码不一致"); } if(errors!=null&&errors.size()>0){ request.setAttribute("errors", errors); request.setAttribute("user", user); request.getRequestDispatcher("/regist.jsp").forward(request, response); return; } UserService userService = new UserService(); try { userService.regist(user); response.getWriter().print("注册成功!<a href='"+request.getContextPath()+"/login.jsp"+"'>登陆</a>"); } catch (UserException e) { request.setAttribute("msg", e.getMessage()); request.setAttribute("user", user); request.getRequestDispatcher("/regist.jsp").forward(request, response); } } }
package cn.code.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.code.CommonUtils.CommonUtils; import cn.code.domain.User; import cn.code.service.UserException; import cn.code.service.UserService; public class LoginServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8");//请求编码 response.setContentType("text/html;charset=utf-8");//响应编码 //依赖UserService /** * 封装表单数据到user * 调用sevice的login()方法,获得返回的user对象 * 若是抛出异常:获取异常信息,保存到request域中,再保存user,转发到login.jsp * 若是没有异常;保存返回值到session中,重定向到welcome.jsp * */ User user =CommonUtils.toBean(request.getParameterMap(), User.class); UserService userService = new UserService(); try{ User u= userService.login(user); request.getSession().setAttribute("sessionUser", u); response.sendRedirect(request.getContextPath()+"/index.jsp"); }catch(UserException e){ request.setAttribute("msg", e.getMessage()); request.setAttribute("user", user); request.getRequestDispatcher("/login.jsp").forward(request, response); } } }
package cn.code.web.servlet; import java.awt.image.BufferedImage; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.code.image.VerifyCode; public class VerifyCodeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //验证码类 VerifyCode vc = new VerifyCode(); //生成图片 BufferedImage image = vc.getImage(); //保存图片文本到session中 request.getSession().setAttribute("session_vcode", vc.getText()); //把图片响应给客户端 VerifyCode.output(image, response.getOutputStream()); } }
验证码类web
package cn.code.image; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import java.util.Random; import javax.imageio.ImageIO; public class VerifyCode { private int w=70; private int h=35; private Random r = new Random(); private String[] fontNames = {"宋体","华文楷体","黑体","微软雅黑","楷体_GB2321"}; private String codes = "23456789abcdefghjkmnopqrstuvwxyzQWERTYUIOPASDFGHJKLZXCVBNM"; private Color bgColor = new Color(255,255,255);//颜色类对象,背景色白色 private String text; //生成随机颜色 private Color randomColor(){ int red = r.nextInt(150); int green = r.nextInt(150); int blue = r.nextInt(150); return new Color(red,green,blue); } //生成随机字体 private Font randomFont(){ int index = r.nextInt(fontNames.length); String fontName = fontNames[index];//生成随机的字体名称 int style = r.nextInt(4);//生成随机样式,0(无样式),1(粗体),2(斜体),3(粗体+斜体) int size = r.nextInt(5)+24;//生成随机字号,24-28 return new Font(fontName,style,size); } //画干扰线 private void drawLine(BufferedImage image){ int num = 3;//一共画三条 Graphics2D g2 = (Graphics2D)image.getGraphics(); for(int i = 0;i<num;i++){//生成2个点的坐标,即4个值; int x1 = r.nextInt(w); int y1 = r.nextInt(h); int x2 = r.nextInt(w); int y2 = r.nextInt(h); g2.setStroke(new BasicStroke(1.5F)); g2.setColor(Color.BLUE);//干扰线是蓝色 g2.drawLine(x1, y1, x2, y2);//画线 } } //随机生成一个字符 private char randomChar(){ int index = r.nextInt(codes.length()); return codes.charAt(index); } //建立bufferedImage private BufferedImage createImage(){ BufferedImage image = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB); Graphics2D g2 = (Graphics2D)image.getGraphics(); g2.setColor(this.bgColor); g2.fillRect(0, 0, w, h); return image; } //外界调用这个方法获得验证码 public BufferedImage getImage(){ //建立图片缓冲区 BufferedImage image = createImage(); //获得绘制环境 Graphics2D g2 = (Graphics2D)image.getGraphics(); //用来装载生成的验证码文本 StringBuilder sb = new StringBuilder(); //向图片中画4个字符 for(int i = 0;i<4;i++){ String s = randomChar()+"";//随机生成一个字符 sb.append(s);//把字母添加到sb中 float x = i * 1.0F * w / 4;//设置当前字符x轴坐标 g2.setFont(randomFont());//设置随即字体 g2.setColor(randomColor());//设置随机颜色 g2.drawString(s,x,h-5);//画图 } this.text=sb.toString();//把生成的字符串赋给this.text drawLine(image);//添加干扰线 return image; } //返回验证码图片上的文本 public String getText(){ return text; } //保存图片到指定的输出流 public static void output(BufferedImage image,OutputStream out) throws IOException{ ImageIO.write(image, "JPEG", out); } }
jspsession
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% 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 'regist.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 change(){ var ele = document.getElementById("vCode"); ele.src="<c:url value='/servlet/VerifyCodeServlet'/>?xxx="+new Date().getTime(); //alert(ele.src); } </script> </head> <body> <h1>注册</h1> <p style="color:red;font=weigth:900">${msg}</p> <!-- ${pageContext.request.contextPath}/RegistServlet } --> <form action="<c:url value='/RegistServlet'/>" method="post"> 用户名:<input type="text" name="username" value='${user.username}'/>${errors.username}<br/> 密 码:<input type="password" name="password" value="${user.password}"/>${errors.password}<br/> 验证码:<input type="text" name="verifyCode" value="${user.verifyCode }" size="3"/> <img id="vCode" src="<c:url value='/servlet/VerifyCodeServlet' /> "/> <a href="javascript:change()">换一张</a><br/> <input type="submit" value="注册"/> </form> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% 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> <h1>登陆</h1> <p>${msg}</p> <form action=<c:url value='/LoginServlet'/> method="post"> 用户名:<input type="text" name="username" value='${user.username}'/><br/> 密 码:<input type="password" name="password" value="${user.password}"/><br/> <input type="submit" value="登陆"/> </form> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="f" uri="http://java.sun.com/jsp/jstl/fmt" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% 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> <h1>欢迎登陆本网站:</h1> <c:choose> <c:when test="${empty sessionScope.sessionUser }">请先登陆</c:when> <c:otherwise> ${sessionScope.sessionUser } </c:otherwise> </c:choose> </body> </html>