json =>json is not a know variable in the current context< - json

I am working on a project where I need to process JSON string and to test it I write the following code
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ParseException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String res=null;
res= "{\"array\":[{\"title\":\"21 new minister join PM narendra modi's gov , shiv sena boycotts oath ceremony\",\"cat\":\"academic\"}]}";
out.print(res);
JSONObject json = new JSONObject(res);
out.print(json);
}catch(Exception e){
e.printStackTrace();
} finally {
out.close();
}
}
I already check the string res at http://pro.jsonlint.com/ and it approved this String.
I also debug the code and set the breakpoint at out.print(res) and it's working fine and then goes to out.close() without throwing any Exception. The debugger message is same as title "json =>json is not a know variable in the current context<"

if you want to pass your json data to the calling area as response then you need to change
out.print(json);
to
out.write(json.toString());
out.flush();

Related

JSONArray is not consuming full response from HTTPServletResponse

I'm filtering a response from a Filter in my Spring Boot application.
My requirement is to get the response Body. I'm using below method. But when i was debugging the complete response(JSONArray) as an array is missing. the response looks like at the end "crea..." and last part is missing with "]".
I'm using ContentCachingResponseWrap to cache the response.
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
throws IOException, ServletException {
request = (HttpServletRequest) servletRequest;
response = (HttpServletResponse) servletResponse;
ContentCachingResponseWrapper multiReadResponse =new ContentCachingResponseWrapper(response);
chain.doFilter(request, multiReadResponse);
InputStream responseInputStream = multiReadResponse.getContentInputStream();
JSONArray jsonArray = new JSONArray(new JSONTokener(inputStream));
multiReadResponse.copyBodyToResponse();
}
How I am missing the full response.
IDE shows '...' after a certain number of length. you need to increase it if you want to see the full length. This question was answered here. Viewing complete strings while debugging in Eclipse

how to redirect to a new page from servlet

I am sending data to the servlet from login.html using JQuery in json format to the servlet and after matching the record i want to open a new page home.html and i also want to send the data to home.html:
DTORegisteration dto=new DTORegisteration();
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
String id = req.getParameter("id");
String password = req.getParameter("password");
System.out.println("id "+id);
System.out.println("password "+password);
dto.setId(id);
dto.setPassword(password);
String str=new ServiceRegisteration().getDetails(dto);
JSONObject json=new JSONObject();
if(str.equals("success")) {
try { json.put("welcome", "welcome"); json.put("name",
DAORegisteration.name);
}catch(JSONException e) { e.printStackTrace(); }
pw.print(json);
}
}
The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource, that may be servlet, jsp or html file.
if(check your param values here) { // if its as expected
res.sendRedirect("home.html");
}
Actually
we cannot send a post request using sendRedirect() method because as per standards redirect should use get.
You can use RequestDispatcher Class to forward() requests with parameters,
e.g.-
req.setAttribute("Greetings", "Greeting of day");
RequestDispatcher dispatcher = servletContext().getRequestDispatcher("url");
dispatcher.forward(req, res);

Spring Boot replace ServletException response in Filter

