javaweb入门实例---servlet例子

1.编写servlet: TreeDataServlet.java

 package com.maggie.tree; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class TreeDataServlet extends HttpServlet{ private String getData(){ StringBuffer sb = new StringBuffer(); sb.append("Hello~First Servlet!"); return sb.toString(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub // super.doGet(req, resp); String data = this.getData(); resp.setContentType("text/html;charset=GBK"); resp.getOutputStream().write(data.getBytes("GBK")); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub // super.doPost(req, resp); } }

2.配置web.xml

treeServlet com.maggie.tree.TreeDataServlet 1 treeServlet /treeServlet

3.测试,访问地址:http://localhost:8080/fistServlet/treeServlet

 

页面显示如下:

Hello~First Servlet!

你可能感兴趣的:(javaweb)