servlet原理图
让servlet输出一句话的简单流程
1.继承HttpServlet类并重写doGet和doPost方法,输出信息
- 正常页面
public class helloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//定义文件类型和网页编码
resp.setContentType("text/html");
//定义中文显示
resp.setCharacterEncoding("utf-8");
PrintWriter writer = resp.getWriter();//获取输入流
writer.print("hello Servlet!");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
- 自定义404页面
public class errorServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//定义文件类型和网页编码
resp.setContentType("text/html");
//定义中文显示
resp.setCharacterEncoding("utf-8");
PrintWriter writer = resp.getWriter();
writer.print("<h1>页面不见啦</h1>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
2.配置web.xml文件
<!-- 注册servlet-->
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>helloServlet</servlet-class>
</servlet>
<!-- 注册servlet-->
<servlet>
<servlet-name>error</servlet-name>
<servlet-class>errorServlet</servlet-class>
</servlet>
<!-- 请求servlet路径-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<!-- 请求servlet路径-->
<servlet-mapping>
<servlet-name>error</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
- servlet-name为自定义
- servlet-class为java代码的包路径
- url-pattern为访问路径,访问时其前面会加在tomcat中自定义的虚拟路径
- 注意所有servlet注册步骤要在任意请求路径设置之上,否则会出现The content of element type “web-app” must match编译错误
3.启动tomcat后效果展示
- 输入非\hello访问则输出自定义404页面
-输入http://localhost/s1/hello则可访问欢迎页面