Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package cookiejar;
- import java.io.IOException;
- import java.io.PrintWriter;
- import javax.servlet.ServletException;
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.Cookie;
- /**
- * Servlet implementation class CredentialsCookie
- */
- @WebServlet("/CredentialsCookie")
- public class CredentialsCookie extends HttpServlet {
- private static final long serialVersionUID = 1L;
- /**
- * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- response.setContentType("text/html");
- PrintWriter out = response.getWriter();
- boolean checkCookie = false;
- Cookie cookie = null;
- Cookie[] cookies = request.getCookies();
- if(cookies!=null) {
- for(int i = 0; i < cookies.length; i++) {
- if(cookies[i].getName().equals("username")) {
- cookie = cookies[i];
- cookie.getValue();
- checkCookie = true;
- break;
- }
- }
- }
- if(!checkCookie) {
- String username = request.getParameter("username");
- if (username != null && username.length() > 0) {
- String userValue = request.getParameter("userValue");
- Cookie userCookie = new Cookie(username, userValue);
- userCookie.setPath("/");
- userCookie.setMaxAge(7*24*60*60);
- response.addCookie(userCookie);
- }
- String password = request.getParameter("password");
- if (password != null && password.length() > 0) {
- String passwordValue = request.getParameter("passwordValue");
- Cookie pwCookie = new Cookie(password, passwordValue);
- pwCookie.setPath("/");
- pwCookie.setMaxAge(7*24*60*60);
- response.addCookie(pwCookie);
- }
- }
- out.println("<html><title>Login</title>"
- + "<form name='Login' action='CredentialsCookie' method='POST'>"
- + "Username:<br> <input type='text' name='username' autofocus><br> "
- + "Password:<br> <input type='text' name='password'><br><br>"
- + "<input type='submit' value='Submit'></form></html>");
- }
- /**
- * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- doGet(request, response);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement