网站建设资讯

NEWS

网站建设资讯

Javaweb如何实现一个验证码权限登录功能

今天就跟大家聊聊有关Java web如何实现一个验证码权限登录功能,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

成都创新互联公司2013年至今,先为张北等服务建站,张北等地企业,进行企业商务咨询服务。为张北企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。

所用到的开发工具为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"?>

 web04
 
 login.jsp
  main.jsp
 
 
  LoginServlet
  com.ningmeng.web.LoginServlet
 
 
 输出验证码
 This is the display name of my J2EE component
 PictureCheckCode
 com.servlet.PictureCheckCode
 
 
  LoginServlet
  /login
 
 
 PictureCheckCode
 /PictureCheckCode
 

login.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>




Insert title here



登录界面
账号:
密码:
验证码: 看不清,换一个
类型: 一般研究人员 管理员研究人员
${error}

main.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>




Insert title here


登录成功

当前用户:${currentUser.username}
当前密码:${currentUser.password}

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+"/";
%>


 
 
 My JSP 'linmao.jsp' starting page
 
 
  
 
 
 
 
 
 This is my JSP page. 

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

Java web如何实现一个验证码权限登录功能 

看完上述内容,你们对Java web如何实现一个验证码权限登录功能有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注创新互联行业资讯频道,感谢大家的支持。


当前文章:Javaweb如何实现一个验证码权限登录功能
文章地址:http://cdweb.net/article/pojeps.html