java web学习笔记first servlet
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java web学习笔记first servlet相关的知识,希望对你有一定的参考价值。
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学习笔记first servlet的主要内容,如果未能解决你的问题,请参考以下文章