awt+IO实现用户的登陆注册

案例:

 awt+IO实现用户的登陆注册
 |-- 界面
 |-- 登陆功能


import java.io.*;
public class User {
 //返回真,用户登陆成功
 public boolean login(String username,String password){
  //获取到用户名和密码,读取文本文件,查找匹配
  BufferedReader bfr = null;
  try{
   bfr = new BufferedReader(new FileReader("c:\\text.txt"));
   String line = null;
   while((line = bfr.readLine())!=null){
    //System.out.println(line);//shisong=123
    String[] s = line.split("=");
    if(username.equals(s[0])&&password.equals(s[1]))
     return true;
   }
  }catch(IOException e){
   System.out.println(e);
   throw new RuntimeException("读取文件失败");
  }finally{
   try{
    if(bfr!=null)
     bfr.close();
   }catch(IOException e){
    throw new RuntimeException("读取关闭失败");
   }
  }
  return false;
 }
 //检测用户名是否存在,存在返回真
 public boolean login(String username){
  //获取到用户名和密码,读取文本文件,查找匹配
  BufferedReader bfr = null;
  try{
   bfr = new BufferedReader(new FileReader("c:\\text.txt"));
   String line = null;
   while((line = bfr.readLine())!=null){
    //System.out.println(line);//shisong=123
    String[] s = line.split("=");
    if(username.equals(s[0]))
     return true;
   }
  }catch(IOException e){
   System.out.println(e);
   throw new RuntimeException("读取文件失败");
  }finally{
   try{
    if(bfr!=null)
     bfr.close();
   }catch(IOException e){
    throw new RuntimeException("读取关闭失败");
   }
  }
  return false;
 }
 
 //将用户名和密码,写入文件,进行永久性保存
 public void regedit(String username,String password){
  FileWriter fw = null;
  try{
   fw = new FileWriter("c:\\text.txt",true);
   String text = username+"="+password;
   fw.write(text+"\r\n");
   fw.flush();
  }catch(IOException e){
   System.out.println(e);
   throw new RuntimeException("文件写入失败");
  }finally{
   try{
    if(fw!=null)
     fw.close();
   }catch(IOException e){
    throw new RuntimeException("文件写入关闭失败");
   }
  }
 }
 //获取所有用户信息的方法
 public String allUserList(){
  StringBuilder sb = new StringBuilder();
  BufferedReader bfr = null;
  try{
   bfr = new BufferedReader(new FileReader("c:\\text.txt"));
   String line = null;
   while((line = bfr.readLine())!=null){
    sb.append(line+"\r\n");
   }
  }catch(IOException e){
   System.out.println(e);
   throw new RuntimeException("读取文件失败");
  }finally{
   try{
    if(bfr!=null)
     bfr.close();
   }catch(IOException e){
    throw new RuntimeException("文件读取关闭失败");
   }
  }
  return sb.toString();
 
}

import java.awt.*;
import java.awt.event.*;
public class FrameRegedit {
 public FrameRegedit(){
  init();
 }
 private Frame frm = null;
 private Label message = null,usernamelbl=null,passwordlbl=null,repasswordlbl=null;
 //文本框
 private TextField usernametf = null, passwordtf = null,repasswordtf = null;
 //3个按钮
 private Button  regeditbut =null, quitbut = null;
 
