首页 >Java >java教程 >Java web含验证码及权限登录的实例代码详解(图)

Java web含验证码及权限登录的实例代码详解(图)

黄舟
黄舟原创
2017-03-31 10:53:464827浏览

这篇文章主要介绍了Java web含验证码及权限登录实例代码,所用到的开发工具为myeclipse10,MySQL数据库,具体实现代码大家参考下本文吧

所用到的开发工具为myeclipse10,MySQL数据库。

首先,在myeclipse中新建一个Java web项目。

项目的结构:

Java web含验证码及权限登录的实例代码详解(图) 

数据库结构:

Java web含验证码及权限登录的实例代码详解(图)Java web含验证码及权限登录的实例代码详解(图) 

下面将各个包中的代码粘贴出来。

com.ningmeng.dao包

package com.ningmeng.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.ningmeng.model.User;
public class UserDao {
 public User login(Connection con,User user) throws SQLException{
  User resultUser=null;
  String sql="select * from user where username=? and password=?";
  PreparedStatement ps=con.prepareStatement(sql);//
  ps.setString(1, user.getUsername());
  ps.setString(2, user.getPassword());
  ResultSet rs=ps.executeQuery();
  if(rs.next()){
   resultUser=new User();
   resultUser.setUsername(rs.getString("username"));
   resultUser.setPassword(rs.getString("password"));
  }
  return resultUser;
 }
}

com.ningmeng.model包

package com.ningmeng.model;
public class User {
 private int id;
 private String username;
 private String password;
 public User() {
  super();
 }
 public User(String username, String password) {
  super();
  this.username = username;
  this.password = password;
 }
 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 getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
}

com.ningmeng.util包

package com.ningmeng.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
 public class DbUtil {
 private String url="jdbc:mysql://localhost:3306/db-jsp";
 private String user="root";
 private String password="123";
 private String driver="com.mysql.jdbc.Driver";
 public Connection getCon() throws Exception{
     Class.forName(driver);
    Connection con=DriverManager.getConnection(url, user, password);
    return con;
 }
 public static void getClose(Connection con) throws SQLException{
  if(con!=null){
   con.close();
  }
 }
 /*public static void main(String[] args) {
  DbUtil db=new DbUtil();
  try {
   db.getCon();
   System.out.println("测试连接数据库,连接成功");
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   System.out.println("测试连接数据库,连接失败");
  }
 }*/
}

com.ningmeng.web包

package com.ningmeng.web;
import java.io.IOException;
import java.sql.Connection;
import java.io.*;
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 javax.servlet.http.*;
import com.ningmeng.dao.UserDao;
import com.ningmeng.model.User;
import com.ningmeng.util.DbUtil;
public class LoginServlet extends HttpServlet{
 DbUtil db=new DbUtil();
 UserDao userDao=new UserDao();
 /**
  * 
  */
 private static final long serialVersionUID = 1L;
 @Override
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  this.doPost(request, response);
 }
 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  String username=request.getParameter("username");
  String password=request.getParameter("password");
  String checkcode=request.getParameter("checkCode");
  HttpSession session=request.getSession();
  //session.getAttribute("randCheckCode");
  String s = (String)session.getAttribute("randCheckCode");
  if(!checkcode.equals(s))
  {
   response.sendRedirect("linmao.jsp");
  }else{
   if(request.getParameter("ra").equals("l")){
  Connection con=null;
  try {
   User user=new User(username,password);
   con=db.getCon();
   User currentUser=userDao.login(con, user);
   if(currentUser==null){
    //System.out.println("no");
    request.setAttribute("error", "用户名或者密码错误");
    request.setAttribute("username", username);
    request.setAttribute("password", password);
    request.getRequestDispatcher("login.jsp").forward(request, response);
   }else{
    //System.out.println("yes");
    HttpSession session1=request.getSession();
    session1.setAttribute("currentUser",currentUser);
    response.sendRedirect("main.jsp");
   }
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   }
  }
   else{
    response.sendRedirect("linmao.jsp");
   }
  }
 }
 }

com.servlet包

