java.lang.nullpointerexception when creating array of cookie objects in servlet - java

have a html form where 4 option buttons are there. when user click submit button servlet wil execute and need to create cookie of selected options.
i wrote following code, but when i "INITIALIZE ARRAY OF OBJECTS OF COOKIES" the nullpointerexception comes.WITHOUT COOKIE INITIALIZATION my program works well.
Cookie[] cookie=null; int i=1;
while(paramNames.hasMoreElements()){
String paramName = (String)paramNames.nextElement();
String[] paramValues = req.getParameterValues(paramName);
String paramValue = paramValues[0];
cookie[i] = new Cookie(paramName, paramValue); **//ERROR IS HERE**
cookie[i].setMaxAge(60*60*24);
resp.addCookie(cookie[i]);
i++}
I CHECKeD THE VALUES "paramName, paramValue". i got Correct Answer without Cookie. what will be the error when i initialize array of objects of cookie like this?

cookie is null and you are trying to access an index of an array which is null.
You should initialize it this way:
Cookie[] cookie = new Cookie[someNumber];

You have not initialized the array of Cookies.
use Cookie[] cookie=new Cookie[SIZE] instead of Cookie[] cookie=null to initialize it before assigning a value to it.

Related

Null pointer exception in passing checkbox value

I made an index page in which you take the value of checkbox and pass it on to a file named AddToWork.java but it is showing null pointer exception. There is some problem in passing the value of the checkbox. Kindly help. Here is the code snipped for index page
<td>
<center>
<form action="addtowork?id2=<%=mail.getTempToken()%>" method="post">
<input type="submit" value="Add to my work">
<input type="checkbox" name="flag" value="flag">High Priority</form>
</center></td>
for AddToWork.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
EmailDesc mail = new EmailDesc();
String imp = new String();
imp = (String) request.getParameter("flag");
String thisid = request.getParameter("id2");
Home home = new Home();
User user = new User();
user = (User) request.getSession().getAttribute("user");
mail = home.getEmail(thisid, user);
home.givePermanentToken(mail,thisid);
if (imp.equals("flag")){
System.out.println("Priority Changed to " + mail.getPriority() + "!");
}
response.sendRedirect("index1.jsp");
}
If I remove the if statement in addtowork.java, the code runs perfectly.
it is because your "imp" Object is pointing to nothing (null) & it is throwing an exception. use "Yoda notation" like so
if("flag".equals(imp)){
// your code
}
this removes the possibility of getting a null pointer exception
Case 1: name.equals("Java") Compare unknown value with known value.
We are comparing name(unknown) value with another string Java(known) value. name will be decided based on some database call, calling another method, etc... It may possible you get null value of name and possible chances of java.lang.NullPointerException or you have to check explicitly for null value of name.
Case 2: "Java".equals(name) Compare known value with unknown value.
We are comparing Java(known) value with another string name(unknown) value. Same way name will be decided based on some database call, calling another method, etc... But equals and equalsIgnoreCase method of String will handle the null value and you don't have to check explicitly for null value of name.
In your case
/* You are getting `null` for variable `imp` */
imp = (String) request.getParameter("flag");
Change
if (imp.equals("flag")){
System.out.println("Priority Changed to " + mail.getPriority() + "!");
}
to
if ("flag".equals(imp)){
System.out.println("Priority Changed to " + mail.getPriority() + "!");
}
Case I : When you are submitting the form with checking the check box , it will work because the value is set in request parameter flag
Case II : When you are submitting the form without checking the "priority" check box then the request parameter sets to null and later you calling the equal method on null on if condition. so please use
if("flag".equals(imp))
Note :- It's bad practice to create string using new
String imp = new String(); //bad don't use this
String imp = ""; //use in this way

What to do if cookie already exists?

