找到你要的答案

Q:Unable to set cookie using Java

Q:无法使用java设置cookie

I am trying to set a cookie with user attribute values that I get from an Identity server. I am getting the user attributes but unable to set cookie. Can you someone tell me what is the mistake that I am doing?.

Here is my Java Code:

 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;
    }
}

Here is my 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>

I am getting the following error when I am accessing the application in browser:

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

我试图设置一个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
answer1: 回答1:

I think I know the root cause. Cookies created in the Servlet via response.addCookie won't be available yet on a request dispatch.

You can use response.sendRedirect instead.

Remove these lines:

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

and replace with:

response.sendRedirect("area.jsp");

我想我知道根本原因。建立在Servlet通过response.addcookie不可没有请求调度的饼干。

你可以使用response.sendredirect相反。

删除这些行:

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

并用:

response.sendRedirect("area.jsp");
java  servlets  cookies