新增cookie

十里相思發表於2019-01-24
package com.neu.servlet;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.neu.entity.Emp;
import com.neu.entity.dept;

/**
 * Servlet implementation class loginServlet
 */
@WebServlet("/login")
public class loginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		//處理
		if("admin".equals(username)&&"123".equals(password)) {
			//新增cllkie
			Cookie cookie=new Cookie("username",username);
			cookie.setMaxAge(60*2);
			response.addCookie(cookie);
			
			//把登入名放到request中
			request.setAttribute("username", username);
			List<dept> list=new ArrayList();
			dept dept=new dept(10,"人力資源部","瀋陽");
			list.add(dept);
			dept=new dept(20,"生產部","大連");
			list.add(dept);
			dept=new dept(30,"銷售部","瀋陽");
			list.add(dept);
			request.setAttribute("list", list);
			
			
			//請求轉發到jsp頁
			request.getRequestDispatcher("/main.jsp").forward(request, response);
		}else {
			//重定向回原來的登入頁
			response.sendRedirect(request.getContextPath()+"/login.jsp?error=true");
		}
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
<%@ 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 o=request.getParameter("error");
		if(o!=null){
			out.println("使用者名稱或密碼錯誤!");
		}
	%>
	<%
		Cookie[] cookies=request.getCookies();
		String username="";
		if(cookies!=null){
			for(Cookie cookie:cookies){
				if(cookie.getName().equals("username")){
					username=cookie.getValue();
					break;
				}
			}
		}
		
	%>
	<form action="/javawebdemo3/login" method="get">
	<table>
		<tr>
		<td>使用者名稱:</td>
		<td><input type="text" name="username" value="<%=username %>"> </td>
		</tr>
		<tr>
		<td>密碼:</td>
		<td><input type="password" name="password"> </td>
		</tr>
		<tr>
		<td colspan="2">
		<input type="submit" value="登入">
		<input type="reset" value="重填">
		</td>
		</tr>
		</table>
	</form>
</body>
</html>

相關文章