Once I got a project of converting PHP project to JAVA project. I don't have any experience  with PHP. I tried to run PHP and Java on single server but I couldn't setup well. Then I just got an Idea of Proxy Servlet and I built one Proxy Servlet to forward requests to another server. In this article I will explain how I did this.
PHP project version is running in remote server. Here Proxy Servlet forward the PHP requests to remote server.

Process

  1. Client (User) sends HTTP requests to Tomacat server
  2. Proxy Filter detects *.php requests and forward it to Proxy Servlet
  3. Proxy servlet creates GET or POST to Remote server based on HTTP request type
  4. Proxy servlet get the response from Remote server and send that response to Client (User) 

ProxyFilter.java

This file is responsible for filtering PHP requests from other requests
package proxy;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class ProxyFilter implements Filter {

    public ProxyFilter() {
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
                     HttpServletRequest req = (HttpServletRequest)request;
                     // Store request path to HTTP Request object
         request.setAttribute("uri", req.getRequestURI().substring(req.getContextPath().length()));
                     // Forward filtered requests to MyProxy servlet
         request.getRequestDispatcher("/ProxyServlet").forward(request, response);       
    }

    public void init(FilterConfig fConfig) throws ServletException {
    }

}

web.xml entry for ProxyFilter.java 

This below web.xml configuration is responsible for sending *.php requests to ProxyServlet.java
  <filter>
    <display-name>ProxyFilter</display-name>
    <filter-name>ProxyFilter</filter-name>
    <filter-class>proxy.ProxyFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>ProxyFilter</filter-name>
    <url-pattern>*.php</url-pattern>
  </filter-mapping>

ProxyServlet.java 

This creates GET and POST request dynamically to remote server

package proxy;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map.Entry;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ProxyServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private final String USER_AGENT = "Mozilla/5.0";   
    public ProxyServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                                //  Create Get request dynamically to remote server
        String url = "http://ipaddress:port/contextpath"+request.getAttribute("uri")+"?"+request.getQueryString();
         
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
 
        // optional default is GET
        con.setRequestMethod("GET");
 
        //add request header
        con.setRequestProperty("User-Agent", USER_AGENT);
 
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);
 
        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response1 = new StringBuffer();
 
        ServletOutputStream sout = response.getOutputStream();
        
        while ((inputLine = in.readLine()) != null) {
            response1.append(inputLine);
            sout.write(inputLine.getBytes());
        }
        in.close();
 
        sout.flush();
 
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                                //  Create Post request dynamically to remote server
        String url = "http://ipaddress:port/contextpath"+request.getAttribute("uri");
        
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
 
        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
 
        StringBuilder sb = new StringBuilder();
          for(Entry<String, String[]> e : request.getParameterMap().entrySet()){
              if(sb.length() > 0){
                  sb.append('&');
              }
              String[] temp =e.getValue();
              for(String s:temp) {
                  sb.append(URLEncoder.encode(e.getKey(), "UTF-8")).append('=').append(URLEncoder.encode(s, "UTF-8"));  
              }
          }
        
        String urlParameters = sb.toString();
 
        
        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
 
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);
 
        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response1 = new StringBuffer();
 
        ServletOutputStream sout = response.getOutputStream();
        
        while ((inputLine = in.readLine()) != null) {
            response1.append(inputLine);
            sout.write(inputLine.getBytes());
        }
        in.close();
 
        sout.flush();
    }

}

web.xml entry for ProxyServlet.java 

  <servlet>
    <description></description>
    <display-name>ProxyServlet</display-name>
    <servlet-name>ProxyServlet</servlet-name>
    <servlet-class>proxy.ProxyServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ProxyServlet</servlet-name>
    <url-pattern>/ProxyServlet</url-pattern>
  </servlet-mapping>

2 comments:

  1. Where would be the entry of the ProxyServlet is made...is it either on the client or on the Remote Server?

    ReplyDelete
    Replies
    1. Here, I have placed this in local server and accessing remote site through this servlet. But you can place it in your own remote server to access another site through your remote server

      Delete

Blogroll

Follow this blog by Email

Popular Posts