本文目錄一覽:
- 1、java 登陸時的驗證碼怎麼做?
- 2、java登陸界面驗證
- 3、java登錄模塊驗證出現問題求解答
- 4、Java (for循環)編程 實現用戶登錄時的信息驗證
- 5、java 如何實現同一賬戶登錄驗證
- 6、JAva登錄驗證窗口
java 登陸時的驗證碼怎麼做?
後台寫一個生成圖片隨機的代碼,生成圖片給前台。切換圖片的時候,使用ajax獲取圖片數據就行。
附上生成圖片的代碼
public class ValidateCode {
private int width=180;
private int height=60;
private int codeCount = 4;
private int x = 0;
private int codeY;
private String Code;
private BufferedImage buffImg;
static char[] codeSequence = { ‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’, ‘H’, ‘I’, ‘J’,
‘K’, ‘L’, ‘M’, ‘N’, ‘O’, ‘P’, ‘Q’, ‘R’, ‘S’, ‘T’, ‘U’, ‘V’, ‘W’,
‘X’, ‘Y’, ‘Z’,’a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’,
‘k’, ‘l’, ‘m’, ‘n’, ‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’,
‘x’, ‘y’, ‘z’, ‘o’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’ };
private int fontHeight;
public ValidateCode() {
x = width / (codeCount + 2);
fontHeight = height – 2;
codeY = height – 4;
CreateCode();
}
public void CreateCode(){
// 定義圖像buffer
BufferedImage buffImg = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
// 創建一個隨機數生成器類
Random random = new Random();
// 將圖像填充為白色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 創建字體,字體的大小應該根據圖片的高度來定。
Font font = new Font(“Fixedsys”, Font.PLAIN, fontHeight);
// 設置字體。
g.setFont(font);
// 畫邊框。
g.setColor(Color.BLACK);
g.drawRect(0, 0, width – 1, height – 1);
// randomCode用於保存隨機產生的驗證碼,以便用戶登錄後進行驗證。
StringBuffer randomCode = new StringBuffer();
int red = 0, green = 0, blue = 0;
// 隨機產生codeCount數字的驗證碼。
for (int i = 0; i codeCount; i++) {
// 得到隨機產生的驗證碼數字。
String strRand = String.valueOf(codeSequence[random.nextInt(62)]);
// 產生隨機的顏色分量來構造顏色值,這樣輸出的每位數字的顏色值都將不同。
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
// 用隨機產生的顏色將驗證碼繪製到圖像中。
g.setColor(new Color(red, green, blue));
g.drawString(strRand, (i ) * x+20, codeY);
// 將產生的四個隨機數組合在一起。
randomCode.append(strRand);
}
this.Code=randomCode.toString().toUpperCase();
this.buffImg=buffImg;
}
public String getCode() {
return Code;
}
public void setCode(String code) {
Code = code;
}
public BufferedImage getBuffImg() {
return buffImg;
}
public void setBuffImg(BufferedImage buffImg) {
this.buffImg = buffImg;
}
}
java登陸界面驗證
以下代碼就是了。
詳細參照附件
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class LoginJFrame extends JFrame implements ActionListener {
private JTextField text_username;
private JPasswordField password_pwd;
private JButton button_lg, button_close;
private JLabel msgArea;
public LoginJFrame() {
super(“登錄”);
this.setBounds(500, 240, 320, 260);
setResizable(false);
setBackground(java.awt.Color.lightGray);
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().setLayout(new GridLayout(4, 1, 20, 10));
getContentPane().add(new JLabel(“在線考試系統用戶登錄”, JLabel.CENTER));
JPanel panel_1 = new JPanel(new GridLayout(2, 2, 0, 5));
getContentPane().add(panel_1);
panel_1.add(new JLabel(“用戶名:”, JLabel.CENTER));
text_username = new JTextField(20);
panel_1.add(text_username);
panel_1.add(new JLabel(“密 碼:”, JLabel.CENTER));
password_pwd = new JPasswordField(20);
panel_1.add(password_pwd);
JPanel panel_2 = new JPanel(new GridLayout(1, 2, 30, 0));
getContentPane().add(panel_2);
button_lg = new JButton(“登陸”);
panel_2.add(button_lg);
button_lg.addActionListener(this);
button_close = new JButton(“註冊”);
panel_2.add(button_close);
setVisible(true);
// 添加一個控制項用於顯示提示信息
JPanel panel_3 = new JPanel();
msgArea = new JLabel();
getContentPane().add(panel_3.add(msgArea));
setVisible(true);
}
public static void main(String arg[]) {
new LoginJFrame();
}
public void actionPerformed(ActionEvent e) {
// 登錄按鈕
if (e.getSource() == button_lg) {
if (text_username.getText().isEmpty() password_pwd.getText().isEmpty()) {
msgArea.setText(“請輸入用戶名和密碼!”);
return;
}
if (text_username.getText().isEmpty()) {
msgArea.setText(“用戶名不能為空!”);
return;
}
if (password_pwd.getText().isEmpty()) {
msgArea.setText(“密碼不能為空!”);
return;
}
// TODO 連接資料庫驗證用戶
}
}
}
java登錄模塊驗證出現問題求解答
前期準備
首先要先明確有個大體的思路,要實現什麼樣的功能,了解完成整個模塊要運用到哪些方面的知識,以及從做的過程中去發現自己的不足。技術方面的進步大都都需要從實踐中出來的。
功能:用戶註冊功能+系統登錄功能+生成驗證碼
知識:窗體設計、資料庫設計、JavaBean封裝屬性、JDBC實現對資料庫的連接、驗證碼(包括彩色驗證碼)生成技術,還有就些比如像使用正則表達式校驗用戶註冊信息、隨機獲得字元串、對文本可用字元數的控制等
設計的模塊預覽圖:
彩色驗證碼預覽圖:
所用資料庫:MySQL
資料庫設計
創建一個資料庫db_database01,其中包含一個表格tb_user,用來保存用戶的註冊的數據。
其中包含4個欄位
id int(11)
username varchar(15)
password varchar(20)
email varchar(45)
MySQL語句可以這樣設計:
create schema db_database01;
use db_database01;
create table tb_user(
id int(11) not null auto_increment primary key,
username varchar(15) not null,
password varchar(20) not null,
email varchar(45) not null
);
insert into tb_user values(1,”lixiyu”,”lixiyu”,lixiyu419@gmail.com);
這樣把lixiyu作為用戶名。
select語句檢查一下所建立的表格:
編寫JavaBean封裝用戶屬性
package com.lixiyu.model;
public class User {
private int id;// 編號
private String username;// 用戶名
private String password;// 密碼
private String email;// 電子郵箱
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;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
編寫JDBC工具類
將與資料庫操作相關的代碼放置在DBConfig介面和DBHelper類中
DBConfig介面用於保存資料庫、用戶名和密碼信息
代碼:
package com.lixiyu.util;
public interface DBConfig {
String databaseName = “db_database01”;// 資料庫名稱
String username = “root”;// 資料庫用戶名
String password = “lixiyu”;// 資料庫密碼
}
為簡化JDBC開發,DBHelper使用了了Commons DbUtil組合。
DBHelper類繼承了DBConfig介面,該類中包含4種方法:
(1)getConnection()方法:獲得資料庫連接,使用MySQL數據源來簡化編程,避免因載入資料庫驅動而發生異常。
(2)exists()方法:判斷輸入的用戶名是否存在。
(3)check()方法:當用戶輸入用戶名和密碼,查詢使用check()方法是否正確。
(4)save()方法:用戶輸入合法註冊信息後,,將信息進行保存。
詳細代碼:
package com.lixiyu.util;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.apache.commons.lang.StringEscapeUtils;
import com.lixiyu.model.User;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
public class DBHelper implements DBConfig {
/*
* 使用MySQL數據源獲得資料庫連接對象
*
* @return:MySQL連接對象,如果獲得失敗返回null
*/
public static Connection getConnection() {
MysqlDataSource mds = new MysqlDataSource();// 創建MySQL數據源
mds.setDatabaseName(databaseName);// 設置資料庫名稱
mds.setUser(username);// 設置資料庫用戶名
mds.setPassword(password);// 設置資料庫密碼
try {
return mds.getConnection();// 獲得連接
} catch (SQLException e) {
e.printStackTrace();
}
return null;// 如果獲取失敗就返回null
}
/*
* 判斷指定用戶名的用戶是否存在
*
* @return:如果存在返回true,不存在或者查詢失敗返回false
*/
public static boolean exists(String username) {
QueryRunner runner = new QueryRunner();// 創建QueryRunner對象
String sql = “select id from tb_user where username = ‘” + username + “‘;”;// 定義查詢語句
Connection conn = getConnection();// 獲得連接
ResultSetHandlerListObject rsh = new ColumnListHandler();// 創建結果集處理類
try {
ListObject result = runner.query(conn, sql, rsh);// 獲得查詢結果
if (result.size() 0) {// 如果列表中存在數據
return true;// 返回true
} else {// 如果列表中沒有數據
return false;// 返回false
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);// 關閉連接
}
return false;// 如果發生異常返回false
}
/*
* 驗證用戶名和密碼是否正確 使用Commons Lang組件轉義字元串避免SQL注入
*
* @return:如果正確返回true,錯誤返回false
*/
public static boolean check(String username, char[] password) {
username = StringEscapeUtils.escapeSql(username);// 將用戶輸入的用戶名轉義
QueryRunner runner = new QueryRunner();// 創建QueryRunner對象
String sql = “select password from tb_user where username = ‘” + username + “‘;”;// 定義查詢語句
Connection conn = getConnection();// 獲得連接
ResultSetHandlerObject rsh = new ScalarHandler();// 創建結果集處理類
try {
String result = (String) runner.query(conn, sql, rsh);// 獲得查詢結果
char[] queryPassword = result.toCharArray();// 將查詢到得密碼轉換成字元數組
if (Arrays.equals(password, queryPassword)) {// 如果密碼相同則返回true
Arrays.fill(password, ‘0’);// 清空傳入的密碼
Arrays.fill(queryPassword, ‘0’);// 清空查詢的密碼
return true;
} else {// 如果密碼不同則返回false
Arrays.fill(password, ‘0’);// 清空傳入的密碼
Arrays.fill(queryPassword, ‘0’);// 清空查詢的密碼
return false;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);// 關閉連接
}
return false;// 如果發生異常返回false
}
/*
* 保存用戶輸入的註冊信息
*
* @return:如果保存成功返回true,保存失敗返回false
*/
public static boolean save(User user) {
QueryRunner runner = new QueryRunner();// 創建QueryRunner對象
String sql = “insert into tb_user (username, password, email) values (?, ?, ?);”;// 定義查詢語句
Connection conn = getConnection();// 獲得連接
Object[] params = { user.getUsername(), user.getPassword(), user.getEmail() };// 獲得傳遞的參數
try {
int result = runner.update(conn, sql, params);// 保存用戶
if (result 0) {// 如果保存成功返回true
return true;
} else {// 如果保存失敗返回false
return false;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);// 關閉連接
}
return false;// 如果發生異常返回false
}
}
系統登錄
1.1窗體設計
使用BoxLayout布局,將控制項排列方式設置從上至下:
複製代碼代碼如下:
contentPane.setLayout(new BoxLayout(contentPane,BoxLayout.PAGE_AXIS));
窗體使用了標籤、文本域、密碼域和按鈕等控制項
實現代碼:
public class login extends JFrame{
private static final long serialVersionUID = -4655235896173916415L;
private JPanel contentPane;
private JTextField usernameTextField;
private JPasswordField passwordField;
private JTextField validateTextField;
private String randomText;
public static void main(String args[]){
try {
UIManager.setLookAndFeel(“com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel”);
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable(){
public void run(){
try{
login frame=new login();
frame.setVisible(true);
}catch(Exception e){
e.printStackTrace();
}
}
});
}
public login(){
setTitle(“系統登錄”);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane=new JPanel();
setContentPane(contentPane);
contentPane.setLayout(new BoxLayout(contentPane,BoxLayout.PAGE_AXIS));
JPanel usernamePanel=new JPanel();
contentPane.add(usernamePanel);
JLabel usernameLable=new JLabel(“\u7528\u6237\u540D\uFF1A”);
usernameLable.setFont(new Font(“微軟雅黑”, Font.PLAIN, 15));
usernamePanel.add(usernameLable);
usernameTextField=new JTextField();
usernameTextField.setFont(new Font(“微軟雅黑”, Font.PLAIN, 15));
usernamePanel.add(usernameTextField);
usernameTextField.setColumns(10);
JPanel passwordPanel = new JPanel();
contentPane.add(passwordPanel);
JLabel passwordLabel = new JLabel(“\u5BC6 \u7801\uFF1A”);
passwordLabel.setFont(new Font(“微軟雅黑”, Font.PLAIN, 15));
passwordPanel.add(passwordLabel);
passwordField = new JPasswordField();
passwordField.setColumns(10);
passwordField.setFont(new Font(“微軟雅黑”, Font.PLAIN, 15));
passwordPanel.add(passwordField);
JPanel validatePanel = new JPanel();
contentPane.add(validatePanel);
JLabel validateLabel = new JLabel(“\u9A8C\u8BC1\u7801\uFF1A”);
validateLabel.setFont(new Font(“微軟雅黑”, Font.PLAIN, 15));
validatePanel.add(validateLabel);
validateTextField = new JTextField();
validateTextField.setFont(new Font(“微軟雅黑”, Font.PLAIN, 15));
validatePanel.add(validateTextField);
validateTextField.setColumns(5);
randomText = RandomStringUtils.randomAlphanumeric(4);
CAPTCHALabel label = new CAPTCHALabel(randomText);//隨機驗證碼
label.setFont(new Font(“微軟雅黑”, Font.PLAIN, 15));
validatePanel.add(label);
JPanel buttonPanel=new JPanel();
contentPane.add(buttonPanel);
JButton submitButton=new JButton(“登錄”);
submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
do_submitButton_actionPerformed(e);
}
});
submitButton.setFont(new Font(“微軟雅黑”, Font.PLAIN, 15));
buttonPanel.add(submitButton);
JButton cancelButton=new JButton(“退出”);
cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
do_cancelButton_actionPerformed(e);
}
});
cancelButton.setFont(new Font(“微軟雅黑”,Font.PLAIN,15));
buttonPanel.add(cancelButton);
pack();// 自動調整窗體大小
setLocation(com.lixiyu.util.SwingUtil.centreContainer(getSize()));// 讓窗體居中顯示
}
窗體居中顯示:
public class SwingUtil {
/*
* 根據容器的大小,計算居中顯示時左上角坐標
*
* @return 容器左上角坐標
*/
public static Point centreContainer(Dimension size) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();// 獲得屏幕大小
int x = (screenSize.width – size.width) / 2;// 計算左上角的x坐標
int y = (screenSize.height – size.height) / 2;// 計算左上角的y坐標
return new Point(x, y);// 返回左上角坐標
}
}
1.2獲取及繪製驗證碼
public class CAPTCHALabel extends JLabel {
private static final long serialVersionUID = -963570191302793615L;
private String text;// 用於保存生成驗證圖片的字元串
public CAPTCHALabel(String text) {
this.text = text;
setPreferredSize(new Dimension(60, 36));// 設置標籤的大小
}
@Override
public void paint(Graphics g) {
super.paint(g);// 調用父類的構造方法
g.setFont(new Font(“微軟雅黑”, Font.PLAIN, 16));// 設置字體
g.drawString(text, 5, 25);// 繪製字元串
}
}
*彩色驗證碼:
public class ColorfulCAPTCHALabel extends JLabel {
private static final long serialVersionUID = -963570191302793615L;
private String text;// 用於保存生成驗證圖片的字元串
private Color[] colors = { Color.BLACK, Color.BLUE, Color.CYAN, Color.DARK_GRAY, Color.GRAY, Color.GREEN, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
Color.PINK, Color.RED, Color.WHITE, Color.YELLOW };// 定義畫筆顏色數組
public ColorfulCAPTCHALabel(String text) {
this.text = text;
setPreferredSize(new Dimension(60, 36));// 設置標籤的大小
}
@Override
public void paint(Graphics g) {
super.paint(g);// 調用父類的構造方法
g.setFont(new Font(“微軟雅黑”, Font.PLAIN, 16));// 設置字體
for (int i = 0; i text.length(); i++) {
g.setColor(colors[RandomUtils.nextInt(colors.length)]);
g.drawString(“” + text.charAt(i), 5 + i * 13, 25);// 繪製字元串
}
}
}
1
Java (for循環)編程 實現用戶登錄時的信息驗證
import java.util.*;
public class PswVerify { /**
* @param args
*/
public static void main(String[] args) {
// TODO 自動生成方法存根
Scanner input =new Scanner(System.in);
String username =”manage”;
int password = 0000;
for(int i =3;i=1;i–)
{
System.out.println(“請輸入用戶名:”);
String name =input.next();
System.out.println(“請輸入密碼:”);
int pw =input.nextInt();
if(name.equals(username)pw==password)
{
System.out.println(“歡迎進入我行我素購物管理系統”);
break;
}
else if(i!=1)
{
System.out.println(“用戶名和密碼不匹配!”);
System.out.println(“你還有”+(i-1)+”次機會,請重新輸入:”);
}
else
{
System.out.println(“您沒有許可權進入系統!”);
} }}
}
java 如何實現同一賬戶登錄驗證
今天繼續討論?-0-#這個只需要session和application就好了,用戶登錄時,這樣寫:User
user
=
dao.login(userName,
password);//
資料庫中判斷用戶名和密碼if
(null
!=
user)
{//
表示用戶存在
session.setAttribute(“user”,
user);//
把用戶放進session中
application.setAttribute(userName,
session.getId());/*
把用戶所在的sessionId放進application中,首先要明白一點,一個session對應一個瀏覽器,其次要注意一點,userName必須是唯一的*/}當用戶訪問到其他url的時候,可以在過濾器或你的攔截器中這樣寫:User
user
=
(User)
session.getAttribute(“user”);//
從session中取出用戶if
(null
==
user)
{//
未登錄或者登錄已經過期
response.sendRedirect(request.getContextPath());//
跳轉到首頁或登錄頁面}String
sessionId
=
(String)
application.getAttribute(user.getUserName());if
(null
==
sessionId
||
!sessionId.equals(session.getId()))
{/*這說明用戶已經在其他電腦或其它瀏覽器登錄了,那麼之前登錄的session就無效了,自動被後面的登錄給踢掉*/
response.sendRedirect(request.getContextPath());//
跳轉到首頁或登錄頁面}chain.doFilter(request,
response);//
通過驗證,放行用戶進入目標url這種方式是我的一個前輩想到的,我們公司的所有項目都採納了這種方式,確保一個賬號只能在一個瀏覽器中使用
JAva登錄驗證窗口
我幫你改了一下,你那個登錄和重置按鈕的監聽器里的代碼書上估計是省略了,運行效果:
代碼在這裡:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
public class UserLogIn extends JFrame{
public JPanel pnluser;
public JLabel lbl用戶登錄,lbl用戶名,lbl密碼;
public JTextField txt用戶名;
public JPasswordField pwd密碼;
public JButton btn登錄,btn重置;
String dburl=”jdbc:odbc:driver={Microsoft Access Driver(*.mdb,*.accdb)};DBQ=D://stdub.mdb”;
Connection conn=null;
Statement stmt=null;
int 查詢記錄=0;
public static void main(String[] args){
new TestClass();
}
public UserLogIn(){
pnluser=new JPanel();
lbl用戶登錄=new JLabel();
lbl用戶名=new JLabel();
lbl密碼=new JLabel();
txt用戶名=new JTextField();
pwd密碼=new JPasswordField();
btn登錄=new JButton();
btn重置=new JButton();
userInit();
}
public void userInit(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400,300);
this.setResizable(false);
this.setTitle(“登錄”);
this.pnluser.setLayout(null);
this.pnluser.setBackground(Color.white);
this.lbl用戶登錄.setText(“用戶登錄”);
this.lbl用戶登錄.setFont(new Font(“宋體”,Font.BOLD,18));
this.lbl用戶登錄.setForeground(Color.blue);
this.lbl用戶名.setText(“用戶名”);
this.lbl用戶名.setText(“密碼”);
this.lbl用戶名.setText(“登錄”);
this.lbl用戶名.setText(“重置”);
this.lbl用戶登錄.setBounds(160,15,80,30);
this.lbl用戶名.setBounds(90,70,80,30);
this.lbl密碼.setBounds(90,120,80,30);
this.txt用戶名.setBounds(160,70,150,30);
this.pwd密碼.setBounds(160,120,150,30);
this.btn登錄.setBounds(100,200,80,30);
this.btn登錄.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e){
//這裡寫按登錄按鈕後執行的代碼,書上估計是省略了。
System.out.println(“登錄”);
}
}
);
this.btn重置.setBounds(220,200,80,30);
this.btn重置.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){
//這裡寫按重置按鈕後執行的代碼,書上估計是省略了。
System.out.println(“重置”);
}
}
);
this.pnluser.add(lbl用戶登錄);
this.pnluser.add(lbl用戶名);
this.pnluser.add(lbl密碼);
this.pnluser.add(txt用戶名);
this.pnluser.add(pwd密碼);
this.pnluser.add(btn登錄);
this.pnluser.add(btn重置);
this.add(pnluser);
this.setVisible(true);
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/242165.html