JavaServlet原理
servlet原理
servlet是由web服务器调用
1.1Mapping问题
-
一个servlet可以指定一个映射路径
<!-- 一个servlet对应一个Mapping:映射--> <servlet-mapping> <servlet-name>helloServlet</servlet-name> <!-- 请求路径--> <url-pattern>/hello</url-pattern> </servlet-mapping>
-
一个servlet可以指定多个映射路径
<servlet-mapping> <servlet-name>helloServlet</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>helloServlet</servlet-name> <url-pattern>/hello2</url-pattern> </servlet-mapping>
-
一个servlet可以指定通用映射路径
<servlet-mapping> <servlet-name>helloServlet</servlet-name> <url-pattern>/hello/*</url-pattern> </servlet-mapping>
注意下面这样重启服务就不会默认进入到index.jsp页面了(不推荐使用)
<servlet-mapping> <servlet-name>helloServlet</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping>
-
指定一些后缀或者前缀等等
<!-- 可以自定义后缀实现请求映射 注意点:*前民不能加项目映射的路径 /hello/*.do 是不可以的 但是/hello/hi.do是可以的 --> <servlet-mapping> <servlet-name>helloServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
-
优先级问题
制定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求
<servlet> <servlet-name>helloServlet</servlet-name> <servlet-class>com.zyy.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>helloServlet</servlet-name> <url-pattern>/hello/hi.do</url-pattern> </servlet-mapping> <!-- 404--> <servlet> <servlet-name>errorServlet</servlet-name> <servlet-class>com.zyy.servlet.ErrorServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>errorServlet</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping>
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Hello World!</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>你好!</h1>"); out.println("</body>"); out.println("</html>"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
本文来自博客园,作者:Cn_FallTime,转载请注明原文链接:https://www.cnblogs.com/CnFallTime/p/15937394.html