create database learnjsp
go
use learnjsp
go
create table userinfo
(
username varchar(20) primary key not null,
userpassword varchar(20) not null
)
select * from userinfo
insert into userinfo(username,userpassword)values('admin','admin888')
select * from userinfo where username =? and userpassword = ?
文件一:login.jsp用户登录填写文件
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<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">
-->
<script type="text/javascript">
function checklogin(){
if(document.loginform.username.value==""){
alert("用户名不能为空");
document.loginform.username.focus();
return false;
}
if(document.loginform.userpassword.value==""){
alert("密码不能为空");
document.loginform.userpassword.focus();
return false;
}
return true;
}
</script>
</head>
<body>
用户登录 <br>
<form action="CheckLogin" method="post" name="loginform" onSubmit="return checklogin();">
用户名:<input type="text" name="username" maxlength="20" size="20">用户名长度不能超过20位<br>(限制用户输入的长度,与数据库中的用户字段长段相吻合)
密码:<input type="password" name="userpassword" maxlength="20" size="20">密码长度不能超过20位<br>
<input type="submit" value="登录"><input type="reset" value="重置">
</form>
</body>
</html>
文件二:Dao.java实现数据库的连接,和检查用户名和密码是否正确的方法
package com.source.dao;
import java.sql.*;
public class Dao {
private Connection conn = null;
private ResultSet rs = null;
private PreparedStatement pstmt = null;
private String user = "sa";
private String password = "sa";
private String url = "jdbc:sqlserver://localhost:1433;databasename=learnjsp";
public Connection getConn() {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(url, user, password);
//System.out.println("conn success");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public boolean validateLogin(String username, String userpassword) {
boolean flag = false;
String sql = "select * from userinfo where username =? and userpassword = ?";
conn = getConn();
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, userpassword);
rs = pstmt.executeQuery();
if (rs.next()) {
flag = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (rs != null)
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
rs = null;
}
if (pstmt != null)
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
pstmt = null;
}
if (conn != null)
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-genserated catch block
e.printStackTrace();
} finally {
conn = null;
}
}
return flag;
}
}
文件三:CheckLogin.java servlet处理检查用户名和密码是否正确的控制层
package com.source.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.source.dao.*;
public class CheckLogin extends HttpServlet {
/**
* Constructor of the object.
*/
public CheckLogin() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");//解决中文乱码问题
response.setContentType("text/html;charset=UTF-8");//解决中文乱码问题
PrintWriter out = response.getWriter();
//get value
String username = request.getParameter("username").trim();
String userpassword = request.getParameter("userpassword").trim();
if(username=="" || username==null || username.length()>20){
//先判断输入的用户名和密码长度是否符合要求
out.println("用户名不能为空或者长度超过20位!!!<br><a href='login.jsp'>重新登录</a>");
}else if(userpassword=="" || userpassword==null || userpassword.length()>20){
out.println("密码不能为空或者长度超过20位!!!<br><a href='login.jsp'>重新登录</a>");
}else{
//call bo
Dao dao = new Dao();
boolean flag = dao.validateLogin(username, userpassword);
if(flag){
//验证成功的话,把用户名放到session中
HttpSession session = request.getSession();
session.setAttribute("username", username);
//然后转向成功页面
response.sendRedirect("success.jsp");
}else{
//验证失败则转向失败页面
response.sendRedirect("failure.jsp");
}
}
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
文件四:success.jsp 验证成功后,显示的欢迎页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'success.jsp' starting page</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>
<%
if(session.getAttribute("username")==null){
//判断是否成功登录过,防止直接输入地址进入成功页
%>
请先登录后再访问本页<br>
<a href="login.jsp">返回登录</a>
<%
}else{
String username = (String)session.getAttribute("username");
%>
欢迎: <font color="red"><%=username %></font>的到来<br>
<a href="logout.jsp">安全退出</a>
<%
}
%>
</body>
</html>
文件五:logout.jsp登录成功后,退出页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'logout.jsp' starting page</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>
<%
//先将session的值移除掉
session.removeAttribute("username");
//再消毁掉session,更加安全,消毁一定要在后面,要是先消毁再操作session会出异常
session.invalidate();
%>
<script type="text/javascript">
alert("成功退出,确定后转向登录页面");
location.href="login.jsp";
</script>
</body>
</html>
文件六:failure.jsp登录失败,显示的页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'failure.jsp' starting page</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>
用户名或者密码错误 <br>
请重新<a href="login.jsp">登录</a>
</body>
</html>
这里进行了两次验证,一个是客户端的javascript验证,另一处是后台servlet验证.
前台先进行客户端验证是为了减轻服务器的负担.后台再进行一次验证是为了更加安全.