Sunday, 24 April 2016

How to fix problem with getting wrong value from context attribute ?


Problem
My servlet performs addition of 2 request parameters and sets the result in context scope. But sometimes I get wrong results. How can I fix it ?

Scenario
My Application has a servlet, which do addition as shown below and sets the value in context scope. Then, It prints the result.

public void doGet(HttpServletRequest req, HttpServletResponse resp) {
 PrintWriter out = response.getWriter();
 param_1 = request.getParameter("Param1");
 param_2 = request.getParameter("Param2");

 getServletContext.setAttribute("result",(param_1 + param_2));
 out.print("Result =="+getServletContext.getAttribute("result"));
}
But sometimes I get wrong results. How can I fix it?


Solution
1. By making the servletContext Synchronized
synchronized(getServletContext()) { 
  param_1= request.getParameter("Param1"); 
  param_2 =request.getParameter("Param2");
  getServletContext.setAttribute("result",(param_1 + param_2)); 
  response.out.print("Result: "+getServletContext.getAttribute("result")); 
}

- OR -

2. By Putting the 'result' attribute in request scope.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.