Servlet 第一课:简单Servlet Demo,写一个Hello Servlet

今天和大家一起写一个简单的Hello Servlet。

目录结构如下:

展示效果:


详细步骤:

01.新建WebProject:

Servlet 第一课:简单Servlet Demo,写一个Hello Servlet_第1张图片

02.创建MyServlet.java.(这里面要特别注意

super.doGet(req, resp)
<pre name="code" class="java">super.doPost(req, resp);
//上面两句必须注释,不能调用,否者会出错。

 ) 
 

package com.goxuexi.demo;

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

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

public class MyServlet extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		//super.doGet(req, resp);
		
		//logic
		//HttpServletRequest 请求类
		//HttpServletResponse 响应类
		
		PrintWriter out = resp.getWriter();
		out.print("Hello Servlet");
		out.close();
		
		
		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		//super.doPost(req, resp);
		doGet(req, resp);
	}

}

03.在Web.xml中添加Servlet的注册。

  <servlet>
  <servlet-name>MyServlet</servlet-name>
  <servlet-class>com.goxuexi.demo.MyServlet</servlet-class>
  
  
  </servlet>
  <servlet-mapping>
  <servlet-name>MyServlet</servlet-name>
  <url-pattern>/hello.html</url-pattern>
  </servlet-mapping>

上面注意两点:

①:servlet-name必须一样。

②url-pattern中必须以/开头,且后面是什么不会做限制。

③:网络访问地址为:http://localhost:8080/ServletDemo/hello.html







你可能感兴趣的:(java,servlet,servlet,web.xml,hello,Servlet入门)