Servlet与Jsp学习笔记--3、Cookie & jsp
Problem
You want to use a JSP to set & read a cookie on a client.
Solution
Wrap a JavaBean around the servlet API for creating cookies. Then use the bean in the JSP with the jsp:useBean standard action.
Code(bean)
package pk;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
public class CookieBean {
private Cookie cookie = null;
public CookieBean( ){}
//set the cookie name
public void setName(String name){
if (name == null || (name.equals("")))
throw new IllegalArgumentException(
"Invalid cookie name set in: "+getClass( ).getName( ));
cookie = new Cookie(name,""+new java.util.Date( ).getTime( ));
}
//set the cookie value
public void setValue(String value){
if (value == null || (value.equals("")))
throw new IllegalArgumentException(
"Invalid cookie value set in: "+getClass( ).getName( ));
if (cookie != null)
cookie.setValue(value);
}
public void setMaxAge(int maxAge){
if (cookie != null)
cookie.setMaxAge(maxAge);
}
public void setPath(String path){
if (path == null || (path.equals("")))
throw new IllegalArgumentException(
"Invalid cookie path set in: "+getClass( ).getName( ));
if (cookie != null)
cookie.setPath(path);
}
public void setCookieHeader(HttpServletResponse response){
if (response == null )
throw new IllegalArgumentException(
"Invalid HttpServletResponse set in: "+getClass( ).getName( ));
if (cookie != null)
response.addCookie(cookie);
}
public String getName( ){
if (cookie != null)
return cookie.getName( );
else
return "unavailable";
}
public String getValue( ){
if (cookie != null)
return cookie.getValue( );
else
return "unavailable";
}
public String getPath( ){
if (cookie != null)
return cookie.getPath( );
else
return "unavailable";
}
}
Code(jsp)
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<jsp:useBean id="cookieBean" class="pk.CookieBean" />
<jsp:setProperty name="cookieBean" property="name" value="bakedcookie" />
<jsp:setProperty name="cookieBean" property="value" value="bakedcookie vlu" />
<jsp:setProperty name="cookieBean" property="maxAge" value="<%= (365*24*60*60) %>" />
<jsp:setProperty name="cookieBean" property="path" value="<%= request.getContextPath( ) %>" />
<jsp:setProperty name="cookieBean" property="cookieHeader" value="<%= response %>" />
<html>
<head><title>Cookie Maker</title></head>
<body>
<h2>Here is information about the new cookie</h2>
Name: <jsp:getProperty name="cookieBean" property="name" /><br>
Value: <jsp:getProperty name="cookieBean" property="value" /><br>
Path: <jsp:getProperty name="cookieBean" property="path" />
<P>
<c:choose>
<c:when test="${empty cookie}" >
<h2>We did not find any cookies in the request</h2>
</c:when>
<c:otherwise>
<h2>The name and value of each found cookie</h2>
<c:forEach var="cookieVal" items="${cookie}">
<strong>Cookie name:</strong> <c:out value="${cookieVal.key}" /><br>
<strong>Cookie value:</strong> <c:out value=
"${cookieVal.value.value}" /><br><br>
</c:forEach>
</c:otherwise>
</c:choose>
</body>
</html>
Code(servlet)
import javax.servlet.*;
import javax.servlet.http.*;
public class CookieServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
java.io.IOException {
Cookie cookie = null;
//Get an array of Cookies associated with this domain
Cookie[] cookies = request.getCookies( );
boolean newCookie = false;
//Get the 'mycookie' Cookie if it exists
if (cookies != null){
for (int i = 0; i < cookies.length; i++){
if (cookies[i].getName( ).equals("mycookie")){
cookie = cookies[i];
}
}//end for
}//end if
if (cookie == null){
newCookie=true;
//Get the cookie's Max-Age from a context-param element
//If the 'cookie-age' param is not set properly
//then set the cookie to a default of -1, 'never expires'
int maxAge;
try{
maxAge = new Integer(
getServletContext( ).getInitParameter(
"cookie-age")).intValue( );
} catch (Exception e) {
maxAge = -1;
}//try
//Create the Cookie object
cookie = new Cookie("mycookie",""+getNextCookieValue( ));
cookie.setPath(request.getContextPath( ));
cookie.setMaxAge(maxAge);
response.addCookie(cookie);
}//end if
// get some info about the cookie
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
out.println("<html>");
out.println("<head>");
out.println("<title>Cookie info</title>");
out.println("</head>");
out.println("<body>");
out.println(
"<h2> Information about the cookie named ""mycookie""</h2>");
out.println("Cookie value: "+cookie.getValue( )+"<br>");
if (newCookie){
out.println("Cookie Max-Age: "+cookie.getMaxAge( )+"<br>");
out.println("Cookie Path: "+cookie.getPath( )+"<br>");
}
out.println("</body>");
out.println("</html>");
}
private long getNextCookieValue( ){
//returns the number of milleseconds since Jan 1, 1970
return new java.util.Date( ).getTime( );
}
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
java.io.IOException {
doGet(request,response);
}
}
Jstl
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<html>
<head><title>Cookie display</title></head>
<body>
<h2>Here are all the Available Cookies</h2>
<%-- ${cookies.key}equals the cookie name; ${cookies.value} equals the Cookie object;
${cookies.value.value} returns the cookie value --%>
<c:forEach var="cookies" items="${cookie}">
<strong>
<c:out value="${cookies.key}"/>
</strong>: Object=
<c:out value="${cookies.value}"/>, value=
<c:out value="${cookies.value.value}"/><br />
</c:forEach>
</body>
</html>
目前维护的开源产品:https://gitee.com/475660