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
- Client (User) sends HTTP requests to Tomacat server
- Proxy Filter detects *.php requests and forward it to Proxy Servlet
- Proxy servlet creates GET or POST to Remote server based on HTTP request type
- 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>
Where would be the entry of the ProxyServlet is made...is it either on the client or on the Remote Server?
ReplyDeleteHere, 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
DeleteWeb based business likewise permits investment funds in stock conveying costs. prywatnoscwsieci.pl
ReplyDeleteGreat Article
ReplyDeleteJava Project Ideas for Final Year Students
FInal Year Project Centers in Chennai
JavaScript Training in Chennai
Java Training in Chennai
You are very good at that.
ReplyDeleteคาสิโนออนไลน์ที่น่าเชื่อถือและมีความเป็นมืออาชีพที่สุดในตอนนี้
โปรโมชั่นGclub ของทางทีมงานตอนนี้แจกฟรีโบนัส 50%
เพียงแค่คุณสมัคร สล็อตออนไลน์ กับทางทีมงานของเราเพียงเท่านั้น
ร่วมมาเป็นส่วนหนึ่งกับเว็บไซต์คาสิโนออนไลน์ของเราได้เลยค่ะ
สมัครสล็อตออนไลน์ >>> Goldenslot
สนใจร่วมสนุกกับ คาสิโนออนไลน์ คลิ๊กได้เลย
มีทั้งคาสิโนออนไลน์ หวยออนไลน์ ฟุตบอลออนไลน์ สล็อตออนไลน์ และอื่นๆอีกมากมาย
Thank you for making me aware of this news.
ReplyDeleteหางานราชการ
I do accept as true with all the ideas youíve offered in your
ReplyDeletepost. Essay Writing Service Uk
When you have conducted a research and now need to summarize it and provide major findings in a visually attractive way, a PDF poster is just the thing. Take a look here https://order-essays.com/pdf-poster-service/ so you will know how to make it in the best way.
ReplyDeleteĐại lý vé máy bay Aivivu
ReplyDeletevé máy bay đi Mỹ bao nhiêu tiền
đặt vé máy bay tết 2021
vé máy bay đi Pháp
giá vé đi hàn quốc
vé máy bay đi nhật giá rẻ 2020
vé máy bay đi Anh bao nhiêu
vé máy bay giá rẻ khuyến mãi
vé máy bay đi San Francisco giá rẻ
vé máy bay giá rẻ đi Los Angeles
combo nha trang tháng 7
Mua vé máy bay Aivivu, tham khảo
ReplyDeletevé máy bay đi Mỹ bao nhiêu
chuyến bay từ mỹ về việt nam hôm nay
đặt vé từ nhật về việt nam
khi nào có chuyến bay từ canada về việt nam
Hi Thanks for your post. In those cases remote server returns a response contains for example a javascript which contains server ip and client browser executes it, the second call will post to the remote server directly.
ReplyDeleteShould we process the response and replace the remote server IP with our local IP?
While Hyper-V has limited replication functionality working out of the box.So you have to find a better option. Hyper-V Replication from Nakivo is a crucial part of your data protection plan. It allows you to place a replica environment in a different geographical location to protect against data loss in the event of a site-wide failure or disaster.
ReplyDeletehttps://www.nakivo.com/hyper-v-backup/