I am using Eclipse IDE and am writing a servlet. The servlet should accept values from an html file and return JSON response accordingly.
My doPost() is:
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { res.setContentType("application/json"); res.setHeader("Cache-Control", "nocache"); res.setCharacterEncoding("utf-8"); PrintWriter out = res.getWriter(); JSONObject json = new JSONObject(); String un=req.getParameter("uname"); String pw=req.getParameter("password"); if(un.equals("xxx") && pw.equals("xxx")) json.put("result", "success"); else json.put("result", "fail"); out.print(json.toString()); } catch(Exception e){System.out.print( e.getMessage());} }
When I run this servlet in Eclipse I get a file download dialog.
When run outside Eclipse with Tomcat, I get error:
root cause java.lang.NoClassDefFoundError: org/json/JSONObject Server1.doPost(Server1.java:25) javax.servlet.http.HttpServlet.service(HttpServlet.java:647) javax.servlet.http.HttpServlet.service(HttpServlet.java:728) root cause java.lang.ClassNotFoundException: org.json.JSONObject org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1713) org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1558) Server1.doPost(Server1.java:25) javax.servlet.http.HttpServlet.service(HttpServlet.java:647) javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
The line Server1.doPost(Server1.java:25) refers to
JSONObject json = new JSONObject();
I have added the org.json.jar to the build path as well as added it to deployment path in Properties->Configure build path->Deployment assembly
No.. It is not proper way. Refer the steps,
For Classpath reference:
Right click on project in Eclipse -> Buildpath -> Configure Build path -> Java Build Path (left Pane) -> Libraries(Tab) -> Add External Jars -> Select your jar and select OK.
For Deployment Assembly:
Right click on WAR in eclipse-> Buildpath -> Configure Build path -> Deployment Assembly (left Pane) -> Add -> External file system -> Add -> Select your jar -> Add -> Finish.
This is the proper way! Don't forget to remove environment variable. It is not required now.
Try this. Surely it will work. Try to use Maven, it will simplify you task.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With