第二章My first servlet file

My first servlet file

1.在webapps中创建servle项目
1)在项目文件夹中添加index.html文件以及WEB-INF文件夹(文件夹名字必须为WEB-INF)
2)在WEB-INF文件夹中创建classes文件夹已经lib文件夹,并且创建web.xml配置文件,使其格式保持与Tomcat中项目格式一样,使服务器能正确找到路径
3)classes 文件夹中存放我们写的java文件已经编译后的.class文件;lib文件夹中存放servlet运行所需要的环境
4)配置classpath(方便在电脑的任何地方都能编译java文件)在这里插入图片描述
2.在classes中创建一个java文件

package cn.webapp;
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 ServletDemo1 extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("hello!!");
		/*out.flush();
		out.close();*/
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

3.在web.xml中配置servlet

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   version="2.5"> 
  <servlet>
    <servlet-name>Servlet1</servlet-name>
    <servlet-class>ServletDemo</servlet-class>  
  </servlet>
  <servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/start</url-pattern>
  </servlet-mapping>
</web-app>

注意:

别忘了配置虚拟目录`<Context path="/first" docBase="D:\myweb"/>`
虚拟目录配置详解请看第一章
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值