servlet出现404问题深入剖析
问题原因:
404(资源未找到)
1、客户端发起的请求中,输入的url中的servlet拼写错误,在web.xml中的找不到对应的url-pattern(注意区分大小写)。
2、客户端发起的请求中,输入的url中的项目名称错误(注意区分大小写)。
关于路径错误进行分析
1.在web_INF下的xml文件中设置访问路径:
<servlet>
<servlet-name>listAllStudentServlet</servlet-name>
<servlet-class>QuaryCase.ListAllStudentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>listAllStudentServlet</servlet-name>
<url-pattern>/listAllStudent</url-pattern>
</servlet-mapping>
这几条语句应该都知道是什么意思,这里
重点分析:< url-pattern>/listAllStudent</ url-pattern>
的设置
①若 jsp文件在web根目录下:路径名为 /listAllStudent。
- 其中/代表tomcat项目路径(不管项目结构是什么,第一个/都是这个意思),如(http://localhost:8080/web_war_exploded)
- listAllStudent 为映射名,可以自定义,但是表单
<form>
的action=” “或者html超链接标签<a>
的href=”“必须与其一致。 如:
<form action="**listAllStudent**" method="Get" >
<a href="**listAllStudent**">listAllStudents</a>
② 若jsp文件在web下的子文件夹中(/javaWEB_MVC/seatchTest.jsp):
(1)xml的路径名需为 /javaWEB_MVC/listAllStudent。
因为从seatchTest.jsp提交到Servlet时,默认的根目录时seatchTest.jsp的根目录,
也就是”http://localhost:8080/web_war_exploded/javaWEB_MVC/“,
但是在xml文件中,/
代表的是”http://localhost:8080/web_war_exploded/“,
所以还要再加上javaWEB_MVC/
。
xml:
<servlet>
<servlet-name>listAllStudentServlet</servlet-name>
<servlet-class>QuaryCase.ListAllStudentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>listAllStudentServlet</servlet-name>
<url-pattern>/javaWEB_MVC/listAllStudent</url-pattern>
</servlet-mapping>
则jsp:
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="listAllStudent">listAllStudents</a>
</body>
</html>
(2)或者xml中路径名为:/listAllStudent:
xml:
<servlet>
<servlet-name>listAllStudentServlet</servlet-name>
<servlet-class>QuaryCase.ListAllStudentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>listAllStudentServlet</servlet-name>
<url-pattern>/listAllStudent</url-pattern>
</servlet-mapping>
则jsp:
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="../listAllStudent">listAllStudents</a>
</body>
</html>
因为xml文件里servlet的访问路径为:http://localhost:8080/web_war_exploded/listAllStudent
而<a href="listAllStudent">listAllStudents</a>
跳转到的servlet路径为:http://localhost:8080/web_war_exploded/javaWEB_MVC/listAllStudent
所以超链接要返回到上级目录,即: <a href="../listAllStudent">listAllStudents</a >
第二种方法:使用注解(这样就更简单了)
在当前servlet中添加注解,这样就不需要配置xml文件了。使用注解方法只能针对servlet 3.0才能用。
对应①:jsp文件在web根目录下
servlet.java
package QuaryCase;
import java.util.List;
@WebServlet("/listAllStudent")
jsp:
<a href="listAllStudent">listAllStudents</a>
对应② :jsp文件在web的子文件夹下
servlet.java
package QuaryCase;
import java.util.List;
@WebServlet("/javaWEB_MVC/listAllStudent")
”/javaWEB_MVC/listAllStudent“ 相当于 ”http://localhost:8080/web_war_exploded/javaWEB_MVC/listAllStudent“
jsp:
<a href="listAllStudent">listAllStudents</a>
超链接从jsp提交,默认路径是”http://localhost:8080/web_war_exploded/javaWEB_MVC/“,那么这里的超链接地址就是:”http://localhost:8080/web_war_exploded/javaWEB_MVC/ listAllStudents“;