1. 程式人生 > >JavaWeb_利用Cookie技術實現自動登入

JavaWeb_利用Cookie技術實現自動登入

//------------------------------------儲存Cookie-------------------------------
package com.MainServlet;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
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.Part;

/**
 * Servlet implementation class MainServlet
 */
@WebServlet(name = "/MainSerlet", urlPatterns = { "/Login", "/Result", "/SH" })
@MultipartConfig(location = "D:\\", fileSizeThreshold = 10 * 1024)
public class MainServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String username = null;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public MainServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		String uri = request.getRequestURI();
		if (uri.endsWith("/Login")) {
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			String checked = "checked";
			if (!username.equals("Admin") || !password.equals("123")) {
				response.sendRedirect("Login.jsp");
			}else{
				if ((request.getParameter("checkbox") != null)
						&& (request.getParameter("checkbox").equals("1"))) {
					Cookie namecookie = new Cookie("username", username);
					Cookie wordcookie = new Cookie("password", password);
					Cookie checkedcookie = new Cookie("checked", checked);
					namecookie.setMaxAge(3600);
					wordcookie.setMaxAge(3600);
					checkedcookie.setMaxAge(3600);
					response.addCookie(namecookie);
					response.addCookie(wordcookie);
					response.addCookie(checkedcookie);
					
				}
				request.getSession().setAttribute("AAA", username);
				response.sendRedirect("LoginPage.jsp");
			}
		} else if (uri.endsWith("/Result")) {
			Result(request, response);
		} else if (uri.endsWith("/SH")) {
			SH(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	protected void Result(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String quest1 = request.getParameter("quest1");
		// System.out.println(quest1);
		String quest2 = request.getParameter("quest2");
		String[] quest3 = request.getParameterValues("quest3");
		String quest4 = request.getParameter("quest4").trim();
		int score = 0;
		if (quest1 != null && quest1.equals("1")) {
			score += 25;
		}
		if (quest2 != null && quest2.equals("3")) {
			score += 25;
		}
		if (quest3 != null && quest3.length == 2 && quest3[0].equals("1")
				&& quest3[1].equals("3")) {
			score += 25;
		}
		if (quest4 != null && quest4.equals("HttpServlet")
				|| quest4.equals("javax.servlet.http.HttpServlet")) {
			score += 25;
		}
		// System.out.println(score);
		request.getSession().setAttribute("score", score);
		request.getSession().setAttribute("username", username);
		response.sendRedirect("Score.jsp");
	}

	protected void SH(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String path = "D:" + "\\" + request.getParameter("number");
		Part p = request.getPart("filename");
		String message = null;
		File f = new File(path);
		if (!f.exists()) {
			f.mkdirs();
		}
		// String h = p.getHeader("content - disposition");
		// System.out.println(h);
		// String name = h.substring(h.lastIndexOf("\\")+1, h.length()-1);
		// System.out.println("aaa");
		p.write(path + "\\" + request.getParameter("number") + ".JPG");
		message = "檔案上傳成功";
		double size = p.getSize() * 1.0 / 1024 / 1024;
		request.getSession().setAttribute("message", message);
		request.getSession().setAttribute("username", username);
		request.getSession().setAttribute("size", size + "");
		response.sendRedirect("SHS.jsp");
	}

}
<pre name="code" class="java"><!------------------------讀取Cookie----------------------------------->
<%@ 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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="Test.css" type="text/css" rel="stylesheet"></link>
<title>登入介面</title>
</head>
<body>
	<%
		String value1 = "";
		String value2 = "";
		String value3 = "";
		Cookie cookie = null;
		boolean flag = false;
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				cookie = cookies[i];
				if (cookie.getName().equals("username")) {
					value1 = cookie.getValue();
				}
				if (cookie.getName().equals("password")) {
					value2 = cookie.getValue();
				}
				if (cookie.getName().equals("checked")) {
					value3 = cookie.getValue();
				}
			}
			
		}
	%>
	
	<div class="Login" style="background: url('Images/Face.jpg');">
		<h1 align="center" style="margin-top: 80px">登入介面</h1>
		<form action="Login" method="post">
			<table border="1" align="center"
				style="border-collapse: collapse; width: 300px; height: 120px; margin-top: 60px;">
				<tr>
					<td align="center" style="font-size: 15px;">使用者名稱</td>
					<td><input type="text" name="username" value="<%=value1%>" /></td>
				</tr>
				<tr>
					<td align="center" style="font-size: 15px;">密    碼</td>
					<td><input type="password" name="password" size="21"
						value="<%=value2%>" /></td>
				</tr>
				<tr>
					<td> </td>
					<td style="font-size: 15px;"><input type="checkbox"
						name="checkbox" value="1" size="25" checked="<%=value3%>"/>自動登入</td>
				</tr>
				<tr>
					<td></td>
					<td><input type="submit" value="登入" />        <input
						type="reset" value="重置" /></td>
				</tr>
			</table>
		</form>
	</div>
</body>
</html>