无法使用Java设置cookie

时间:2015-10-07 23:56:09

标签: java servlets cookies

我正在尝试使用从Identity Server获取的用户属性值设置cookie。我正在获取用户属性但无法设置cookie。你能告诉我我在做什么错吗?

这是我的Java代码:

 public class CircleArea extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("Server name is: " + request.getServerName());
        System.out.println("Requesting cookies...");
        Cookie[] cookies = request.getCookies();
        String targetResourceURL = request.getRequestURL().toString();
        if (cookies == null) {
            System.out.println("Cookies are not present");
            System.out.println("Requesting reference value...");
            String refValue = request.getParameter("REF");
            if (refValue == null) {
                System.out.println("Reference value is null...");
                System.out.println("Redirecting to URL: " + Configurations.PF_BASE_URL + ":"
                        + Configurations.PF_PRIMARY_SSL_PORT + Configurations.PF_START_SSO_ENDPOINT + "?"
                        + "PartnerIdpId=" + Configurations.PARTNER_ENTITY_ID + "&TargetResource=" + targetResourceURL);
                response.sendRedirect(Configurations.PF_BASE_URL + ":" + Configurations.PF_PRIMARY_SSL_PORT
                        + Configurations.PF_START_SSO_ENDPOINT + "?" + "PartnerIdpId="
                        + Configurations.PARTNER_ENTITY_ID + "&TargetResource=" + targetResourceURL);
            } else {
                try {
                    System.out.println("Reference Value is: " + refValue);
                    System.out.println("Getting user attributes...");
                    Map<String, String> userAttrs = UserAttributes.pickUpAttributesFromReferenceIdAdapter(refValue);
                    for(Map.Entry<String, String> userAttr : userAttrs.entrySet()){
                        System.out.println("Key: " + userAttr.getKey() + " Value: " + userAttr.getValue());
                    }
                    System.out.println("Creating cookie with user attribute displayname Value...");
                    System.out.println("Cookie name is : " + targetResourceURL.substring(38));
                    Cookie cookie = new Cookie(targetResourceURL.substring(38), userAttrs.get("displayName"));
                    System.out.println("Setting cookie path to :" + targetResourceURL);
                    cookie.setPath(targetResourceURL);
                    System.out.println("Setting cookie age...");
                    System.out.println("Cookie will be deleted atonce when the browser is closed");
                    cookie.setMaxAge(-1);
                    response.addCookie(cookie);
                    RequestDispatcher dispatch = request.getRequestDispatcher("/area.jsp");
                    dispatch.forward(request, response);
                } catch (Throwable any) {
                    any.printStackTrace();
                }
            }
        }
    }

    public double calculateArea() {
        Random rnd = new Random();
        int radius = rnd.nextInt(15);
        double area = Math.pow((double) radius, (double) 2) * Math.PI;
        return area;
    }
}

这是我的area.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" session="false"%>
<%@ page import="com.pegright.seleniumproject.controllers.CircleArea"%>
<%@ page import="javax.servlet.http.Cookie;"%>
<!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=ISO-8859-1">
<title>Area</title>
</head>
<body>
    <%
        CircleArea area = new CircleArea();
        Cookie[] cookie = request.getCookies();
        for (int i = 0; i < cookie.length; i++) {
            out.println("Welcome " + cookie[i].getValue());
        }
        out.println("Area of a random circle: " + area.calculateArea());
    %>
</body>
</html>

我在浏览器中访问应用程序时收到以下错误:

Oct 07, 2015 5:50:40 PM org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet jsp threw exception
java.lang.NullPointerException
    at org.apache.jsp.area_jsp._jspService(area_jsp.java:76)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:486)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:411)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:338)
    at com.pegright.seleniumproject.controllers.CircleArea.service(CircleArea.java:54)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

org.apache.jasper.JasperException: java.lang.NullPointerException
    at org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:549)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:486)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:411)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:338)
    at com.pegright.seleniumproject.controllers.CircleArea.service(CircleArea.java:54)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at org.apache.jsp.area_jsp._jspService(area_jsp.java:76)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    ... 33 more

1 个答案:

答案 0 :(得分:0)

我想我知道根本原因。通过response.addCookie在Servlet中创建的Cookie在请求发送时仍然无法使用。

您可以改用response.sendRedirect。

删除以下行:

RequestDispatcher dispatch = request.getRequestDispatcher("/area.jsp");
dispatch.forward(request, response);

并替换为:

response.sendRedirect("area.jsp");