在Dynamic Web Project下创建Servlet

在Dynamic Web Project下创建Servlet,第1张

在Dynamic Web Project下创建Servlet

1.首先创建一个Dynamic Web Project

 2.在src下创建包,为了演示我这里创建了一个名为web的包

 3.选中包,右键选择新建,选择新建Servlet,然后取一个名称。(这里我取的名字为HelloServlet1)

   4.此时HelloServlet1类中会自动生成相关代码。 

package web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/HelloServlet1")
public class HelloServlet1 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    
    public HelloServlet1() {
        super();
        // TODO Auto-generated constructor stub
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

 5.现在我们模拟一个get请求,并在浏览器显示"你好呀,陌生人!"。要修改HelloServlet1类中doGet方法的代码。

doGet方法的代码修改后如下:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8");  
        PrintWriter out = response.getWriter();  
        out.println("你好呀,陌生人!");  
        out.close();  
	}

6.配置web.xml文件

 web.xml代码如下:



  Tomcat_web_test
    
   
 HelloServlet1  
    
 web.HelloServlet1  
   
   
   
 HelloServlet1  
   
 /pw  
 

7.运行HelloServlet1类,此时在浏览器中就会显示刚才定义的内容了

 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5684185.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存