解决404报错(关于servlet路径配置)
在servlet上踩的坑真的不少了,其中路径就是最大的麻烦,404的罪魁祸首之一。
目前最新的servlet的版本支持两种不同的配置路径模式
第一种是使用配置文件web.xml(较为原理),第二种是通过注解配置(较为方便)
通过注解配置servlet
首先我们看我们JavaWeb项目的结构,可以看到entrance.jsp是在web.Student目录路径下的
在entrance.jsp中我们书写了一个表单传数据给后端,调用名为StudentInsert.do的servlet。
那其实现在就有问题了,'StudentInsert.do'指的是谁呢?
答案是:指的是urlPatterns为"Student/StudentInsert.do"的HttpServlet.class文件。因此对于entrance.jsp而言StudentInsert.do是同级文件,所以只需要通过"/StudentInsert.do"就可以找到这个servlet了。
使用web.xml配置
web.xml的配置只是代替了@WebServlet注解,在web.xml配置以下映射即可作为代替。class用来指定HttpServlet.class文件的路径,urlPattern的作用和上述一致。
<servlet>
<servlet-name>WhteverYouNameIt</servlet-name>
<servlet-class>com.example.bookstore.student.StudentInsertServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WhteverYouNameIt</servlet-name>
<url-pattern>/Student/StudentInsert.do</url-pattern>
</servlet-mapping>