 private void init(){
  frm = new Frame("用户注册");
  frm.setBounds(300, 100, 500, 350);
  frm.setBackground(Color.gray);
  frm.setLayout(null);
  frm.setVisible(true);
  
  message = new Label("用户的登陆和注册");
  message.setBounds(150, 50, 100, 30);
  frm.add(message);
  
  usernamelbl = new Label("用户名");
  usernamelbl.setBounds(100, 100, 50, 30);
  frm.add(usernamelbl);
  
  usernametf = new TextField();
  usernametf.setBounds(160, 105, 150, 20);
  frm.add(usernametf);
  
  passwordlbl = new Label("密  码");
  passwordlbl.setBounds(100, 150, 50, 30);
  frm.add(passwordlbl);
  
  passwordtf = new TextField();
  passwordtf.setBounds(160, 150, 150, 20);
  frm.add(passwordtf);
  
  repasswordlbl = new Label("确认密码");
  repasswordlbl.setBounds(100, 200, 50, 30);
  frm.add(repasswordlbl);
  
  repasswordtf = new TextField();
  repasswordtf.setBounds(160, 200, 150, 20);
  frm.add(repasswordtf);
  
  regeditbut = new Button("确认注册");
  regeditbut.setBounds(200, 250, 80, 30);
  frm.add(regeditbut);
  myEvent();
 }
 private void myEvent(){
  regeditbut.addActionListener(new ActionListener() {
 
   public void actionPerformed(ActionEvent e) {
    //获取用户名密码,确认密码
    String username = usernametf.getText();
    String password = passwordtf.getText();
    String repassword = repasswordtf.getText();
    if("".equals(username)||"".equals(password)||"".equals(repassword))
     return;
    if(!(password.equals(repassword))){
     System.out.println("两次密码不一致");
     return;
    }
    //检测用户名是否存在
    boolean b = new User().login(username);
    if(b){
     System.out.println("用户名存在");
    }else{
     //调用IO中的功能,将用户名和密码写入文件保存
     new User().regedit(username, repassword);
     System.out.println("注册成功");
     frm.setVisible(false);
    }
   }
  });
 }
}

import java.awt.*;
import java.awt.event.*;
public class FrameLogin {
 public FrameLogin(){
  init();
 }
 //窗体
 private Frame frm = null;
 private Label message = null,usernamelbl=null,passwordlbl=null;
 //文本框
 private TextField usernametf = null, passwordtf = null;
 //3个按钮
 private Button loginbut = null, regeditbut =null, quitbut = null;
 private void init(){
  frm = new Frame("用户登陆");
  frm.setBounds(300, 100, 500, 350);
  frm.setBackground(Color.gray);
  frm.setLayout(null);
  frm.setVisible(true);
  
  message = new Label("用户的登陆和注册");
  message.setBounds(150, 50, 100, 30);
  frm.add(message);
  
  usernamelbl = new Label("用户名");
  usernamelbl.setBounds(100, 100, 50, 30);
  frm.add(usernamelbl);
  
  usernametf = new TextField();
  usernametf.setBounds(160, 105, 150, 20);
  frm.add(usernametf);
  
  passwordlbl = new Label("密  码");
  passwordlbl.setBounds(100, 150, 50, 30);
  frm.add(passwordlbl);
  
  passwordtf = new TextField();
  passwordtf.setBounds(160, 150, 150, 20);
  passwordtf.setEchoChar('你');
  frm.add(passwordtf);
  
  loginbut = new Button("登陆");
  regeditbut = new Button("注册");
  
  loginbut.setBounds(150, 200, 50, 20);
  regeditbut.setBounds(250, 200, 50, 20);
  
  frm.add(loginbut);
  frm.add(regeditbut);
  myEvent();
 }
 private void myEvent(){
  loginbut.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    String username = usernametf.getText();
    String password = passwordtf.getText();
    if("".equals(username)||"".equals(password))
     return;
    //有了用户名和密码,到文本文件中,查找有没有这个匹配的用户名和密码
    boolean b = new User().login(username, password);
    if(b){
      new AllUserList();
    }else{
     System.out.println("登陆失败,检查用户名和密码");
    }
   }
  });
  
  regeditbut.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    //打开注册的窗体
    new FrameRegedit();
   }
  });
 }
}
import java.awt.*;
public class AllUserList {
 public AllUserList(){
  init();
  
 }
 private Frame frm = null;
 private TextArea ta = null;
 private void init() {
  frm = new Frame("展示所有用户的信息");
  frm.setBounds(300, 100, 500, 350);
  frm.setBackground(Color.gray);
  frm.setLayout(null);
  frm.setVisible(true);
  ta = new TextArea();
  ta.setBounds(50, 35, 400, 300);
  frm.add(ta);
  String s = new User().allUserList();
  ta.setText("");
  ta.append(s);
 }
 
}
public class Test {
 public static void main(String[] args) {
  new FrameLogin();
 }
}

5. 网络通讯的三要素
  |-- IP地址
    |-- 接入互联网的计算的,唯一的身份标识  222.222.123.23   
www.baidu.com.cn  edu gov org 
    |-- 本机回环地址 127.0.0.1 localhost ,只要你的机器的网卡是好的,安装了驱动
    |-- java中,将IP地址,封装成对象,java.net.InetAddress
    |-- InetAddress私有构造,找静态方法,返回这个类的对象
      |-- getName("主机名")根据主机名,获取该主机的IP地址对象
      |-- getLocalHost()获取本机IP地址对象
      |-- 通过IP地址对象,单独获取IP 和主机名

  |-- 端口号
    |-- 用于标识进程的逻辑地址,不同进程的标识(十进制数)
    |-- 有效端口:0~65535,其中0~1024系统使用或保留端口。
    |-- 常见端口 80,1433 ,1521,3306
    |-- 注意:一个端口号上,只能有一个应用程序

  |-- 协议
    |-- UDP
      |-- 面向无连接
      |-- 发送的数据有限制 64K
      |-- 不安全的协议
      |-- 效率高
    |-- TCP
      |-- 面向连接
      |-- 传输大数据
      |-- 安全可靠
      |-- 效率低

6. Socket服务
  |-- 港口,快递
  |-- 发送和接收都需要有Socket服务

7. UDP的发送端
  |-- DatagramSocket对象即可发送,也可以接收
  |-- 发送数据的步骤
    |-- 先要有数据
    |-- 将数据封包DatagramPacket
        DatagramPacket(byte[] buf, int length, InetAddress address, int port)
    |-- 发送
    |-- 关闭资源

9. UDP的接收端
  |-- DatagramSocket对象即可发送,也可以接收
  |-- 先建立Socket服务,监听端口
  |-- 接收 void receive(DatagramPacket p) 数据包
  |-- 解包
  |-- 关闭资源

10. 多线程的聊天程序,案例*****

import java.net.*;

