欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java web含验证码及权限登录实例代码

程序员文章站 2024-03-03 23:15:22
所用到的开发工具为myeclipse10,mysql数据库。 首先,在myeclipse中新建一个java web项目。 项目的结构:   数据库结构:...

所用到的开发工具为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 'linmao.jsp' 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含验证码及权限登录实例代码,希望对大家有所帮助