- 前言
- 第一部分 核心实现
- 第 1 章 Spring 整体架构和环境搭建
- 第 2 章 容器的基本实现
- 第 3 章 默认标签的解析
- 第 4 章 自定义标签的解析
- 第 5 章 bean 的加载
- 第 6 章 容器的功能扩展
- 第 7 章 AOP
- 第二部分 企业应用
- 第 8 章 数据库连接 JDBC
- 第 9 章 整合 MyBatis
- 第 10 章 事务
- 第 11 章 SpringMVC
- 第 12 章 远程服务
- 第 13 章 Spring 消息
11.3.1 servlet 的使用
我们同样还是以最简单的 servlet 来快速体验其用法。
(1)建立 servlet。
public class MyServlet extends HttpServlet{
public void init(){
System.out.println("this is init method");
}
public void doGet(HttpServletRequest request, HttpServletResponse response){
handleLogic(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response){
handleLogic(request,response);
}
private void handleLogic(HttpServletRequest request, HttpServletResponse response){
System.out.println("handle myLogic");
ServletContext sc = getServletContext();
RequestDispatcher rd = null;
rd = sc.getRequestDispatcher("/index.jsp"); //定向的页面
try {
rd.forward(request, response);
} catch (ServletException | IOException e) {
e.printStackTrace();
}
}
麻雀虽小,五脏俱全。实例中包含了对 init 方法和 get/post 方法的处理,init 方法保证在在 servlet 加载的时候能做一些逻辑操作,而 HttpServlet 类则会帮助我们根据方法类型的不同而将逻辑引入不同的函数。在子类中我们只需要重写对应的函数逻辑便可,如以上代码重写了 doGet 和 doPost 方法并将逻辑处理部分引导至 handleLogic 函数中,最后,又将页面跳转至 index.jsp。
(2)添加配置。
为了使 servlet 能够正常使用,需要在 web.xml 文件中添加以下配置:
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>test.servlet.MyServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
配置后便可以根据对应的配置访问响应的路径了。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论