Programmatically adding and configuring web components


The ability to programmatically add a servlet and filter to a context is useful for framework developers.


package com.pkg.servlet30;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebListener;

@WebListener
public class SimpleServletContextListener implements ServletContextListener {

 @Override
 public void contextInitialized(ServletContextEvent sce) {
 ServletContext context = sce.getServletContext();

 String simpleServletName = "simpleServlet";
 String simpleFilterName = "simpleFilter";

 Map<String, String> initParams = new HashMap<String, String>();
 initParams.put("param1", "value1");
 initParams.put("param2", "value2");

 String[] urlPatterns = new String[]{"/simple"};

 ServletRegistration.Dynamic addServlet = context.addServlet(simpleServletName, NewServlet.class);
 addServlet.addMapping(urlPatterns);
 addServlet.setInitParameters(initParams);

 context.addFilter(simpleFilterName, NewFilter.class);

 }

 @Override
 public void contextDestroyed(ServletContextEvent sce) {

 }

}

 

The code is straightforward. It acquires the reference to ServletContext and makes use of the methods addServlet(), addMapping(), setInitParameters() and addFilter() for dynamically adding web components.

Advertisements

Obtain your Lost Java source codes from executable jar or classes


This post describes how you can have your lost source codes from the Jar.

For this we need to decompile all the classes which are present inside the jar to obtain your lost source codes.

A software called “JD-GUI” does this. You just need to open it and drag your executable jar to it and it will show you the decompiled source codes.

You can download the decompiler from http://java.decompiler.free.fr/?q=jdgui. The page contain all relevant information you will need to decompile.

Note : Make sure you don’t use it for illegal purpose. If the codes are obfuscated then decompiler won’t be able to fully decompile the jar.