Parametri di init in una Servlet

Mattepuffo's logo
Parametri di init in una Servlet

Parametri di init in una Servlet

E' possibile che dobbiate creare delle Servlet che richiedano dei parametri iniziali.

Impostare questi parametri è abbastanza facile, sia se li registriamo nel web.xml che non.

Nel primo caso la sintassi per la Servlet sarà una cosa del genere:

<web-app>
 <servlet>
  <servlet-name>MyServlet</servlet-name>
  <servlet-class>mypackage.MyServlet</servlet-class>
  <init-param>
   <param-name>nome</param-name>
   <param-value>MattePuffo</param-value>
  </init-param>
.......
</servlet>
........
</web-app>

In pratica abbiamo aggiunto il tag init-param.

Se invece non vogliamo registrare le Servlet nel file web.xml, dobbiamo usare l'annotazione @WebInitParam:

@WebServlet(name = "MyServlet", urlPatterns = {"/MyServlet"})
@WebInitParam(name = "nome", value = "MattePuffo")
public class MyServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            out.println("NOME:" + getServletConfig().getInitParameter("nome"));
 
        } finally {
            out.close();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }
}

Indichiamo il nome del parametro e il valore.

Poi sotto lo leggiamo con il metodo getServletConfig, che ritorna un oggetto ServletConfig.

Io ormai preferisco la seconda opzione, e cioè non usare il file web.xml.

Enjoy!!


Condividi

Commentami!