myEclipse for Spring2014
Navicat : 用来管理MySQL数据库
Firefox浏览器:用来展现并调试页面
第一步:先创建一个web项目工程,(涉及到从数据库抓取数据展现到浏览器项目的均为Web Project)取个名字吧:LoginDemo,简要步骤如下:
File-New-Web Project
然后在上面视图中点击两次“下一步”后进入如下页面,勾选generate web.xml....,则可以自动在WebRoot/WEB-INF下生成一个web.xml文件
如下是自动生成的web.xml文件的内容:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>LoginDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
接下来我们创建一个servlet,取名为LoginServlet,处理用户登录,步骤如下:
File-New-Servlet
点击下一步
点击上图完成,则一个登录的servlet创建完成了,但此时web.xml里没有自动给我们配置servlet,它是以注释的形式体现出来,如下图示:
所以为了能在web.xml里面自动配置servlet,我们需要采取其它方法。
在创建项目时,我们选择Dynamic Web Project, 2.5版本的支持web.xml里面自动配置servlet,3.0的不支持。
选择Dynamic Web Project, 2.5版本后,web.xml自动生成了servlet配置,如下图:
导入访问数据库的jar包
好了,准备工作基本结束了,现在开始上菜了:
第二步,编写代码了。
1>Login.jsp:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style>
body {
top: 20%;
text-align: center
}
.div {
top: 50%;
margin: auto;
}
</style>
<title>Insert title here</title>
<!--判断是否为空-->
<script type="text/javascript">
function login(form) {
if (form.username.value == "") {
alert("用户不能为空!");
return false;
}
if (form.password.value == "") {
alert("密码不能为空!");
return false;
}
}
</script>
</head>
<body>
<h1>登录</h1>
<hr>
<br>
<br>
<br>
<div class="div">
<form method="post" action="LoginServlet"
onSubmit="return login(this);">
<center>
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"></td>
</tr>
</table>
</center>
<br> <br> <input type="submit" value="点击登录"
style="width: 120px; height: 33px; background: #ccc; color: black">
</form>
</div>
<br>
<br>
<div id="Butten">
<a href="zhuCe.jsp">还没有帐号??点击注册 ! !</a>
</div>
<br>
<br>
</body>
</html>
2>LoginFailed.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>登录失败</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
登录失败,请返回重新登录 <br>
<!--注意此处的action中的路径写法-->
<form action="Login.jsp">
<input type = "submit" value = "返回">
</form>
</body>
</html>
3>LoginSuccess.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>登陆成功</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<center><h1>登录成功!!!!</h1></center>
<hr>
</body>
</html>
4>zhuCe.jsp
<%@ page language="java" pageEncoding="utf-8"%>
<%@ page contentType="text/html;charset=utf-8"%>
<%
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=utf-8");
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<!--判断是否为空-->
<script type="text/javascript">
function login(form) {
if (form.username.value == "") {
alert("ID不能为空!");
return false;
}
if (form.password1.value == "") {
alert("密码不能为空!");
return false;
}
if (form.password1.value != form.password2.value) {
alert("两次输入密码不一致!!!!!");
return false;
}
}
</script>
</head>
<body>
<center>
<h1>注册:</h1>
<HR>
<form method="post" action="zhuCeServlet"
onSubmit="return login(this);">
ID :<br> <input type="text" name="username" value="" /><br>
建议字母加上数字!! <br>
<br> 密码 :<br> <input type="password" name="password1"
value="" /> <br>
<br> 再次输入密码 :<br> <input type="password" name="password2"
value="" /> <br>
<br> <input type="submit" value="点击注册" />
</form>
</center>
</body>
</html>
5>zhuCeSuccess.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>注册成功</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<center><h1>注册成功!!!!</h1></center>
<hr>
</body>
6>User.jsp
package com.user;
/*
* 用户登录类,定义基本属性,用户名和密码
*/
public class User {
private String username;
private String password;
public String getUsername(){
return this.username;
}
public void setUsername(String username){
this.username = username;
}
public String getPassword(){
return this.password;
}
public void setPassword(String password){
this.password = password;
}
}
7>DBDao.java
package com.dao;
import java.sql.*;
public class DBDao {
private static String USER = "root";
private static String PASSWORD = "123456";
private static String DB_URL = "jdbc:mysql://localhost:3306/logindemo";
private static String DB_DRIVER = "com.mysql.jdbc.Driver";
private static Connection connection = null;
//连接数据库
public static Connection getConnection(){
try {
Class.forName(DB_DRIVER);
connection = DriverManager.getConnection(DB_URL, USER, PASSWORD);
} catch (Exception e) {
System.out.println("数据库连接异常");
e.printStackTrace();
}
return connection;
}
public static void closeConnection(Connection connection){
if(connection != null){
try {
connection.close(); // 关闭数据库连接
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
8>UserDao.java
package com.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.user.User;
public class UserDao {
User user = null;
private String SQL = "";
public User login(String username, String password) {
SQL = "select * from UserPWD where username = ? and password = ?";
Connection connection = null;
PreparedStatement pstmt = null;
try {
connection = DBDao.getConnection();
pstmt = (PreparedStatement) connection.prepareStatement(SQL);
// 这里的意思将用户名和密码填到SQL语句的问号处
pstmt.setString(1, username);
pstmt.setString(2, password);
ResultSet rSet = (ResultSet) pstmt.executeQuery();//得到数据库的查询结果,一个数据集
// 判断结果集是否有效
if (rSet.next()) {
user = new User();
user.setUsername(rSet.getString("username"));
user.setPassword(rSet.getString("password"));
}
pstmt.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBDao.closeConnection(connection);
}
return user;
}
public int zhuCe(String username, String password) {
SQL = "insert into userpwd(username,password) values (?,?)";
int b=0;
Connection connection = null;
PreparedStatement pstmt = null;
try {
connection = DBDao.getConnection();
pstmt = connection.prepareStatement(SQL);
pstmt.setString(1, username);
pstmt.setString(2, password);
b=pstmt.executeUpdate();
System.out.println("---------"+b);
pstmt.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBDao.closeConnection(connection);
}
return b;
}
}
9>LoginServlet.java
package com.login.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dao.UserDao;
import com.user.User;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
// 获取用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
// 获取UserDao实例
UserDao userDao = new UserDao();
User user = userDao.login(username, password);
// 判断user是否为空
if (user != null) {
// 转发到LoginSuccess.jsp页面
// getRequestDispatcher()是请求转发
request.getRequestDispatcher("LoginSuccess.jsp").forward(request,
response);
} else {
// 登录失败
request.getRequestDispatcher("LoginFailed.jsp").forward(request,
response);
}
System.out.println("-------******--------");
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
10>zhuCeServlet.java
package com.login.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dao.UserDao;
public class zhuCeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public zhuCeServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("zhuCeServlet.java访问我啦");
response.setCharacterEncoding("utf-8");
// 获取用户名和密码
String username = request.getParameter("username");
System.out.println("username----->" + username);
String password = request.getParameter("password1");
System.out.println("password----->" + password);
// 获取UserDao实例
UserDao userDao = new UserDao();
int i = userDao.zhuCe(username, password);
System.out.println("-----" + i);
// 判断i的值,为0表示未插入,为1表示插入一条数据
if (i != 0) {
System.out.println("-----------注册成功---------");
request.getRequestDispatcher("zhuCeSuccess.jsp").forward(request,
response);
} else {// 注册失败,仍然去注册页面 操作
System.out.println("000000000000000000000");
request.getRequestDispatcher("zhuCe.jsp")
.forward(request, response);
}
}
}
11>web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>LoginDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description>my first servlet</description>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.login.servlet.LoginServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>zhuCeServlet</servlet-name>
<servlet-class>com.login.servlet.zhuCeServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>zhuCeServlet</servlet-name>
<url-pattern>/zhuCeServlet</url-pattern>
</servlet-mapping>
</web-app>
mysql数据库,数据库名logindemo,表名userpwd.