其实,一个Servlet就是一个java文件,所以创建servlet的过程其实就是创建一个类的过程,接下来我们创建一个Servlet。
- 比如我们创建一个类名叫作DateServlet的类,使得这个类继承(extends)HttpServlet
- 重写doGet()和doPost()方法。
-
public class DateServlet1 extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String date=new Date().toLocaleString(); resp.getWriter().print(date); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } }
4.我们写完之后要在web.xml下配置一下它的路径
<servlet> <servlet-name>DateServlet1</servlet-name> <servlet-class>com.ser.DateServlet1</servlet-class> </servlet> <servlet-mapping> <servlet-name>DateServlet1</servlet-name> <url-pattern>/DateServlet1</url-pattern> </servlet-mapping>
假如你不想配置路径的话,你可以通过注解的方式直接写,如下
@WebServlet("/DateServlet") public class DateServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public DateServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String date=new Date().toLocaleString(); PrintWriter out=response.getWriter(); out.print("<h1>"+date+"</h1>"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
但是需要注意的是使用注解的这种方式和配置xml文件的方式不能够同时使用。
时间: 2024-11-18 09:10:33