Hello folks!
Today, I want to share a problem that I was having at work. I have a very legacy application written in JSP using scriplets, tiles and what not they were using in thier stone age era. I wanted to use React for a set of UIs connected via routers. So I created the entire app in React which can be used in the place of certain set of JSPs.
THE PROBLEM
Now the problem was that I had to embed the ReactJS application into the JSP application using the same construct and framework. There were lot of JSPs with different URLs and different parameters passed from servlet context.
If you are wondering how to acheive this in React and Integrating into JSP, please read on.
THE SOLUTION
There are 2 things you need to do to achieve this. React Fix and Servlet Container Fix (tomcat application in my perspective). Lets look at them.
React Fix
The change on react side is to provide the “homepage” property in package.json to enable react build script to consider the same. In my side, the application will be hosted under a folder named “/web/br” hence my package.json looks like below:
Next things to do in React is to provide a basename for all your routes so it start from the JSP you will put the react code in. In my case I am putting react within a jsp named “page2.jsp” under the folder “/web/br” hence my main App.js looks like below:
Now, lets talk about how we can enable the passing of URL parameters from JSP level to React App. When we hit a hit with a url parameters like “?param1=value1” and this page contains a react app, the url params will be passed to props.location.search as it is. The auto parsing into name value is removed from react router hence not automatically possible. However there is a simpler way to get it done. I prefer using URLSearchParams only.
const params = URLSearchParams(props.location.search)
and then you can get the params using the params object. Please refer API guide for the same. [URLSearchParams]
Done with ReactJS fix.
Tomcat Fix
Now, to be able to use the ReactJS complete framework with router, redux and state we need to tell our container to route all requests for a specific pattern to the same JSP. Below is my web.xml for the war project.
It tells the container to route all requests “/br/*” to my servlet which is a jsp embedding the react app.
The last part is simple. Embed the <div> tag for holding react app and set proper width and height for your application.
Well that all for the solution. It works like a charm. Hoping this would help you as well!
Let me know if this worked for you or you employ any other solution.
Please leave a comment and happy hacking!
[출처] http://technology.toraveabout.com/integrate-react-in-jsp-application/

