/*java
public class Servlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Login login = new service.impl.Login(); String username =request.getParameter("username"); String password = request.getParameter("password"); String code = request.getParameter("code"); Object checkcode1 = request.getSession().getAttribute("checkcode"); String checkcode = (String) checkcode1; request.getSession().removeAttribute("checkcode"); if (checkcode!=null&&code.equalsIgnoreCase(checkcode)){ User u=new User(); u.setUsername(username); u.setPassword(password); User user = login.Login(u); if (user!=null){ request.getSession().setAttribute("username",username) request.getRequestDispatcher("Success.jsp").forward(request,response); }else{ request.getSession().setAttribute("userfail","用戶名或密碼錯誤"); request.getRequestDispatcher("index.jsp").forward(request,response); } }else{ request.getSession().setAttribute("codefail","驗證碼錯誤"); request.getRequestDispatcher("index.jsp").forward(request,response); } }
public class CheckcodeServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //定義驗證碼框的長寬 int width = 100; int height = 50; //建立image對象 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //建立畫筆對象 Graphics graphics = image.getGraphics(); //設置畫筆顏色 graphics.setColor(Color.white); //填充背景 graphics.fillRect(0, 0, width, height); //從新設定畫筆顏色 graphics.setColor(Color.BLUE); //畫驗證碼的邊框 graphics.drawRect(0, 0, width - 1, height - 1); //將驗證碼所要顯示的內容組成字符串 String s = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890"; //建立隨機數對象 Random random = new Random(); //建立顏色數組 Color[] colors = {Color.red, Color.BLACK, Color.magenta, Color.YELLOW, Color.GREEN}; //建立builder對象用於組合驗證碼 StringBuilder builder = new StringBuilder(); //for循環畫驗證碼 for (int i = 1; i <= 4; i++) { //每一個字母換一個顏色 graphics.setColor(colors[new Random().nextInt(colors.length)]); //隨機生成字符串下標 int index = random.nextInt(s.length()); //經過字符串下標拿到字符 char c = s.charAt(index); //組合字符串 builder.append(c); //設置驗證碼的字體 graphics.setFont(new Font("Comic Sans MS", Font.BOLD, 20)); //驗證碼所要擺放的位置 graphics.drawString(c + "", width / 5 * i, height / 2); } //將驗證碼轉爲String類型 String s1 = builder.toString(); //存放在session中 request.getSession().setAttribute("checkcode", s1); //for循環畫干擾線 for (int i = 0; i < 30; i++) { //設置干擾線顏色 graphics.setColor(colors[new Random().nextInt(colors.length)]); //設置干擾線座標 int x = random.nextInt(width); int y = random.nextInt(height); int x1 = random.nextInt(30); int y1 = random.nextInt(30); int sin = random.nextBoolean() ? 1 : -1; int cos = random.nextBoolean() ? 1 : -1; graphics.drawLine(x, y, x + x1 * sin, y + y1 * cos); } //輸出驗證碼框 ImageIO.write(image, "jpg", response.getOutputStream()); }