【发布时间】:2014-11-19 03:36:07
【问题描述】:
我可以在没有 web.xml 和 @WebServlet("/Myservlet") 的情况下在 Eclipse 中运行我的动态 Web 应用程序吗?
在我书中给出的示例中,我有三个 html 文件和一个 servlet,但它没有在 eclipse 中运行。当我运行 Eclipse 时,它给出了一个错误:404 source not found。我还注意到 TrainingServlets(myprojectname)/deployment descriptor/servlets 区域中没有显示 servlet。
他们的代码如下
**login.html**
<!DOCTYPE html>
<html>
<meta charset="ISO-8859-1">
<body>
<h2>Please provide login details</h2>
<form method="post" action="http://localhost/TrainingServlets/myservlet" name="myForm">
<br>User Id:
<input type="text" name="userid"/>
<br>Password:
<input type="password" name="pwd">
<br><br>
<input type="submit" value="Submit Form"/>
</form>
</body>
</html>
**welcome.html**
<!DOCTYPE html>
<html>
<meta charset="ISO-8859-1">
<body>
<h2>You have successfully logged in</h2>
</body>
</html>
**register.html**
<!DOCTYPE html>
<html>
<meta charset="ISO-8859-1">
<body>
<h2>Your login is incorrect.Please register yourself</h2>
<form method="post" action="" name="myform">
<br>Name:
<input type="text" name="userid"/>
<br> Address:
<input type="text" name="address"/>
<br> Phone No:
<input type="text" name="phoneno"/>
<br><br>
<input type="submit" value="Register"/>
</form>
</body>
</html>
**MyServlet**
package com;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Myservlet extends HttpServlet{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
processRequest(request,response);
}
protected void doPOST(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
processRequest(request,response);
}
protected void processRequest(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
String id = request.getParameter("userid");
String pwd = request.getParameter("pwd");
if (id.equals("ali")&& pwd.equals("vu")) {
response.sendRedirect("welcome.html");
}else{
response.sendRedirect("register.html");
response.sendError(response.SC_PROXY_AUTHENTICATION_REQUIRED,"Send Error Demo");
}
}
}
【问题讨论】:
-
Web.xml 就像您的
public static void main(String [] args)用于基于 Java 的 Web 应用程序。绝对必须! -
您可以将 web.xml 替换为 web-app 3.0 以上版本的注释,但您不能完全跳过它。
-
我还有两个问题 1-我每次编辑 servlet 或 html 代码时都需要重新启动 tomcat,因为当我在 html 文件中更新操作时 eclipse 不会自动更新 url 2-现在在包含注释之后我正在运行 servlet eclipse 出现这样的错误“服务器遇到内部错误,导致它无法完成此请求”