代码目录结构(只用到了四个Jsp页面)
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>
<title>用户登录页面</title>
</head>
<body>
<form action="dologin.jsp" method = "post"><!-- post提交给dologin.jsp页面处理逻辑 -->
<table align = "center" border = "1" width = "500">
<tr>
<td>用户名称:</td>
<td>
<input type = "text" name = "username"/>
</td>
</tr>
<tr>
<td>用户密码:</td>
<td>
<input type = "password" name = "password"/>
</td>
</tr>
<tr align = "center">
<td colspan = "2">
<input type = "submit" value = "登录"/>
<input type = "reset" value = "重置"/>
</td>
</tr>
</table>
</form>
</body>
</html>
dologin.jsp(处理表单提交的业务)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//定义两个字符串空,用来存输入用户名和密码
String username = "";
String password = "";
//定义传输流字符集utf-8避免生成乱码
request.setCharacterEncoding("utf-8");
//接收两个数据
username = request.getParameter("username");
password = request.getParameter("password");
//业务处理
if("admin".equals(username)&&"admin".equals(password)){
//内置都想session中将username复制给loginUser让success.jsp输出
session.setAttribute("loginUser", username);
//请求重定向
request.getRequestDispatcher("success.jsp").forward(request, response);
}else{
//请求转发
response.sendRedirect("failure.jsp");
}
%>
success.jsp(登陆成功页面)
<%@page import="java.nio.channels.SeekableByteChannel"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String username = "";
if(session.getAttribute("loginUser")!=null){
username = session.getAttribute("loginUser").toString();
}
%>
<h1>登陆成功!
欢迎:<font color="red"><%=username %></font>
</h1>
</body>
</html>
failure.jsp(登陆失败页面)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
登录失败!<br>
<a href="login.jsp">返回登陆</a>
</body>
</html>