Servlet系列兩種創(chuàng)建方式
一、使用web.xml的方式配置(Servlet2.5之前使用)
在早期版本的Java EE中,可以使用XML配置文件來(lái)定義Servlet。在web.xml文件中,可以定義Servlet的名稱、類(lèi)名、初始化參數(shù)等。然后,在Java代碼中實(shí)現(xiàn)Servlet接口,并覆蓋其中的doGet()或doPost()方法來(lái)處理請(qǐng)求。
web.xml
<?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_4_0.xsd" id="WebApp_ID" version="4.0"> <display-name>java-servlet-demo02</display-name> <!-- servlet配置 --> <servlet> <!-- 名稱 --> <servlet-name>WebXmlServlet</servlet-name> <!-- servlet全稱類(lèi)名 --> <servlet-class>com.mcode.servlet.controller.WebXmlServlet</servlet-class> <!-- 啟動(dòng)的優(yōu)先級(jí),數(shù)字越小越先起作用 --> <load-on-startup>1</load-on-startup> </servlet> <!-- 映射配置 --> <servlet-mapping> <!-- 對(duì)應(yīng)名稱 --> <servlet-name>WebXmlServlet</servlet-name> <!-- 資源匹配規(guī)則:精確匹配 --> <url-pattern>/webxml</url-pattern> </servlet-mapping> </web-app>
WebXmlServlet
package com.mcode.servlet.controller; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * ClassName: WebXmlServlet * Package: com.mcode.servlet.controller * Description: * * @Author robin * @Version 1.0 */ public class WebXmlServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //設(shè)置編碼方式 resp.setCharacterEncoding("UTF-8"); //指定客戶端解碼方式 resp.setHeader("content-type", "text/html;charset=UTF-8"); //輸出 resp.getWriter().write("基于webxml方式配置的servlet"); } }
效果圖
url-pattern匹配規(guī)則
匹配規(guī)則 | 值 | 取值說(shuō)明 |
---|---|---|
精確匹配 | /具體的名稱 | 只有url路徑是具體的名稱的時(shí)候才會(huì)觸發(fā) Servlet |
后綴匹配 | *.xxx | 只要是以xxx結(jié)尾的就匹配觸發(fā)Servlet |
通配符匹配 | /* | 匹配所有請(qǐng)求,包含服務(wù)器的所有資源 |
通配符匹配 | / | 匹配所有請(qǐng)求,包含服務(wù)器的所有資源,不包括.jsp |
load-on-startup說(shuō)明
元素標(biāo)記容器是否應(yīng)該在web應(yīng)用程序啟動(dòng)的時(shí)候就加載這個(gè) servlet
它的值必須是一個(gè)整數(shù),表示 servlet被加載的先后順序
如果該元素的值為負(fù)數(shù)或者沒(méi)有設(shè)置,則容器會(huì)當(dāng)serv1et被請(qǐng)求時(shí)再加載
如果值為正整數(shù)或者0時(shí),表示容器在應(yīng)用啟動(dòng)時(shí)就加載并初始化這個(gè) servlet,值越小, servlet的優(yōu)先級(jí)越高,就越先被加載。值相同時(shí),容器就會(huì)自己選擇順序來(lái)加載
二、使用注解的方式配置(Servlet3.0后支持,推薦)
從Java EE 5開(kāi)始,可以使用注解來(lái)創(chuàng)建Servlet。通過(guò)在Java類(lèi)上添加@WebServlet注解,可以將該類(lèi)作為Servlet來(lái)處理。在注解中,可以指定Servlet的名稱、URL映射等。
AnnotationServlet
package com.mcode.servlet.controller; 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; /** * ClassName: AnnotationServlet * Package: com.mcode.servlet.controller * Description: * * @Author robin * @Version 1.0 */ @WebServlet("/annotation") public class AnnotationServlet extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //設(shè)置編碼方式 response.setCharacterEncoding("UTF-8"); //指定客戶端解碼方式 response.setHeader("content-type", "text/html;charset=UTF-8"); //輸出 response.getWriter().write("基于注解方式配置的servlet"); } }
注意:response中的set的一些方法必須寫(xiě)在
response.getWriter()
之前It does not set the response's characterencoding if it is called after getWriterhas been called or after the response has been committed.
效果圖
@WebServlet注解
屬性:下面是一些常用屬性,value和url一般是必須的,但是二者不能共存,若同時(shí)指定,一般自動(dòng)忽略value。
屬性名 | 類(lèi)名 | 屬性描述 |
---|---|---|
name | String | 指定servlet的name屬性,等價(jià)于<servlet-name> ,若沒(méi)有指定,則默認(rèn)是類(lèi)的全限定名 |
value | String[] | 等價(jià)于urlPatterns,兩者不能共存 |
urlPatterns | String[] | 指定一組servlet的url的匹配模式,等價(jià)于<url-pattern> |
loadOnStartup | int | 指定servlet的加載順序,等價(jià)于<load-on-startup> |
initParams | WebinitParams[] | 指定一組初始化參數(shù),等價(jià)于<init-params> |
asyncSupported | boolean | 申明servlet是否支持異步操作模式,等價(jià)于<async-supported> |
displayName | String | servlet的顯示名,等價(jià)于<display-name> |
description | String | servlet的描述信息,等價(jià)于<description> |
@WebServlet 屬于類(lèi)級(jí)別的注解,標(biāo)注在繼承了 HttpServlet 的類(lèi)之上。常用的寫(xiě)法是將 Servlet 的相對(duì)請(qǐng)求路徑(即 value)直接寫(xiě)在注解內(nèi),
@WebServlet(urlPatterns = “/MyServlet”)。
@WebServlet(“/MyServlet”) 省略了 urlPatterns 屬性名
如果 @WebServlet 中需要設(shè)置多個(gè)屬性,則屬性之間必須使用逗號(hào)隔開(kāi).
通過(guò)實(shí)現(xiàn) Serlvet 接口或繼承 GenericServlet 創(chuàng)建的 Servlet 類(lèi)無(wú)法使用 @WebServlet 注解。
使用 @WebServlet 注解配置的 Servlet 類(lèi),不要在 web.xml 文件中再次配置該 Servlet 相關(guān)屬性。若同時(shí)使用 web.xml 與 @WebServlet 配置同一 Servlet 類(lèi),則 web.xml 中 的值與注解中 name 取值不能相同,否則容器會(huì)忽略注解中的配置。
三、封裝BaseServlet
package com.mcode; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.lang.reflect.Method; /** * ClassName: BaseServlet * Package: com.mcode * Description: * * @Author: robin * @Version: v1.0 */ public abstract class BaseServlet extends HttpServlet { @Override public void service(HttpServletRequest request, HttpServletResponse response) { try { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); String methodName = request.getParameter("method"); if (methodName == null || methodName.trim().isEmpty()) { throw new RuntimeException("您沒(méi)有傳遞 method 參數(shù)! 無(wú)法確定您想調(diào)用的方法"); } Class<? extends BaseServlet> classz = this.getClass(); Method method = classz.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class); method.setAccessible(true);//開(kāi)啟暴力反射 method.invoke(this, request, response); } catch (Exception e) { e.printStackTrace(); } } }
四、測(cè)試
UserServlet
package com.mcode; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; /** * ClassName: UserServlet * Package: com.mcode * Description: * * @Author: robin * @Version: v1.0 */ @WebServlet("/user") public class UserServlet extends BaseServlet{ public void getList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String method = request.getParameter("method"); HttpSession session = request.getSession(); session.setAttribute("method",method); request.getRequestDispatcher("index.jsp").forward(request, response); } }
index.jsp
引入jsp-api依賴
<dependency> <groupId>jakarta.servlet.jsp</groupId> <artifactId>jakarta.servlet.jsp-api</artifactId> <version>3.1.1</version> </dependency>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <body> <a href="/user?method=getList" rel="external nofollow" >user</a> <%=session.getAttribute("method") %> <% out.println(session.getAttribute("method")); %> </body> </html>
到此這篇關(guān)于Servlet系列兩種創(chuàng)建方式的文章就介紹到這了,更多相關(guān)Servlet創(chuàng)建 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- myeclipse創(chuàng)建servlet_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
- IDEA創(chuàng)建Servlet并配置web.xml的實(shí)現(xiàn)
- 使用IDEA創(chuàng)建servlet?JavaWeb?應(yīng)用及使用Tomcat本地部署的實(shí)現(xiàn)
- servlet創(chuàng)建web后端程序的示例代碼
- Servlet的兩種創(chuàng)建方式(xml?注解)示例詳解
- IDEA創(chuàng)建Servlet程序的兩種實(shí)現(xiàn)方法
- IDEA2023創(chuàng)建MavenWeb項(xiàng)目并搭建Servlet工程的全過(guò)程
相關(guān)文章
mybatisPlus自定義批量新增的實(shí)現(xiàn)代碼
這篇文章主要介紹了mybatisPlus自定義批量新增的實(shí)現(xiàn)代碼,代碼簡(jiǎn)單易懂,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11Flink實(shí)戰(zhàn)之實(shí)現(xiàn)流式數(shù)據(jù)去重
流式數(shù)據(jù)是一種源源不斷產(chǎn)生的數(shù)據(jù),本文探索了一種流式大數(shù)據(jù)的實(shí)時(shí)去重方法,不一定適用于所有場(chǎng)景,不過(guò)或許可以給面對(duì)相似問(wèn)題的你一點(diǎn)點(diǎn)啟發(fā),2025-03-03SpringBoot常見(jiàn)問(wèn)題小結(jié)
這篇文章主要介紹了SpringBoot常見(jiàn)問(wèn)題小結(jié),需要的朋友可以參考下2017-07-07mybatis對(duì)傳入基本類(lèi)型參數(shù)的判斷方式
這篇文章主要介紹了mybatis對(duì)傳入基本類(lèi)型參數(shù)的判斷方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03SSM框架實(shí)現(xiàn)分頁(yè)和搜索分頁(yè)的示例代碼
本篇文章主要介紹了SSM框架實(shí)現(xiàn)分頁(yè)和搜索分頁(yè)的示例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-03-03詳解Springboot如何通過(guò)注解實(shí)現(xiàn)接口防刷
本文主要為大家介紹一種極簡(jiǎn)潔、靈活通用接口防刷實(shí)現(xiàn)方式、通過(guò)在需要防刷的方法加上@Prevent?注解即可實(shí)現(xiàn)短信防刷,感興趣的可以了解一下2022-09-09