java语言实现用户注册和登录

Python015

java语言实现用户注册和登录,第1张

//这个是我写的,里面有连接数据库的部分。你可以拿去参考一下

import java.awt.*

import javax.swing.*

import java.awt.event.*

import java.sql.*

class LoginFrm extends JFrame implements ActionListener// throws Exception

{

JLabel lbl1 = new JLabel("用户名:")

JLabel lbl2 = new JLabel("密码:")

JTextField txt = new JTextField(5)

JPasswordField pf = new JPasswordField()

JButton btn1 = new JButton("确定")

JButton btn2 = new JButton("取消")

public LoginFrm() {

this.setTitle("登陆")

JPanel jp = (JPanel) this.getContentPane()

jp.setLayout(new GridLayout(3, 2, 5, 5))

jp.add(lbl1)

jp.add(txt)

jp.add(lbl2)

jp.add(pf)

jp.add(btn1)

jp.add(btn2)

btn1.addActionListener(this)

btn2.addActionListener(this)

}

public void actionPerformed(ActionEvent ae) {

if (ae.getSource() == btn1) {

try {

Class.forName("com.mysql.jdbc.Driver")// mysql数据库

Connection con = DriverManager.getConnection(

"jdbc:mysql://localhost/Car_zl", "root", "1")// 数据库名为Car_zl,密码为1

System.out.println("com : "+ con)

Statement cmd = con.createStatement()

String sql = "select * from user where User_ID='"

+ txt.getText() + "' and User_ps='"

+ pf.getText() + "'"

ResultSet rs = cmd

.executeQuery(sql)// 表名为user,user_ID和User_ps是存放用户名和密码的字段名

if (rs.next()) {

JOptionPane.showMessageDialog(null, "登陆成功!")

} else

JOptionPane.showMessageDialog(null, "用户名或密码错误!")

} catch (Exception ex) {

}

if (ae.getSource() == btn2) {

System.out.println("1111111111111")

//txt.setText("")

//pf.setText("")

System.exit(0)

}

}

}

public static void main(String arg[]) {

JFrame.setDefaultLookAndFeelDecorated(true)

LoginFrm frm = new LoginFrm()

frm.setSize(400, 200)

frm.setVisible(true)

}

}

java的用户登录记住上次登录的用户名和密码的方式是使用cookie来保存在本地,并且需要加密保存,实例如下:

HttpServletRequest request = ServletActionContext.getRequest()

Cookie cookies[]=request.getCookies()//声明一个cookie对象

String login=null//登录的用户名 

String password=null //登录的密码

for (int i = 0 i < cookies.length i++){   //取最后一次保存的用户名和密码

    if(cookies[i].getName().equals("userName")){

             login = cookies[i].getValue()

     }

    if (cookies[i].getName().equals("password")){

         password = cookies[i].getValue()

         break

    }

    }

    if(!AssertUtil.isEmpty(login)&&!login.equals("JSESSIONID")){

    request.setAttribute("login", login)

    request.setAttribute("password", password)

}

同意楼上的说法,具体点可以这样:创建一个用户表,里边包括LoginName(登录名),UserName(用户名),Password(密码),Age(年龄),Address(地址)。然后编写Java程序(用MVC架构)模型层(M):DBConnection.java(负责连接数据库)

import java.sql.Connection

import java.sql.DriverManager

import java.sql.*

public class DBConnection {

private static final String DRIVER_CLASS = "sun.jdbc.odbc.JdbcOdbcDriver"

private static final String DB_URL = "jdbc:odbc:text"

public DBConnection() {

}

public static Connection getConnection() {

Connection conn = null

try {

Class.forName(DRIVER_CLASS)

conn = DriverManager.getConnection(DB_URL)

} catch (SQLException ex) {

System.out.println(ex.getMessage())

} catch (ClassNotFoundException ex) {

System.out.println(ex.getMessage())

}

return conn

}

}

第2个负责数据库查询操作的类:DBUserManager.java

import edu.systop.text.model.entity.User

import edu.systop.text.model.dao.DBConnection

import java.sql.Connection

import java.sql.PreparedStatement

