servlet的使用

本文介绍了Servlet的使用步骤,包括创建继承自HttpServlet的Java类,覆写service方法实现业务逻辑,以及在web.xml文件中进行配置以确保服务器能正确找到Servlet,强调了web.xml配置对于Servlet安全性的重要性。
摘要由CSDN通过智能技术生成

第一个JavaEE代码

package com.dym.servlet;

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 MyServlet extends HttpServlet{
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		resp.getWriter().write("this is my first servlet.");
		System.out.println("this is my first servlet.");
	}
	
	
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  	<!-- 配置servlet -->
	  	<!-- 配置servlet类路径 -->
	  	<servlet>
	  		<servlet-name>my</servlet-name>
	  		<servlet-class>com.dym.servlet.MyServlet</servlet-class>
	  	</servlet>
	  	<!-- 配置访问方式 -->
	  	<servlet-mapping>
	  		<servlet-name>my</servlet-name>
	  		<url-pattern>/my</url-pattern>
	  	</servlet-mapping>
</web-app>

package com.dym.servlet;

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 MyServlet2 extends HttpServlet{
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.getWriter().write("this is my second servlet");  // write("这里面不允许写中文")  
		System.out.println("MyServlet2.service()");
	}
}

 


web.xml   使服务器能够找到对应的servlet,最大的好处:安全性

web.xml 文件的配置是为了保护 servlet

servlet的使用:


1、 创建普通的 java 类并继承 HttpServlet
2、 覆写 service 方法
3、 在 service 方法中书写逻辑代码即可

4、 在 webRoot 下的 WEB-INF 文件夹下的 web.xml文件中配置 servlet

Servlet 的 web.xml 配置:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值