标签:
src-> new-> servlet
可见,继承自HttpServlet
dopost doget分别是post请求和get请求时调用的
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * Created by DESTR on 2016/10/10. */ @WebServlet(name = "FirstServlet") public class FirstServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); out.println("<p>Hello post</p>"); out.flush(); out.close(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); out.println("<p>Hello get</p>"); out.flush(); out.close(); } }
url 映射:
在web.xml里添加<servlet-mapping>元素
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>FirstServlet</servlet-name> <servlet-class>FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FirstServlet</servlet-name> <url-pattern>/firstServlet/Hello</url-pattern> </servlet-mapping> </web-app>
<url-pattern>元素表明访问路径
运行后:
【java web学习笔记(2)】first servlet
标签:
原文地址:http://www.cnblogs.com/dreamingsheep/p/5947538.html