1.安装MySQL数据库,建立用户表 uid uname upwd 并插入3条数据
2.制作jsp登录页面 login.jsp 提交到dologin.jsp,使用jdbc连数据库,判断输入的用户名密码是否存在
3.如果存在,把用户名保存在SESSION中,跳转到welcome.jsp,welcome.jsp中读取session中的用户名,显示欢迎你xxx
4.若不存在,跳到登录页面。
package com.school.lty; import java.sql.DriverManager; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import com.mysql.jdbc.Driver; public class JDBCKu { public static Connection getConnection() throws Exception { Class clazz = Class.forName("com.mysql.jdbc.Driver"); Driver driver = (Driver) clazz.newInstance(); String url = "jdbc:mysql://localhost:3306/user_info?useUnicode=true&characterEncoding=utf8"; String user="root"; String password = "root"; DriverManager.registerDriver(driver); Connection conn = DriverManager.getConnection(url,user,password); return conn; } public static void closeAll(Connection conn, PreparedStatement ps, ResultSet rs) throws Exception { if (rs != null) rs.close(); if (ps != null) ps.close(); if (conn != null) conn.close(); } }
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <form action="doLogin.jsp" method="post" > 用户名:<input type="text" name="username"/> <br> 密码:<input type="password" name="password"/> <br> <input type="submit" value="登录"> </form> </body> </html>
<%@ page import="java.sql.Connection" %> <%@ page import="static com.school.lty.JDBCKu.getConnection" %> <%@ page import="java.sql.PreparedStatement" %> <%@ page import="java.sql.ResultSet" %> <%@ page import="com.school.lty.BaseDao" %> <%@ page import="com.school.lty.JDBCKu" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <% JDBCKu jdbcKu = new JDBCKu(); String username = request.getParameter("username"); String password = request.getParameter("password"); Connection conn = jdbcKu.getConnection(); String sql = "select * from user where uname = ? and upassword = ?"; PreparedStatement ps = conn.prepareStatement(sql); ps.setNString(1,username); ps.setNString(2,password); ResultSet rs = ps.executeQuery(); if (rs.next() == true) { request.getSession().setAttribute("username",username); request.getRequestDispatcher("welcome.jsp").forward(request,response); }else{ response.sendRedirect("index.jsp"); } jdbcKu.closeAll(conn, ps, rs); %> <body> </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <% String username = (String) request.getSession().getAttribute("username"); %> 欢迎您!<%=username%> </body> </html>