我可以在没有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");
}
}
}
答案 0 :(得分:3)
如果您的html文件位于根文件夹中(如果您使用的是eclipse的标准项目,则位于WebContent
中),请将您的HTML表单更改为:
<form method="post" action="myservlet" name="myForm">
另一方面,如果您使用Servlet 3.0(例如Tomcat 7),如果您使用注释,则可以避免文件web.xml
:
@WebServlet(value="/myservlet", name="Myservlet")
public class Myservlet extends HttpServlet { ... }
如果应用程序服务器支持Servlet 3.0,则可以使用注释。请参阅Servlet 3.0 tutorial。
中的详情遵循Java EE 1.5概述的路径,Servlet规范3.0大量使用注释来声明Servlet,过滤器,监听器和安全性。配置文件web.xml现在是可选的。
答案 1 :(得分:0)
在servlet 3.0之前是不可能的。现在不需要web.xml。
但是如果您在servlet 3.0之前使用的是版本,则需要它。
然后,Web.xml是部署描述符,它向服务器通知存在的servlet。
简而言之,它是您的Web应用程序的核心。没有这个,您的应用程序无法运行。
答案 2 :(得分:0)
取决于你的意思&#34;运行&#34;。您可以在servlet中放置一个main方法并以这种方式运行它,但是如果要在servlet上执行HTTPRequest,则必须在web.xml中指定它或使用servlet注释。否则,服务器将无法将传入请求映射到该servlet。