问题描述
我正在使用 Eclipse IDE 并且正在编写一个 servlet.servlet 应该接受来自 html 文件的值并相应地返回 JSON 响应.
I am using Eclipse IDE and am writing a servlet. The servlet should accept values from an html file and return JSON response accordingly.
我的 doPost() 是:
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());}
}
当我在 Eclipse 中运行这个 servlet 时,我得到一个文件下载对话框.
When I run this servlet in Eclipse I get a file download dialog.
在 Eclipse 外使用 Tomcat 运行时,出现错误:
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)
Server1.doPost(Server1.java:25) 这行是指
The line Server1.doPost(Server1.java:25) refers to
JSONObject json = new JSONObject();
我已将 org.json.jar 添加到构建路径中,并将其添加到 Properties->Configure build path->Deployment assembly
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
推荐答案
不行..方法不对.参考步骤,
对于类路径参考:
在 Eclipse 中右键单击项目 -> Buildpath -> 配置构建路径 -> Java 构建路径(左窗格) -> 库(Tab) -> 添加外部罐子 ->选择您的 jar 并选择 OK.
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:
在eclipse中右键WAR-> Buildpath -> Configure Build path -> Deployment Assembly (left Pane) -> Add -> External file system -> Add -> Select你的罐子 -> 添加 -> 完成.
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.
试试这个.肯定会奏效的.尝试使用 Maven,它会简化您的任务.
Try this. Surely it will work. Try to use Maven, it will simplify you task.
这篇关于java.lang.NoClassDefFoundError: org/json/JSONObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!