菜鸟发帖, 自编第一个servlet程序,访问出现404错误

「已注销」 2016-07-17 11:58:26
各位csdn网友大家好,本人最近自学servlet,菜鸟一枚,在自学了tomcat服务器之后,入手编写第一个servlet程序,就遇到了很大的麻烦,现将问题贴出来,希望各位网友能够帮忙解答,在此,表示非常感谢!!
1、编写servlet程序
HelloServlet.java文件内容如下:虽然目前不太熟悉这些语法,但是直接抄来李孝祥老师的例子,应该没有错。
package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloServlet {
public void Service(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException{

PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<font size=30 color=red>www.baidu.com</font>");
out.println("<marquee>"+new java.util.Date()+"</marquee>");
out.println("</html>");
}
}
编译,生产HelloServlet.class文件,
2、配置tomcat服务器
2.1 配置虚拟子目录
为了方便,直接在server.ml文件中<host>中添加如下语句,
<Context path="/servlet" docBase="F:\servlet" debug="0"/>
配置一个servlet虚拟子目录,真实路径为:F:\servlet。为了验证配置的正确性,在F:\servlet\index.html文件中写入一句话:
F:\servlet\index.html
开启tomcat服务器,在浏览器地址栏中输入http://localhost:8080/servlet/index.html路径,访问结果如下:

说明虚拟子目录配置成功。
2.2 注册和映射servlet
在F:\servlet目录下创建WEB-INF,在WEB-INF目录下创建web.xml文件和classes文件夹,将编译好的HelloServlet.class文件拷贝到classes文件夹下。
打开web.xml文件,编辑内容为:
<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">

<servlet>
<servlet-name>AnyName</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>AnyName</servlet-name>
<url-pattern>/domo/hello.html</url-pattern>
</servlet-mapping>

</web-app>
关闭文件,重启tomcat服务器,在地址栏中输入:http://localhost:8080/servlet/demo/hello.html,出现如下内容:


在网上搜了很多资料,大部分没有使用虚拟子目录的方式访问,我觉得其实都是一样的。也曾经试过在tomcat应用程序目录webapps目录下创建一个servlet文件,将上面WEB-INF文件夹直接拷贝过来,通过浏览器访问,效果也是一样的,目前不知道真正问题所在,希望大家能够指点指点,在此感谢大家!!
...全文
128 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
「已注销」 2016-07-17
  • 打赏
  • 举报
回复
能否详细说明,刚开始接触servlet,对很多概念不大了解,谢谢!!
阳光越来越暖 2016-07-17
  • 打赏
  • 举报
回复
WEB-INF下的网页不能直接访问 得通过Servlet跳转

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