I have a Spring Boot Filter that I'm using to authenticate using Jwt. If successful, everything works great and I send out a Json response of my design. However, if the Authorization header is missing or incorrect, I throw a ServletException with a custom message. This results in an ugly Json that looks like this:
{
"timestamp":1453192910756,
"status":500,
"error":"Internal Server Error",
"exception":"javax.servlet.ServletException",
"message":"Invalid Authorization header.",
"path":"/api/test"
}
I wish to customize this Json so it takes the standard form I'm using for all my other responses.
My Filter code is here:
public class JwtFilter extends GenericFilterBean {
#Override
public void doFilter(final ServletRequest req,
final ServletResponse res,
final FilterChain chain) throws IOException, ServletException {
System.out.println("JwtFilter");
final HttpServletRequest request = (HttpServletRequest) req;
final String authHeader = request.getHeader("Authorization");
if (authHeader == null) {
throw new ServletException("Missing Authorization header.");
}
if (!authHeader.startsWith("Bearer ")) {
throw new ServletException("Invalid Authorization header.");
}
final String token = authHeader.substring(7);
try {
final Claims claims = Jwts.parser().setSigningKey("secretkey")
.parseClaimsJws(token).getBody();
request.setAttribute("claims", claims);
}
catch (final SignatureException e) {
throw new ServletException("Invalid token.");
}
chain.doFilter(req, res);
}
}
I tried using a wrapper to wrap the response but that didn't work. Another SO post said the response was not changeable but that wouldn't even make sense.
I think the correct way would be to edit the ServletResponse res but I couldn't get it to work.
Thanks!
EDIT: Kind of hacky but it works. If there's a better way, please answer:
public class JwtFilter extends GenericFilterBean {
#Override
public void doFilter(final ServletRequest req,
final ServletResponse res,
final FilterChain chain) throws IOException, ServletException {
System.out.println("JwtFilter");
final HttpServletRequest request = (HttpServletRequest) req;
final String authHeader = request.getHeader("Authorization");
if (authHeader == null) {
res.setContentType("application/json;charset=UTF-8");
res.getWriter().write(ExceptionCreator.createJson("Missing Authorization header."));
return;
}
if (!authHeader.startsWith("Bearer ")) {
res.setContentType("application/json;charset=UTF-8");
res.getWriter().write(ExceptionCreator.createJson("Invalid Authorization header."));
return;
}
final String token = authHeader.substring(7);
try {
final Claims claims = Jwts.parser().setSigningKey("secretkey")
.parseClaimsJws(token).getBody();
request.setAttribute("claims", claims);
}
catch (Exception f) {
res.setContentType("application/json;charset=UTF-8");
res.getWriter().write(ExceptionCreator.createJson("Invalid token."));
return;
}
chain.doFilter(req, res);
}
}
In general, wrapping the response and then modifying the response output stream after the call to doFilter is the correct approach, e.g.
PrintWriter out = response.getWriter();
CharResponseWrapper wrapper = new CharResponseWrapper(
(HttpServletResponse)response);
chain.doFilter(request, wrapper);
CharArrayWriter caw = new CharArrayWriter();
caw.write("your json");
response.setContentLength(caw.toString().getBytes().length);
out.write(caw.toString());
out.close();
Taken from Oracle JavaEE 5 Tutorial
Nevertheless, your usecase seems more appropriate for being dealt with in a RestController handler method, possibly in conjunction with an #ExceptionHandler(ServletException.class) annotated method. This would be a more generic approach that allows you to harness the power of Spring's content negotiation to deal with the JSON serialization.

Uncaught exception from servlet - JSON GAE deployment issue

I have created a script on browser that calls a servlet which is deployed on GAE. The servlet uses Datastore.
Everytime servlet is called I receive the following error
Uncaught exception from servlet java.lang.NoClassDefFoundError: org/json/JSONException
For development I use eclipse and Maven.
In pom.xml I have already included org.json 20090211 and javax.validation.
UPDATE
In order to better clarify my question I am posting code from servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
StringBuilder sb = new StringBuilder();
BufferedReader br = request.getReader();
String str;
while ((str = br.readLine()) != null)
{
sb.append(str);
}
String jsonResp = sb.toString();
JSONParser gparser = new JSONParser();
The problem appears on the last line, so I am posting code from JSONParser
public class JSONParser {
public ArrayList<String> ReturnGoogleJSON(String ResponseString) throws IOException {
ArrayList<String> Row = new ArrayList<String>();
try {
JSONObject rootObject = new JSONObject(ResponseString); // Parse the JSON to a JSONObject
JSONArray rows = rootObject.getJSONArray("items") ; // Get all JSONArray rows
for(int i=0; i < rows.length(); i++) { // Loop over each each row
JSONObject element = rows.getJSONObject(i); // Get the element object
Row.add(element.getString("tag"));
Row.add(element.getString("link"));
Row.add(element.getString("priority"));
}
} catch (JSONException e) {
e.printStackTrace();
}
return Row;
}
}
Could anyone help me with this kind of error?
Thank you in advance.
Check war/WEB-INF/lib directory of your project in eclipse before upload and make sure that json and other dependent files are present in this directory.
Edit:
You may want to check:
GAE - ClassNotFoundException after deployment to Appspot server
http://javanto.com/blog/2012/01/11/gae-eclipse-maven-2-0/

How do I send java string array to sencha touch list?

How do I send java string array to sencha touch list. I am using a servlet and gson and I get the error at the line JsonObject creation.
import com.google.gson.JsonObject;
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String[] anArray;
anArray = new String[11]; //assign each element of array later
JsonObject myObj = new JsonObject();
PrintWriter out = response.getWriter();
for(int i = 0; i <11; i++){
myObj.addProperty(anArray[i], i);
}
out.println(myObj.toString());
out.close();
}
eg:-
The following link uses jdbc to serve it via a database.
http://www.mysamplecode.com/2012/05/sencha-touch-list-example.html
Similar to this but the data is to be taken from the array of strings.
Set your content type to application/json on line 4 -
response.setContentType("application/json");
and make sure you are sending properly formatted JSON from your servlet.