Created
March 25, 2015 13:37
-
-
Save freekman/faa8354b35237178edc9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.clouway.servlets; | |
import javax.servlet.ServletException; | |
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 java.io.IOException; | |
import java.security.MessageDigest; | |
import java.security.NoSuchAlgorithmException; | |
import java.text.CollationKey; | |
import java.util.UUID; | |
/** | |
* @author Ivan Genchev ([email protected]) | |
*/ | |
public class TestServlet extends HttpServlet { | |
@Override | |
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { | |
// on login ... | |
String sid = getSid(req); | |
if (sid == null) { | |
UUID uuid = new UUID(10,5); | |
String randomValue = "[email protected]" + uuid.randomUUID().toString() + "abc"; | |
sid = sha1(randomValue); | |
resp.addCookie(new Cookie("sid", sid)); | |
// register session in database (userid, sid, expirationTime); | |
} | |
// on login ... | |
// sessions.refresh(sid); // or redirect to login page in case of expiration or unknown sid was provided | |
// resp.addCookie(new Cookie("test", "value1")); | |
} | |
private String getSid(HttpServletRequest req) { | |
Cookie[] cookies = req.getCookies(); | |
if (cookies == null) { | |
return null; | |
} | |
for (Cookie each : cookies) { | |
if (each.getName().equalsIgnoreCase("sid")) { | |
return each.getValue(); | |
} | |
} | |
return null; | |
} | |
static String sha1(String input) { | |
MessageDigest mDigest = null; | |
try { | |
mDigest = MessageDigest.getInstance("SHA1"); | |
} catch (NoSuchAlgorithmException e) { | |
return ""; | |
} | |
byte[] result = mDigest.digest(input.getBytes()); | |
StringBuffer sb = new StringBuffer(); | |
for (int i = 0; i < result.length; i++) { | |
sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1)); | |
} | |
return sb.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment