Java代码
创建JavaBean,用来封装用户登录时表单中的用户名和密码
package servlet;
public class User {
private int id;
private String username;
private String email;
private String password;
public void User() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
创建一个接口用来存放连接数据库所用的方法
package com.java.demo.Impl;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public interface DemoImpl {
Connection createConnection() throws SQLException;
public void close(ResultSet rs);
public void close(Statement stmt);
public void close(Connection conn);
public int executeUpdate(String sql, Object... parameters) throws SQLException;
public int executeUpdate(Connection conn, String sql,Object... parameters) throws SQLException;
ResultSet executeQuery(String sql, Object... parameters) throws SQLException;
ResultSet executeQuery(Connection conn, String sql,Object... parameters) throws SQLException;
public void closeAll(ResultSet rs);
}
连接数据库
创建JdbcUtils类实现DemoImpl接口
package com.java.conn;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.java.demo.Impl.DemoImpl;
public class JdbcUtils2 implements DemoImpl{
/**
* 连接数据库的基本参数。均声明为final类型,即变量只可被赋值一次,且为private私有的。
*/
private final static String dbdriver = "com.mysql.jdbc.Driver";
private final static String dburl = "jdbc:mysql://localhost:3306/javaweb?seUnicode=true&characterEncoding=UTF8&useSSL=false";
private final static String dbusername = "root";
private final static String dbpassword = "root";
/**
* 这种注释是文档注释
* 一般对于整个类整个方法做说明的时候,用此注释
* 静态代码块,在创建此类的实例时执行。
* @author lenovo
*/
//这种是注释是让别人能过看懂这段代码
static
{
try
{
Class.forName(dbdriver);//加载驱动
} catch (ClassNotFoundException e)
{
throw new ExceptionInInitializerError(e);
}
}
/**
* 创建连接
* @return
* @throws SQLException
*/
public Connection createConnection() throws SQLException
{
return DriverManager.getConnection(dburl, dbusername, dbpassword);
}
/**
* 关闭ResultSet
* @param rs
*/
public void close(ResultSet rs)
{
if (rs != null)
{
try
{
rs.close();
} catch (SQLException e)
{
}
}
}
/**
* 关闭statement
* @param stmt
*/
public void close(Statement stmt)
{
if (stmt != null)
{
try
{
stmt.close();
} catch (SQLException e)
{
}
}
}
/**
* 关闭connection
* @param conn
*/
public void close(Connection conn)
{
if (conn != null)
{
try
{
conn.close();
} catch (SQLException e)
{
}
}
}
/**
* 执行除查询以外的语句
* @param sql
* @param parameters为可变长度参数,相当于数组
* @return
* @throws SQLException
*/
public int executeUpdate(String sql, Object... parameters)
throws SQLException
{
Connection conn = null;
try
{
conn = createConnection();
return executeUpdate(conn, sql, parameters);//调用。
} finally
{
close(conn);
}
}
public int executeUpdate(Connection conn, String sql,
Object... parameters) throws SQLException
{
PreparedStatement ps = null;
try
{
ps = conn.prepareStatement(sql);
//开始遍历
for (int i = 0; i < parameters.length; i++)
{
ps.setObject(i + 1, parameters[i]);//setObject(parm1,parm2);其中parm1为占位符的位置,parm2为对应占位符的值
}
return ps.executeUpdate();//执行SQL
} finally
{
close(ps);
}
}
/**
* 执行查询语句
* @param sql
* @param parameters
* @return
* @throws SQLException
*/
public ResultSet executeQuery(String sql, Object... parameters)
throws SQLException
{
Connection conn = null;
try
{
conn = createConnection();
return executeQuery(conn, sql, parameters);//调用
} catch (SQLException ex)
{
close(conn);
throw ex;
}
}
public ResultSet executeQuery(Connection conn, String sql,
Object... parameters) throws SQLException
{
PreparedStatement ps = null;
ResultSet rs = null;
try
{
ps = conn.prepareStatement(sql);
//遍历
for (int i = 0; i < parameters.length; i++)
{
ps.setObject(i + 1, parameters[i]);//给占位符传参
}
rs = ps.executeQuery();//执行SQL
return rs;
} catch (SQLException ex)
{
close(ps);
throw ex;
}
}
/**
* 关闭所有资源
* @param rs
*/
public void closeAll(ResultSet rs)
{
if (rs == null)
{
return;
}
try
{
close(rs);
close(rs.getStatement());
close(rs.getStatement().getConnection());
} catch (SQLException e)
{
}
}
}
在这里我用到了 工厂模式
下面我在说为什么使用工厂模式
package com.java.demo.Factory;
import com.java.conn.JdbcUtils2;
import com.java.demo.Impl.DemoImpl;
public class DaoFactory {
public static DemoImpl getUserDao() {
return new JdbcUtils2();
}
}
JSP页面(CSS样式代码我没有弄)
首先是登陆界面
<%@ page language="java" import="java.io.*,java.util.*" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录界面</title>
</head>
<body>
<%
//获取客户端的Cookie
//1.获取Cookie数组
/* String username="";
String password="";
Cookie[] cookies=request.getCookies();
if(!"".equals("cookies")&&cookies.length>0){
for(Cookie cookie:cookies){
if("username".equals(cookie.getName())){
username=cookie.getValue();
}
if("password".equals(cookie.getName())){
password=cookie.getValue();
}
}
} */
%>
<div class="yemian">
<div id="yemian-head">
<h1 align="center">登录页面的简单实现</h1>
</div>
<hr>
<div class="yemian-content">
<div id="tips"></div>
<form id="form1" name="form1" method="post" action="denglu_chuli.jsp">
<table>
<tr><th>用户名:</th><td><input type="text" id="username" name="username" <%-- value="<%=username %>" --%> placeholder="请输入用户名"></td><td><a href="../chap5/registerP.jsp" id="zhuce">注册新用户</a></td></tr>
<tr><th>密 码:</th><td> <input type="password" id="password" name="password" <%-- value="<%=password %> " --%> placeholder="请输入密码"></td><td><a href="searchmima.jsp" id="search">找回密码?</a></td></tr>
<tr><th>验证码:</th><td><div class="yanzhengma"><input type="text" name="shuru" id="shuru"><div id="yanzheng"></div><div></td></tr>
</table>
<div id="btn">
<input type="submit" id="submit" value="登录" onclick="return check()">
<input type="reset" id="reset" value="重置">
</div>
</form>
</div>
</div>
<!-- 生成验证码 -->
<script type="text/javascript">
var d1=document.getElementById("yanzheng");
var codeChars=new Array('a','b','c','d','e','f','g','h','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1',
'2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
var yanzhengma="";
var obj;
var username=document.getElementById("username");
var password=document.getElementById("password");
var shuru=document.getElementById("shuru");
function sc(){
var Num=0;
for(var i=0;i<4;i++){
Num=parseInt(Math.random()*60);
yanzhengma+=codeChars[Num];
}
console.log(yanzhengma);
d1.innerHTML=""
+yanzhengma+"";
}
window.onload=function(){
sc();
addBlur($('username'));
addBlur($('password'));
addBlur($('shuru'));
}
//首先获取input控件的id
function $(obj){
return document.getElementById(obj);
}
//在输入框为空的时候添加焦点失去事件
function addBlur(obj){
//调用onblur
obj.onblur=function(){
isEmpty(this);
};
}
//判断表单是否为空
function isEmpty(obj){
if(username.value==''){
$('tips').style.display='block';
$('tips').innerHTML='用户名不能为空!';
document.getElementById("username").focus();
return false;
}
if(password.value==''){
$('tips').style.display='block';
$('tips').innerHTML='密码不能为空!';
document.getElementById("password").focus();
return false;
}
return true;
}
//判断验证码是否输入正确
function check(){
if(yanzhengma.toLowerCase()!=shuru.value.toLowerCase()){
alert("验证码输入错误!");
return false;
} else{
return true;
}
}
document.getElementById("yanzheng");
</script>
登录处理,判断用户输入的用户名密码是否正确
<%@page import="java.sql.SQLException"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.ResultSet"%>
<%@ page import="com.java.conn.JdbcUtils"%>
<%@ page import="servlet.User"%>
<%@ page import="com.java.demo.Impl.*" %>
<%@ page import="com.java.demo.Factory.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>判断用户输入的内容</title>
</head>
<body>
<%
//设置请求编码
request.setCharacterEncoding("UTF-8");
//设置响应编码
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
String pwd = request.getParameter("password");
DemoImpl denglu=DaoFactory.getUserDao();
ResultSet rs=denglu.executeQuery("select * from admin_info");
//我的返回值是ResultSet型的
/* String sql="select * from admin_info where name=? and pwd=?";
ResultSet rs = JdbcUtils.executeQuery(sql,username,pwd);*/
if(rs.next()) {
/* if("admin".equals(username)&&"123456".equals(pwd)){ */
/* //用户名密码中正确,通过向客户端cookie写用户登陆的用户名和密码
Cookie cookie1 = new Cookie("username", username);
Cookie cookie2 = new Cookie("password", pwd);
//设置cookie的有效期
cookie1.setMaxAge(60 * 60 * 24);
cookie2.setMaxAge(60 * 60 * 24);
response.addCookie(cookie1);
response.addCookie(cookie2);
*/
//放置数据
session.setAttribute("username", username);
//用户多长时间没使用,则设置失效时间
//session.setMaxInactiveInterval(5);
%>
<jsp:forward page="success.jsp" />
<%
} else {
%>
<jsp:forward page="error.jsp"/>
<!-- /* response.sendRedirect("error.jsp"); */ -->
<% }
%>
最后运行代码
login登录界面
登录成功啦 ?
1 工厂模式的作用,为什么要用工厂模式?
工厂模式是为了解耦:把对象的创建和使用的过程分开。就是Class A 想调用Class B,那么只是调用B的方法,而至于B的实例化,就交给工厂类。
工厂模式可以降低代码重复。如果创建B过程都很复杂,需要一定的代码量,而且很多地方都要用到,那么就会有很多的重复代码。可以把这些创建对象B的代码放到工厂里统一管理。既减少了重复代码,也方便以后对B的维护。
工厂模式可以减少错误,因为工厂管理了对象的创建逻辑,使用者不需要知道具体的创建过程,只管使用即可,减少了使用者因为创建逻辑导致的错误。