1、創(chuàng)建登錄界面login.jsp
1.1 樣式代碼:
<style>
body,p,div,ul,li,h1,h2,h3,h4,h5,h6{
margin:0;
padding: 0;
}
body{
background: #E9E9E9;
}
#login{
width: 400px;
height: 250px;
background: #FFF;
margin:200px auto;
position: relative;
}
#login h1{
text-align:center;
position:absolute;
left:120px;
top:-40px;
font-size:21px;
}
#login form p{
text-align: center;
}
#user{
background:url(images/user.png) rgba(0,0,0,.1) no-repeat;
width: 200px;
height: 30px;
border:solid #ccc 1px;
border-radius: 3px;
padding-left: 32px;
margin-top: 50px;
margin-bottom: 30px;
}
#pwd{
background: url(images/pwd.png) rgba(0,0,0,.1) no-repeat;
width: 200px;
height: 30px;
border:solid #ccc 1px;
border-radius: 3px;
padding-left: 32px;
margin-bottom: 30px;
}
#submit{
width: 232px;
height: 30px;
background: rgba(0,0,0,.1);
border:solid #ccc 1px;
border-radius: 3px;
}
#submit:hover{
cursor: pointer;
background:#D8D8D8;
}
</style>
1.2舞终、form表單以及cookie設(shè)置:
<%
Cookie[] cookie_arr=request.getCookies();
%>
<div id="login">
<h1>登錄管理</h1>
<form action="LoginServlet" method="post" id="login_form">
<p><input type="text" name="userName" id="user" value="<%
if(cookie_arr!=null){
for(Cookie cookie:cookie_arr){
if(cookie.getName().equals("login_uname")){
out.print(cookie.getValue());
}
}
}
%>" placeholder="用戶名"></p>
<p><input type="password" name="userPassword" id="pwd" value="<%
//判斷是否有用戶信息存入cookie,如果有則讀取
if(cookie_arr!=null)
{
for(Cookie cookie:cookie_arr){
if(cookie.getName().equals("login_pwd")){
out.print(cookie.getValue());
}
}
}
%>" placeholder="密碼"></p>
<p><input type="checkbox" value="check" name="check">記住密碼</p>
<p><input type="submit" id="submit" name="sub" value="登錄"></p>
</form>
</div>
2、配置LoginServlet.servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
//1癣猾、獲得用戶信息
String userName=request.getParameter("userName");
String userPassword=request.getParameter("userPassword");
//2敛劝、從數(shù)據(jù)庫獲取信息
String sql="select * from login_reg where userName=? && userPassword=?";
List<Object> paramList=new ArrayList<Object>();
paramList.add(userName);
paramList.add(userPassword);
DbHelper dbHelper=new DbHelper();
List<Map<String, Object>> list= dbHelper.executeQuery(sql, paramList);
if(list!=null && list.size()>0) {
if(request.getParameter("check")!=null) {
//4、如果客戶選擇了記住密碼則將用戶名和密碼存入cookie中
Cookie uname_cookie=new Cookie("login_uname", userName);
Cookie pwd_cookie=new Cookie("login_pwd", userPassword);
uname_cookie.setPath("/reg_login");
pwd_cookie.setPath("/reg_login");
uname_cookie.setMaxAge(15*24*3600);
pwd_cookie.setMaxAge(15*24*3600);
response.addCookie(uname_cookie);
response.addCookie(pwd_cookie);
}
response.sendRedirect("main.jsp");
}else {
response.getWriter().println("用戶名或密碼出錯");
}
}
效果如圖:
login.jpg