Java实现表单登陆及验证

Java实现登陆及验证

  1. 前端代码
    前端代码只是一个表单随意就好具体样式看个人爱好






欢迎登陆










  1. 后端接受数据的代码
package login;

import java.io.IOException;
import java.io.PrintWriter;

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 mysql.chelogin;

/**
 * Servlet implementation class login
 */
@WebServlet("/login")
public class login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public login() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
		PrintWriter pw = response.getWriter();
		pw.append("sss");
		String username = request.getParameter("username");
		String userpass = request.getParameter("userpass");
		System.out.println("账号:"+username);
		System.out.println("userpass:"+userpass);
		chelogin ch = new chelogin(username,userpass);
		if(ch.check()) {
			System.out.println("登陆成功");
			response.sendRedirect("logintrue.html");
		}else {
			System.out.println("登陆失败");
			response.sendRedirect("loginfalse.html");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

3.数据库验证的代码

package mysql;
import java.sql.*;
import java.sql.DriverManager;

public class chelogin {
	String user = "root";
	String password = "123123";
	private String name;
	private String pass;
	public chelogin(String username,String userpass){
		this.name = username;
		this.pass = userpass;
	}
	public boolean check(){
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://localhost:3306/login";
			Connection conn = DriverManager.getConnection(url, user, password);
			Statement stmt = conn.createStatement();
			String sql = "select * from user where name = '"+name+"'";
			ResultSet rs = stmt.executeQuery(sql);
			System.out.println(sql);
			System.out.println(pass);
			if(rs.next()) {
				if(rs.getString(3).equals(pass) ) {
					System.out.println(rs.getString(3));
					return true;
				}
				else {
					System.out.println(rs.getString(3));
					return false;
				}
			}else {
				return false;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}
}

总结
前端用最简单的表单提交
后端用request.getParameter()函数接收数据
数据用jdbc连接并且从数据库中查询

你可能感兴趣的:(java,简单基础)