首先给出显示页面:index.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> </head> <body> <h3>带有验证码的登录页面</h3> <form action="servlet/LogonFormServlet" method="post"> 用户名:<input type="text" name="name" ><br> 密 码:<input type="text" name="password"><br> 验证码:<input type="text" name="check_code"><br> <img src="servlet/CheckCodeServlet"><br> <input type="submit" value="登录"> </form> </body> </html>
效果就是显示用户名、密码、验证码,以及给出对应的输入框,不多说
然后给出验证码生成的servlet并且将随机生成的验证码保存到session中去。
package com.cjg.servlet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintWriter; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class CheckCodeServlet extends HttpServlet { private static int WIDTH=60; private static int HEIGHT=20; /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @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 doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //PrintWriter out = response.getWriter(); HttpSession session = request.getSession(); response.setContentType("image/jpeg");//设置返回信息编码格式 ServletOutputStream sos = response.getOutputStream();//获取输出流 //设置浏览器不缓存返回的图片 response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); //创建内存图像并获得其图形上下文 BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); //产生随机验证码 char[] rands=generateCheckCode(); //产生图像 drawBackground(g); drawRands(g,rands); g.dispose(); //将图像输出到客户端 ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(image, "JPEG", bos); byte[] buf = bos.toByteArray(); response.setContentLength(buf.length); sos.write(buf); bos.close(); sos.close(); session.setAttribute("check_code", new String(rands)); } //把随机产生的字符画成图片 private void drawRands(Graphics g, char[] rands) { g.setColor(Color.black); g.setFont(new Font(null,Font.ITALIC|Font.BOLD,18)); //在不同的高度上显示出验证码 g.drawString(rands[0]+"", 1, 17); g.drawString(rands[1]+"", 16, 15); g.drawString(rands[2]+"",31,18); g.drawString(rands[3]+"", 46, 16); System.out.println(rands); } //制作背景 private void drawBackground(Graphics g) { //制作背景 g.setColor(new Color(0xDCDCDC)); g.fillRect(0, 0, WIDTH, HEIGHT); //产生干扰点 num个 int num=120; for(int i=0;i<num;i++){ int x = (int )(Math.random()*WIDTH); int y = (int )(Math.random()*HEIGHT); int red = (int )(Math.random()*255); int green=(int )(Math.random()*255); int blue=(int)(Math.random()*255); g.setColor(new Color(red,green,blue)); g.drawOval(x, y, 1, 0); } } //生成随机验证码 private char[] generateCheckCode() { String chars="0123456789abcdefghijklmnopqrstuvwxyz"; char rands[]=new char[4]; for(int i=0;i<4;i++){ int rand=(int)(Math.random()*36); rands[i]=chars.charAt(rand); } return rands; } /** * 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 { response.setContentType("text/html"); PrintWriter out = response.getWriter(); } }
登录验证,这里由于没有进行相应的数据库开发,所以不对用户名和密码进行验证,仅仅演示验证码的验证。
package com.cjg.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class LogonFormServlet extends HttpServlet { /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @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 doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); } /** * 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 { response.setContentType("text/html"); PrintWriter out = response.getWriter(); } public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(false); if(session==null){ out.println("验证码生成失败,请刷新重试,session 错误"); return ; } //获取session中的验证码 String saveCode = (String)session.getAttribute("check_code"); if(saveCode==null){ out.println("验证码生成失败,请刷新重试"); return; } //获取requset中提交的验证码 String checkCode=request.getParameter("check_code"); System.out.println("输入的是:"+checkCode+"保存的验证码是:"+saveCode); if(!saveCode.equals(checkCode)){ out.println("验证码错误"); return; } session.removeAttribute("check_code"); out.println("登录成功"); } }
最后给出 声明servlet配置的web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" 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_3_0.xsd"> <servlet> <servlet-name>CheckCodeServlet</servlet-name> <servlet-class>com.cjg.servlet.CheckCodeServlet</servlet-class> </servlet> <servlet> <servlet-name>LogonFormServlet</servlet-name> <servlet-class>com.cjg.servlet.LogonFormServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CheckCodeServlet</servlet-name> <url-pattern>/servlet/CheckCodeServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>LogonFormServlet</servlet-name> <url-pattern>/servlet/LogonFormServlet</url-pattern> </servlet-mapping> </web-app>
小实例总结:
到现在我明白了servlet配置的含义:声明servlet,给出路径,给出映射。
这么说其实也不是很明白,但是,相信我,写几个servlet应用程序就可以理解了,
因为这几个配置都是死的,定式的。不难理解。你可以这么想,总比泰勒展开式简单
吧。fighting。
下次记的把代码不展开。不然太多了。
关于控制台:在调试的时候,有时候控制台没有日志显示出来,气得我想砸电脑,其实那是你的程序没有执行。
肯定是配置存在问题。
比如:from 的action 路径没有设置,或者是设置之后没有实现。(我就是这样错的)