servletconfig example in java


ServletConfig example in java

By using getServletConfig() method of Servlet interface we can get ServletConfig object in java.

Syntax

ServletConfig config = getServletCofig(); 

Configure value in ServletConfig object in web.xml

Below are the configuration which is use to declare some value inside ServletConfig object.

Below configuration should be declared inside <servlet> tag because we already discussed the object of ServletConfig is created per Servlet.

<init-param>
    <param-name>param_name</param-name>
    <param-value>param_value</param-value>
</init-param>

Example

  1. web.xml
  2. ConfigExample.java

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
 <servlet>
 <servlet-name>config</servlet-name>
 <servlet-class>com.javagf.session.ConfigExample</servlet-class>
 <init-param>
    <param-name>URL</param-name>
    <param-value>www.javagf.com</param-value>
 </init-param>
 </servlet>
 <servlet-mapping>
 <servlet-name>config</servlet-name>
 <url-pattern>/ConfigExample</url-pattern>
 </servlet-mapping>
</web-app>

ConfigExample.java

package com.javagf.session;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ConfigExample extends HttpServlet {
 private static final long serialVersionUID = 1L;

 @Override
 protected void service(HttpServletRequest request,
 HttpServletResponse response) throws ServletException, IOException {
 PrintWriter out = response.getWriter();
    ServletConfig config = getServletConfig();
    String websiteName = config.getInitParameter("URL");
    out.println(websiteName);

 }

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

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

}

Output

www.javagf.com






Full-stack web and mobile app development company Contact Us : Skype: indore.webcoder Email: info@w3sparks.com Sales: +91 8085506229