package com.servlet;
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;
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 javax.imageio.ImageIO;
public class PictureCheckCode extends HttpServlet {
 private static final long serialVersionUID = 1L;
 public PictureCheckCode() {
  super();
 }
 public void destroy() {
  super.destroy(); 
 }
 public void init() throws ServletException {
  super.init();
 }
 /*该方法主要作用是获得随机生成的颜色*/ 
 public Color getRandColor(int s,int e){
  Random random=new Random ();
  if(s>255) s=255;
  if(e>255) e=255;
  int r,g,b;
  r=s+random.nextInt(e-s); //随机生成RGB颜色中的r值
  g=s+random.nextInt(e-s); //随机生成RGB颜色中的g值
  b=s+random.nextInt(e-s); //随机生成RGB颜色中的b值
  return new Color(r,g,b);
 }
 @Override
 public void service(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //设置不缓存图片
  response.setHeader("Pragma", "No-cache");
  response.setHeader("Cache-Control", "No-cache");
  response.setDateHeader("Expires", 0);
  //指定生成的响应图片,一定不能缺少这句话,否则错误.
  response.setContentType("image/jpeg");
  int width=86,height=33;  //指定生成验证码的宽度和高度
  BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //创建BufferedImage对象,其作用相当于一图片
  Graphics g=image.getGraphics();  //创建Graphics对象,其作用相当于画笔
  Graphics2D g2d=(Graphics2D)g;  //创建Grapchics2D对象
  Random random=new Random();
  Font mfont=new Font("楷体",Font.BOLD,20); //定义字体样式
  g.setColor(getRandColor(200,250));
  g.fillRect(0, 0, width, height); //绘制背景
  g.setFont(mfont);     //设置字体
  g.setColor(getRandColor(180,200));
  //绘制100条颜色和位置全部为随机产生的线条,该线条为2f
  for(int i=0;i<100;i++){
   int x=random.nextInt(width-1);
   int y=random.nextInt(height-1);
   int x1=random.nextInt(6)+1;
   int y1=random.nextInt(12)+1;
   BasicStroke bs=new BasicStroke(2f,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL); //定制线条样式
   Line2D line=new Line2D.Double(x,y,x+x1,y+y1);
   g2d.setStroke(bs);
   g2d.draw(line);  //绘制直线
  }
  //输出由英文,数字,和中文随机组成的验证文字,具体的组合方式根据生成随机数确定。
  String sRand="";
  String ctmp="";
  int itmp=0;
  //制定输出的验证码为四位
  for(int i=0;i<4;i++){
   switch(random.nextInt(3)){
    case 1:  //生成A-Z的字母
      itmp=random.nextInt(26)+65;
      ctmp=String.valueOf((char)itmp);
      break;
    default:
      itmp=random.nextInt(10)+48;
      ctmp=String.valueOf((char)itmp);
      break;
   }
   sRand+=ctmp;
   Color color=new Color(20+random.nextInt(110),20+random.nextInt(110),random.nextInt(110));
   g.setColor(color);
   //将生成的随机数进行随机缩放并旋转制定角度 PS.建议不要对文字进行缩放与旋转,因为这样图片可能不正常显示
   /*将文字旋转制定角度*/
   Graphics2D g2d_word=(Graphics2D)g;
   AffineTransform trans=new AffineTransform();
   trans.rotate((45)*3.14/180,15*i+8,7);
   /*缩放文字*/
   float scaleSize=random.nextFloat()+0.8f;
   if(scaleSize>1f) scaleSize=1f;
   trans.scale(scaleSize, scaleSize);
   g2d_word.setTransform(trans);
   g.drawString(ctmp, 15*i+18, 14);
  }
  HttpSession session=request.getSession(true);
  session.setAttribute("randCheckCode", sRand);
  g.dispose(); //释放g所占用的系统资源
  ImageIO.write(image,"JPEG",response.getOutputStream()); //输出图片
 }
}

配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 <display-name>web04</display-name>
 <welcome-file-list>
 <welcome-file>login.jsp</welcome-file>
  <welcome-file>main.jsp</welcome-file>
 </welcome-file-list>
 <servlet>
  <servlet-name>LoginServlet</servlet-name>
  <servlet-class>com.ningmeng.web.LoginServlet</servlet-class>
 </servlet>
 <servlet>
 <description>输出验证码</description>
 <display-name>This is the display name of my J2EE component</display-name>
 <servlet-name>PictureCheckCode</servlet-name>
 <servlet-class>com.servlet.PictureCheckCode</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>LoginServlet</servlet-name>
  <url-pattern>/login</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
 <servlet-name>PictureCheckCode</servlet-name>
 <url-pattern>/PictureCheckCode</url-pattern>
 </servlet-mapping>
</web-app>

login.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script language="javascript">
function myReload() {
 document.getElementById("CreateCheckCode").src = document
   .getElementById("CreateCheckCode").src
   + "?nocache=" + new Date().getTime();
}
</script>
</head>
<body>
<form action="login" method="post">
 <table>
  <tr>
   <th colspan="2">登录界面</th>
  </tr>
  <tr>
   <td>账号:</td>
   <td><input type="text" id="username" name="username" value="${username}"></td>
  </tr>
  <tr>
   <td>密码:</td>
   <td><input type="password" id="password" name="password" value="${password}"></td>
  </tr>
  <tr>
   <td>验证码:</td>
   <td><input name="checkCode" type="text" id="checkCode" title="验证码区分大小写"
    size="8" ,maxlength="4" />
   <img src="PictureCheckCode" id="CreateCheckCode" align="middle">
   <a href="" onclick=" rel="external nofollow" myReload()"> 看不清,换一个</a>
  </tr>
  <tr>
   <td>类型:</td>
   <td>
   <input type="radio" name="ra" value="l" checked="checked"/>一般研究人员
   <input type="radio" name="ra" value="m" />管理员研究人员
   </td>
  </tr>
  <tr>
   <td>
   <input type="submit" value="提交">
   <font color="red">${error}</font>
   </td>
  </tr>
 </table>
</form>
</body>
</html>

main.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>登录成功</p>
当前用户:${currentUser.username}<br/>
当前密码:${currentUser.password}<br/>
</body>
</html>

linmao.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
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%>" rel="external nofollow" >
 <title>My JSP &#39;linmao.jsp&#39; 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" rel="external nofollow" >
 -->
 </head>
 <body>
 This is my JSP page. <br>
 </body>
</html>

项目现在做到验证码和权限这一块,找回密码功能还没有做完,结构中Check.jsp还用不到。还有连接数据库的操作,就不详细叙述了。

Java web含验证码及权限登录的实例代码详解(图) 

账号和密码在数据库的表中

以上是Java web含验证码及权限登录的实例代码详解(图)的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn