一个简单的servlet

 1、创建一个自己的servlet文件,继承HttpServlet

 MyServlet.java

 1 package com.jmu.ccjoin.controller;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.annotation.WebServlet;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 /**
12  * Servlet implementation class MyServlet
13  */
14 @WebServlet("/MyServlet")
15 public class MyServlet extends HttpServlet {
16     private static final long serialVersionUID = 1L;
17 
18     /**
19      * Default constructor. 
20      */
21     public MyServlet() {
22         // TODO Auto-generated constructor stub
23     }
24 
25     /**
26      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
27      */
28     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
29         // TODO Auto-generated method stub
30         System.out.println("get");
31 //        response.getWriter().append("Served at: ").append(request.getContextPath());
32     }
33 
34     /**
35      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
36      */
37     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
38         // TODO Auto-generated method stub
39         doGet(request, response);
40     }
41 
42 }

 2、在web.xml容器加入<servlet></servlet>和<servlet-mapping></servlet-mapping>标签,用来交互式地浏览和修改数据,生成动态 Web 内容。

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee"
 4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 5     version="2.5">
 6     <display-name>spring-mybatis</display-name>
 7     <context-param>
 8         <param-name>contextConfigLocation</param-name>
 9         <param-value>classpath:applicationContext.xml</param-value>
10     </context-param>
11     <servlet>
12         <servlet-name>MyServlet</servlet-name>
13         <servlet-class>com.jmu.ccjoin.controller.MyServlet</servlet-class>
14     </servlet>
15     <servlet-mapping>
16         <servlet-name>MyServlet</servlet-name>
17         <url-pattern>/MyServlet1</url-pattern>
18     </servlet-mapping>
19 
20 </web-app>

注意:<servlet-name>和<url-pattern>值不能一样。

<url-pattern>*.action</url-pattern>表示以.action结尾的都执行上面的Myservlet

 

3、启动服务

http://localhost:9906/spring-mybatis/MyServlet1

 

 

posted @ 2018-07-24 19:56  乌瑟尔  阅读(134)  评论(0编辑  收藏  举报