Transferred from: Http://blog.csdn.net/qq924862077/article/details/52883973?locationNum=2&fps=1
In the previous servlet we initialized some parameters that were configured in Web. xml, and since servlet3.0 provided us with annotations @webservlet and @webinitparam,@ Webservlet is used to configure the properties of a servlet, @WebInitParam is used to configure some initialization properties.
@WebServlet and @webinitparam are used as Follows:
packageroseindia.net; Importjava.io.IOException; Importjava.io.PrintWriter; Importjavax.servlet.ServletConfig; Importjavax.servlet.ServletException; Importjavax.servlet.annotation.WebServlet; Importjavax.servlet.annotation.WebInitParam; Importjavax.servlet.http.HttpServlet; Importjavax.servlet.http.HttpServletRequest; Importjavax.servlet.http.HttpServletResponse; @WebServlet (name= "webinitparamexample", Urlpatterns = {"/hello"}, initparams={@WebInitParam (name= "Site:", value= "http://roseindia.net"), @WebInitParam (name= "Rose", value= "India"), } ) public classWebinitparamexampleextendshttpservlet{ public voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {response.setcontenttype ("text/html"); PrintWriter out=Response.getwriter (); Out.println ("); ServletConfig Config=Getservletconfig (); String PValue= Config.getinitparameter ("Site:"); Out.println ("Param Value:" +pValue); String pValue1= Config.getinitparameter ("Rose"); Out.println ("<br>param Value:" +pValue1); Out.close (); } }
If configured in Web. xml, the following is True:
<?xml version= "1.0" encoding= "UTF-8"?> <web-app id= "webapp_id" version= "2.4" xmlns= "http://java.sun.com/xml /NS/J2EE "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http://java.sun.com/xml/ns/ Java http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd "> <display-name>servletannotationexample</ display-name> <servlet> <servlet-name>WebInitParamExample</servlet-name> <s ervlet-class>roseindia.net.webinitparamexample</servlet-class> <init-param> <param-name>site:</param-name> <param-value> http//roseindia.net</param-value></init-param> </servlet> <servlet-mapping> <servlet-name>webinitparamexample< ;/servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app>
servlet3.0 Annotations @webinitparam and @webservlet