import java.sql.ResultSet

import java.sql.DriverManager

import java.sql.*

public class DBUserManager {

private static final String SQL_SELECT =

"SELECT LoginName,UserName,PassWord,Age,Address FROM UserInfo WHERE LoginName = ? AND PassWord = ?"

public DBUserManager() {

}

public boolean checkDB(User u) {

boolean b = false

Connection conn = null

PreparedStatement psmt = null

ResultSet rs = null

conn = DBConnection.getConnection()

try {

psmt = conn.prepareStatement(SQL_SELECT)

psmt.setString(1, u.getLoginName())

psmt.setString(2, u.getPassWord())

rs = psmt.executeQuery()

b = rs.next()

if (rs.next()) {

b = true

}

} catch (SQLException ex) {

System.out.println(ex.getMessage())

} finally {

cleanDB(rs, psmt, conn)

}

return b

}

public User checkBC(User u) {

Connection conn = null

PreparedStatement psmt = null

ResultSet rs = null

User tmp = new User()

conn = DBConnection.getConnection()

try {

psmt = conn.prepareStatement(SQL_SELECT)

psmt.setString(1, u.getLoginName())

psmt.setString(2, u.getPassWord())

rs = psmt.executeQuery()

if (rs.next()) {

tmp.setLoginName(rs.getString(1))

tmp.setUserName(rs.getString(2))

tmp.setAge(rs.getInt(4))

tmp.setAddress(rs.getString(5))

}

} catch (SQLException ex) {

System.out.println(ex.getMessage())

} finally {

cleanDB(rs, psmt, conn)

}

return tmp

}

public void cleanDB(ResultSet rs, PreparedStatement psmt, Connection conn) {

try {

if (rs != null) {

rs.close()

}

if (psmt != null) {

psmt.close()

}

if (conn != null) {

conn.close()

}

} catch (SQLException ex) {

System.out.println(ex.getMessage())

}

}

第3个实体用户类:User.java

package edu.systop.text.model.entity

public class User {

private String loginName

private String userName

private String passWord

private int age

private String address

public User() {

}

public void setLoginName(String loginName) {

this.loginName = loginName

}

public void setUserName(String userName) {

this.userName = userName

}

public void setPassWord(String passWord) {

this.passWord = passWord

}

public void setAge(int age) {

this.age = age

}

public void setAddress(String address) {

this.address = address

}

public String getLoginName() {

return loginName

}

public String getUserName() {

return userName

}

public String getPassWord() {

return passWord

}

public int getAge() {

return age

}

public String getAddress() {

return address

}

}

然后编写控制层(C):GetInfoServlet.java

package edu.systop.text.control

import javax.servlet.*

import javax.servlet.http.*

import java.io.*

import java.util.*

import edu.systop.text.model.entity.User

import edu.systop.text.model.service.UserManager

public class GetInfoServlet extends HttpServlet {

private static final String CONTENT_TYPE = "text/htmlcharset=GBK"

//Initialize global variables

public void init() throws ServletException {

}

//Process the HTTP Get request

public void doGet(HttpServletRequest request, HttpServletResponse response) throws

ServletException, IOException {

}

//Process the HTTP Post request

public void doPost(HttpServletRequest request, HttpServletResponse response) throws

ServletException, IOException {

String loginName = request.getParameter("loginName")

String passWord = request.getParameter("passWord")

User u = new User()

u.setLoginName(loginName)

u.setPassWord(passWord)

UserManager m = new UserManager()

RequestDispatcher d

if (m.checkUser(u)) {

User o = m.checkBC(u)

request.setAttribute("JavaBEAN",o)

d = request.getRequestDispatcher("GetInfoUser.jsp")

} else {

d = request.getRequestDispatcher("GetInfoFinale.jsp")

}

d.forward(request, response)

}

//Clean up resources

public void destroy() {

}

}

最后,创建表示层(V):包括3个Jsp(登录页面GetInfo.jsp、登录成功页面GetInfoUser.jsp、登录失败页面GetInfoFinale.jsp)

上面的就是Jsp结合Servlet用MVC架构写的用户登录程序。