<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>登陆页面</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="/Session/servlet/LoginServlet" method="post">
用户名:<input type="text" name="username"><br/>
密码:<input type="password" name="password"><br/>
<input type="submit" value="登陆">
</form>
</body>
</html>
package login;
public class User
{
private String username;
private String password;
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(String username, String password) {
super();
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
package login;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = DB.find(username, password); //html
if(user==null){
out.write("用户名或密码有误!!");
return;
}
request.getSession().setAttribute("user", user); //向用户session中存一个登陆标记,也就是让用户登陆成功
response.sendRedirect("/Session/index1.jsp");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
class DB
{
private static List<User> list = new ArrayList();
static{
list.add(new User("aaa","123"));
list.add(new User("bbb","123"));
list.add(new User("ccc","123"));
}
public static User find(String username ,String password){
for(User user : list){
if(user.getUsername().equals(username) && user.getPassword().equals(password)){
return user;
}
}
return null;
}
}
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="login.User"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
</head>
<body>
欢迎您:
<%
User user = (User)session.getAttribute("user");
if(user!=null) out.write(user.getUsername());
%>
<br/><br/>
<a href="/Session/login.html">登陆</a>
</body>
</html>
浏览器输入:http://localhost:8080/Session/login.html
对用户名和密码进行输入:
输入错误用户名和密码::
登陆:
输入正确的用户名和密码:
登陆: