1、通过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" version="4.0"> <servlet> <servlet-name>Hello07</servlet-name> <servlet-class>com.csdn.servlet.InitParamServlet</servlet-class> <init-param> <param-name>uname</param-name> <param-value>我是服务器</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Hello07</servlet-name> <url-pattern>/h07</url-pattern> </servlet-mapping> </web-app>
package com.csdn.servlet; import jakarta.servlet.*; import java.io.IOException; public class InitParamServlet extends GenericServlet { private String uname; @Override public void init() throws ServletException { //ServletConfig - 代表当前Servlet的配置信息 ServletConfig config = getServletConfig(); //获取初始化参数 uname = config.getInitParameter("uname"); } @Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { System.out.println(uname); } }
文章来源:https://www.toymoban.com/news/detail-737537.html
2、通过@WebServlet注解方式
package com.csdn.servlet; import jakarta.servlet.*; import jakarta.servlet.annotation.WebInitParam; import jakarta.servlet.annotation.WebServlet; import java.io.IOException; @WebServlet(urlPatterns = "/h07", initParams = { @WebInitParam(name = "uname", value = "我是服务器") }) public class InitParamServlet extends GenericServlet { private String uname; @Override public void init() throws ServletException { //ServletConfig - 代表当前Servlet的配置信息 ServletConfig config = getServletConfig(); //获取初始化参数 uname = config.getInitParameter("uname"); } @Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { System.out.println(uname); } }
文章来源地址https://www.toymoban.com/news/detail-737537.html
到了这里,关于Servlet 初始化参数(web.xml和@WebServlet)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!