public class TestUDP {
 public static void main(String[] args) throws Exception{
  //建立Socket对象,将Socket对象传给多线程程序
  //建立发送端的Socket服务
  DatagramSocket dsSend = new DatagramSocket(8000);
  DatagramSocket dsReceive = new DatagramSocket(10000);
  
  ThreadUDPSend ts = new ThreadUDPSend(dsSend);
  ThreadUDPReceive tr = new ThreadUDPReceive(dsReceive);
  
  new Thread(ts).start();
  new Thread(tr).start();
 }

}
import java.net.*;
public class ThreadUDPReceive  implements Runnable{
 private DatagramSocket ds;
 public ThreadUDPReceive(DatagramSocket ds){ this.ds = ds;}
   public void run(){
    while(true){
     try{
     byte[] buf = new byte[1024];
     DatagramPacket dp = new DatagramPacket(buf, 0,buf.length);
     ds.receive(dp);
     //获取数组中的有效长度
     int length = dp.getLength();
     //获取发送的IP地址
     String ip = dp.getAddress().getHostAddress();
     int port = dp.getPort();//端口号
     String message = new String(buf,0,length);
     if("over".equals(message)){
      System.out.println(ip+"::"+port+"::退出聊天室");
     }
     System.out.println(ip+"::"+port+"::"+message);
     }catch(Exception e){}
    }
   }
}

import java.net.*;
import java.io.*;

public class ThreadUDPSend implements Runnable{
 private DatagramSocket ds;
 public ThreadUDPSend(DatagramSocket ds){ this.ds = ds;}
 public void run(){
  BufferedReader bfr = null;
  try{
   bfr = new
    BufferedReader(new InputStreamReader(System.in));
  String line = null;
  while((line = bfr.readLine())!=null){
   if("over".equals(line))
    break;
   //封装数据包
   byte[] buf = line.getBytes();
   DatagramPacket dp =
     new DatagramPacket(buf, 0,buf.length,InetAddress.getByName("127.0.0.1"),10000);
   ds.send(dp);
    }
  }
  catch(IOException e){
   System.out.println(e);
   throw new RuntimeException("发送失败");
  }finally{
   try{
    if(bfr!=null)
     bfr.close();
   }catch(IOException e){}
   
   ds.close();
  }
 }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用JavaWeb实现用户注册登录页面并完成图片验证码的示例代码: 1. 注册页面代码 register.jsp ```html <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>注册页面</title> </head> <body> <form action="register" method="post"> 用户名:<input type="text" name="username"><br> 密码:<input type="password" name="password"><br> 确认密码:<input type="password" name="confirm_password"><br> 验证码:<input type="text" name="verificationCode"><img src="verificationCode" alt="验证码"><br> <input type="submit" value="注册"> </form> </body> </html> ``` 2. 登录页面代码 login.jsp ```html <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>登录页面</title> </head> <body> <form action="login" method="post"> 用户名:<input type="text" name="username"><br> 密码:<input type="password" name="password"><br> 验证码:<input type="text" name="verificationCode"><img src="verificationCode" alt="验证码"><br> <input type="submit" value="登录"> </form> </body> </html> ``` 3. 图片验证码生成代码 VerificationCodeServlet.java ```java import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebServlet("/verificationCode") public class VerificationCodeServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int width = 80; int height = 40; Random random = new Random(); // 随机生成验证码 String verificationCode = ""; for (int i = 0; i < 4; i++) { verificationCode += random.nextInt(10); } // 将验证码存入session HttpSession session = request.getSession(); session.setAttribute("verificationCode", verificationCode); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); // 设置背景颜色 g.setColor(new Color(255, 255, 255)); g.fillRect(0, 0, width, height); // 设置字体颜色 g.setColor(new Color(0, 0, 0)); // 设置字体 g.setFont(new Font("Arial", Font.BOLD, 20)); // 绘制验证码 g.drawString(verificationCode, 20, 25); // 输出图片 response.setContentType("image/jpeg"); ImageIO.write(image, "jpeg", response.getOutputStream()); } } ``` 4. 注册和登录处理代码 RegisterServlet.java 和 LoginServlet.java ```java import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebServlet("/register") public class RegisterServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); String confirmPassword = request.getParameter("confirm_password"); String verificationCode = request.getParameter("verificationCode"); HttpSession session = request.getSession(); String sessionVerificationCode = (String) session.getAttribute("verificationCode"); if (!verificationCode.equals(sessionVerificationCode)) { // 验证码错误 response.sendRedirect("register.jsp"); } else if (!password.equals(confirmPassword)) { // 两次密码不一致 response.sendRedirect("register.jsp"); } else { // 注册成功 // ...处理注册逻辑 response.sendRedirect("login.jsp"); } } } import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebServlet("/login") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); String verificationCode = request.getParameter("verificationCode"); HttpSession session = request.getSession(); String sessionVerificationCode = (String) session.getAttribute("verificationCode"); if (!verificationCode.equals(sessionVerificationCode)) { // 验证码错误 response.sendRedirect("login.jsp"); } else { // 登录成功 // ...处理登录逻辑 response.sendRedirect("index.jsp"); } } } ``` 注意:以上代码仅为示例代码,实际应用中需要根据具体需求进行修改和完善。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值