In my application I have a dropdownlist and when the user clicks on an item is redirects them to a certain page. In this servlet I create a cookie with there selected item which contains the value of the drop-down list(So when they return the the previous page that item will be selected in the drop-down list)
What I want to know different values may be selected at different times it there a way to modify the cookie for that drop-down list or do I have to create a new one each time. I cant see that as being a sustainable way of doing it?
You can edit the cookie by getting it from the request and assigning the new value:
Cookie[] cookies = request.getCookies();
Cookie dropDownCookie = null;
for (Cookie cookie : cookies) {
if(cookie.getName().equals("DROP_DOWN_COOKIE")){
dropDownCookie = cookie;
}
}
if(dropDownCookie!=null){
dropDownCookie.setValue("THE NEW VALUE");
response.addCookie(dropDownCookie);
}

Delete a cookie by its value

How do I delete a cookie by its value?
In my.jsp page I am setting the cookie
String timeStamp = new SimpleDateFormat("dd:MM:yyyy_HH:mm:ss:SSS").format(Calendar.getInstance().getTime());
timeStamp = timeStamp + ":" + System.nanoTime();
String loc = "/u/poolla/workspace/FirstServlet/WebContent/WEB-INF/"+timeStamp;
Cookie cookie = new Cookie("path", loc);
Multiple users will have cookies with the same name but different loc values,
So, How do I get the cookie value in servlet.java and delete a particular loca value cookie??
Cookies are not same for each user. Generally cookies are tied to the client/user/browser which is accessing the JSP/application and each client can have a cookie value of its own.
When you delete a cookie you just delete it for the client which has made the request to your application. Rest of the clients will still have their own cookie without any effect in the value. Hence, you need not to worry about deleting a cookie may affect multiple users.
In order to delete a cookie, first get all the cookies from request and delete the cookie which has particular name/value.
public void delete(MyType instance) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("test")) {
cookie.setValue(null);
cookie.setMaxAge(0);
cookie.setPath(theSamePathAsYouUsedBeforeIfAny);
response.addCookie(cookie);
}
}
}
}
You will need to call getCookies() on the request and loop through them until you find the one you're looking for.
here is a little simple example tha might help you
//declaring a cookie
Cookie cookie = new Cookie(name, value);
//getting the cookie name
String name = cookie.getName()
//getting the cookie value
String value= cookie.getValue();

Getting wrong value from session in javascript, How to use session in javascript?

I am using following code to get session variable value in javascript embedded in a JSP:
var numberOfPages= '<%=session.getAttribute("numberOfPage")%>';
I am getting a wrong value (old value) when I hit the page for the first time but when I refresh the page, then I'm getting the correct value. Please help me.
Servlet code:
HttpSession session = request.getSession(false);
if( session == null ) {
session = request.getSession(true);
}
String numberOfPage = Integer.toString(noOfPages);
session.removeAttribute("numberOfPage");
session.setAttribute("numberOfPage", numberOfPage);
Jsp (javascript) Code:
if(<%=session.getAttribute("numberOfPage")%>!= null)
numberOfPages= '<%=session.getAttribute("numberOfPage")%>';
session.getAttribute() returns an Object, try to cast it.

How to get asp.net created cookies in Java servlet?

How to get ASP.NET created cookies in a Java servlet?
This is My Cookie In ASP.NET
emid=11&eud=11&euid=33zU4Yq/p3k=&euseremail=F/zVoXtd4NoAd7yj6Z47gxFVaMCMYha/La6IzlC+xQo=&euserid=33zU4Yq/p3k=&emdn=testing
But when I try To Call it in Servlet it only prints: emid [only print the starting string before first equal to (=) sign]
I'm using the following code in Servlet to print cookies..
Cookie cookie = null;
Cookie[] cookies = null;
cookies = request.getCookies();
if( cookies != null ){
out.println("<h2> Found Cookies Name and Value</h2>");
for (int I = 0; I < cookies.length; I++){
cookie = cookies[I];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" \n");
}
}else{
out.println(
"<h2>No cookies founds</h2>");
}
Whats wrong with my code?
The equals character is a reserved character in a cookie value. The specification compliant way of fixing this is to quote the cookie value by surrounding it with double quotes. However, some browsers don't handle this very well. If you are using Tomcat you can set the system property -Dorg.apache.tomcat.util.http.ServerCookie.ALLOW_EQUALS_IN_VALUE=true to allow equals in cookie values.

Categories

Resources