生成验证码:
ImgServlet.java:
package cn.hncu.servlets; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 生成验证码! * ---4个随机数字,8条随机干扰线-数字,线的颜色随机 * @author 陈浩翔 * 2016-8-2 */ public class ImgServlet 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 { response.setContentType("imag/jpg"); int width = 80; int height= 30; int lines = 8; BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = img.getGraphics(); g.setColor(Color.white); g.fillRect(0, 0, width, height); g.setFont(new Font("黑体", Font.BOLD, 18)); long time = new Date().getTime(); String realCode=""; Random r = new Random(time); for(int i=0;i<4;i++){ Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)); g.setColor(c); int y=r.nextInt(10); int a = r.nextInt(10); g.drawString(a+"",5+i*18,y+12); realCode+=a; } Cookie cook = new Cookie("realCode", realCode); cook.setMaxAge(60*60); cook.setPath(request.getContextPath()); response.addCookie(cook); //request.getServletContext().setAttribute("realCode",realCode); //System.out.println("imgServlet:"+realCode); for(int i=0;i<lines;i++){ Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)); g.setColor(c); g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height)); } //刷入img对象 g.dispose(); ImageIO.write(img, "jpg", response.getOutputStream()); } }
LoginServlet.java:
package cn.hncu.servlets; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.hncu.domain.Contact; import cn.hncu.domain.User; import cn.hncu.service.UserIService; import cn.hncu.service.UserServiceImpl; public class LoginServlet extends HttpServlet { //注入service UserIService service = new UserServiceImpl(); 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"); response.setContentType("text/html;charset=utf-8"); //1、收集参数 String name = request.getParameter("name"); String pwd = request.getParameter("pwd"); String code = request.getParameter("code"); String realCode=""; Cookie[] cs = request.getCookies(); for(Cookie c:cs){ if(c.getName().equals("realCode")){ realCode=c.getValue(); break; } } //System.out.println("rc="+realCode); //判断验证码 if(!code.equals(realCode)){ response.getWriter().print("<h1>验证码错误!</h1>"); return; } //2组织参数 User user = new User(); user.setName(name); user.setPwd(pwd); //3调用service层 user = service.login(user); //System.out.println(user); //4根据service层的返回结果,导向不同的结果页面---直接到前台去防护了 if(user==null){ response.getWriter().print("<h1>用户名或密码错误!</h1>"); return ; } //System.out.println(request.getLocalAddr()); List<Contact> contacts = new ArrayList<Contact>(); //通过user的uuid拿到所有的联系人 contacts=service.getUserContacts(user.getUuid()); request.getSession().setAttribute("contacts", contacts); request.getSession().setAttribute("user", user); request.getSession().setAttribute("userUuid",user.getUuid()); request.getRequestDispatcher("/jsps/contacts.jsp").forward(request, response); } }
contacts.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <c:if test="${empty sessionScope.user}"> <c:redirect url="/index.jsp"></c:redirect> </c:if> <link rel="stylesheet" href='<c:url value="/css/table.css"></c:url>'> <script type="text/javascript" src='<c:url value="/js/contact.js"></c:url>'> </script> <script type="text/javascript"> var path = '<c:url value="/" />'; </script> </head> <body> <br/> <div> <button onclick="_add()">添加联系人</button> <button onclick="_del()">删除联系人</button> <button onclick="_query()">查询联系人</button> </div> <br/> <div> <table id="tb"> <tr> <th>选择<input type="checkbox" id="parentChk" onclick="chk(this)"/></th> <th>姓名</th> <th>年龄</th> <th>电话</th> <th>ID</th> </tr> <c:forEach items="${contacts}" var="contact"> <tr> <td><input type="checkbox" name="childChk" onclick="subchk(this)" /></td> <td>${contact.name}</td> <td>${contact.age}</td> <td>${contact.tel}</td> <td>${contact.uuid}</td> </tr> </c:forEach> </table> <!-- 下面的form和iframe是用于做"_del()"功能的myAjax --> <form name="form" target="df" action='<c:url value="/DelServlet" ></c:url>' method="post"> <input type="hidden" name="ids" id="ids" /> </form> <iframe name="df" style="display: none;"></iframe> </div> </body> </html>
contact.js:
function _add(){ var url = path+"jsps/input.jsp"; var result = window.showModalDialog(url,"","dialogWidth:400px;dialogHeight:300px;"); if(result==null){ return; } realadd(result); } function realadd(obj){ var oTable = document.getElementById("tb"); var oTr = oTable.insertRow(); var oTd = oTr.insertCell(); oTd.innerHTML='<input type="checkbox" name="childChk" onclick="subchk(this)" /> '; oTr.insertCell().innerHTML=obj.name; oTr.insertCell().innerHTML=obj.age; oTr.insertCell().innerHTML=obj.tel; oTr.insertCell().innerHTML=obj.id; } function chk(obj){ //监听全部选择的那个复选框 var allChildChks = document.getElementsByName("childChk"); for(var i=0;i<allChildChks.length;i++){ allChildChks[i].checked=obj.checked; } } function subchk(obj){ //复选框监听 if(obj.checked==false){ document.getElementById("parentChk").checked=false; }else{ var boo = true; var allChildChks = document.getElementsByName("childChk"); for(var i=0;i<allChildChks.length;i++){ if(allChildChks[i].checked == false ){ boo=false; break; } } if(boo){ document.getElementById("parentChk").checked=true; } } } function _del(){ var ids =""; var oTable = document.getElementById("tb"); var allChildChks = document.getElementsByName("childChk"); for(var i=0;i<allChildChks.length;i++){ if(allChildChks[i].checked==true){ var id = oTable.rows[i+1].cells[4].innerHTML; if(ids==""){ ids=id; }else{ ids+=","+id; } } } //alert(ids); if(ids==""){ alert("请选择要删除的行!"); }else{ document.getElementById("ids").value=ids; document.forms["form"].submit(); } } //这里因为每个用户只能操坐自己的联系人。因此,当前用户操作时,没有其他用户对这些联系人进行增删改操作。 //如果要想多用户能够同时对同一集合联系人进行增删改查,那么每个增删改查的动作必须 //实时利用ajax向后台查询(在后台把结果放入list中,然后在前台利用<forEach>显示) function realdel(boo){ if(!boo){ alert("很遗憾,删除失败了!"); return; } var oTable = document.getElementById("tb"); var allChildChks = document.getElementsByName("childChk"); //因为allChiledChks的长度是随着删除而变短的,所以要用后面先删除、当然,可以从前面删除,不过要防范一下 for(var i=allChildChks.length-1;i>=0;i--){ if(allChildChks[i].checked == true){ var oTr = oTable.rows[i+1]; oTr.parentNode.removeChild(oTr); } } //对全选框设置为不打勾 document.getElementById("parentChk").checked=false; } function _query(){ var url = path+"jsps/query.jsp"; var result = window.showModalDialog(url,"","dialogWidth:650px;dialogHeight:400px;"); if(result==null){ return; } realadd(result); }
添加联系人和查询联系人页面:
总的来说,无论是设计模式,还是框架,其实都需要我们多去做做项目,自己多练习,只看书是远远不够的,需要自己动手才知道不足之处!
大家一起进步吧,O(∩_∩)O哈哈~