fbpx

Deploy React JS in Tomcat

Deploy React JS in Tomcat

Deploy react JS  in tomcat or any servlet container is a challenge and bit tricky. There is an issue in one of my app that I am developing. I have used Browser Router in my app.

So the issue is there were no errors as such in the code but nothing is loading.I see a White Screen with no errors. I checked the console and saw its throwing  404 for some of my bundled static resources.

A strange behavior is noticed, if I run the app in web pack dev server same code works fine and routers works fine as well.But same behavior is not observed once I deploy to tomcat.

So after a lot of research and thinking, i  got the solution. As you know BrowserRouter uses HTML5 history API to keep your UI in sync with URL.So, For example, if you used React Router with a route for,/todos/42 the webpack development server will respond properlylocalhost:3000/todos/42, but a production build as above will not.Check out this link to understand the problem.



React router takes the root URL  by default, hence able to serve static resources from tomcat ROOT directory.But Once you deploy the build files to a different path is not able to serve static content.

In this article, we will see how we can configure our code and deploy in tomcat successfully.We will use Maven to create a war of our UI and deploy in tomcat. Deploy React JS in Tomcat needs some changes in router property .

Tools Used:-

  • Maven 3.3.9
  • Npm

Pom.xml:-

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.frugalis</groupId>
    <artifactId>Frugalis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <npm.output.directory>build</npm.output.directory>
    </properties>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.1.1</version>
                <configuration>
                    <webResources>
                        <resource>
                            <directory>${npm.output.directory}</directory>
                        </resource>
                    </webResources>
                    <webXml>${basedir}/web.xml</webXml>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.3.2</version>
                <executions>
                    <execution>
                        <id>npm run build (compile)</id>
                        <goals>
                            <goal>exec</goal>
                        </goals>
                        <phase>compile</phase>
                        <configuration>
                            <executable>npm</executable>
                            <arguments>
                                <argument>run</argument>
                                <argument>build</argument>
                            </arguments>
                        </configuration>
                    </execution>

                </executions>

                <configuration>
                    <environmentVariables>
                        <CI>false</CI>
                        <!-- The following parameters create an NPM sandbox for CI -->
                        <NPM_CONFIG_PREFIX>${basedir}/npm</NPM_CONFIG_PREFIX>
                        <NPM_CONFIG_CACHE>${NPM_CONFIG_PREFIX}/cache</NPM_CONFIG_CACHE>
                        <NPM_CONFIG_TMP>${project.build.directory}/npmtmp</NPM_CONFIG_TMP>
                    </environmentVariables>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>local</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>exec-maven-plugin</artifactId>

                        <configuration>
                            <environmentVariables>
                                <PUBLIC_URL>http://localhost:8080/${project.artifactId}</PUBLIC_URL>
                                <REACT_APP_ROUTER_BASE>/${project.artifactId}</REACT_APP_ROUTER_BASE>
                            </environmentVariables>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>

        <profile>
            <id>prod</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>exec-maven-plugin</artifactId>

                        <configuration>
                            <environmentVariables>
                                <PUBLIC_URL>http://frugalisminds.com/${project.artifactId}</PUBLIC_URL>
                                <REACT_APP_ROUTER_BASE>/${project.artifactId}</REACT_APP_ROUTER_BASE>
                            </environmentVariables>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>

Web.xml:-

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
	      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	      xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
	      http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
	      version="2.4">

  <display-name>frugalis</display-name>

  <error-page>
    <error-code>404</error-code>
    <location>/index.html</location>
  </error-page>
  
</web-app>

We Configure BrowserRouter in our app as follows, provide full path of your context as follows. Above code redirects all errors to index.html.
<BrowserRouterbasename={process.env.REACT_APP_ROUTER_BASE||''}>





App.jsx:-

import React, { Component } from 'react';
import {
    BrowserRouter,
    Link,
    Route,
    Switch
} from 'react-router-dom';

import Home from './Home.jsx';
import ContactUs from './ContactUs.jsx';
import Blog  from './Blog.jsx';

class App extends Component {
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <h2>Welcome to React</h2>
        </div>
        <BrowserRouter basename={process.env.REACT_APP_ROUTER_BASE || ''}>
          <div>
            <ul className="nav">
              <li><Link to="/">Home</Link></li>
              <li><Link to="/blog">Blog</Link></li>
              <li><Link to="/contactUs">Contact Us</Link></li>
            </ul>
            <Switch>
              <Route path="/blog" component={Blog}/>
              <Route path="/contactUs" component={ContactUs}/>
              <Route path="/" component={Home}/>
            </Switch>
          </div>
        </BrowserRouter>
      </div>
    );
  }
}

export default App;

We declared three routes in our sample app, Our maven script will replace the basename with actual tomcat url context.process.env.REACT_APP_ROUTER_BASE  will be replaced by maven .

Basically, when you type the URL by hand, by default the server will look for a file with that path, stored on its disk — if not found, it will show a 404 error. What you want to do is internally redirect the request for static resources to the index of your application.

Now we run

npm install
mvn clean install

OutPut:-

Deploy React JS Tomcat

Download Code

Note:-   For a simple application built using create-react-app if we can to configure and Deploy React JS in Tomcat. We need to configure a relative path which can be done from your package.json. by declaring home page as follows.let’s say we have an app folder inside web app in tomcat known assampleapp.We want to have our deployed app in that location. So the relative path configuration would be as below.

{
  "name": "App",
  "version": "0.1.0",
   "homepage":"http://localhost:8080/sampleapp",
  "private": true,
  "dependencies": {
    "react": "^16.3.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

Most of the hosting services  which supports javascript and html supports reactjs hosting  as well , as it runs on client side .So to deploy react app it is not difficult but your app needs a backend server as well .Hence complexity increases and i faced this while deploying a react app to a  servlet container like tomcat . Let me know in your commnets if you have faced any similar sort of trouble deploying react app.

Posts You Want to Check :-




React JS Components

React JS Components:-

Components let you split the UI into independent and reusable pieces of code. Components help to render your UI, rather describes what should exactly appear on the screen. Lets write a simple react component and see how it works?

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Welcome" />
      <Welcome name="Frugalis" />
      <Welcome name="Minds" />
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

This is a basic way of writing components, there is an advanced and good way of writing react components as well. We will see that later.Now lets’ see what happens here.

  1. There is a component created named as Welcome
  2. There is another component named as,App inside this Welcome is called multiple times.
  3. React calls the componentWelcome from the componentApp with as{name: 'Welcome'} the props.

The above code looks good, but this is not good practice generally followed in applications. Let’s write a cleaner code using ES6.




Project Structure:-

React Components



Let’s Write Our Welcome Component, create a file named Welcome.jsx.

import React from 'react';
class Welcome extends React.Component {
   constructor(props) {
        super(props);
       
  }
  render(){
    return <div>{this.props.name}</div>;
  }
}

export default Welcome;

Now,React.Component is an abstract base class present in React and must define at least render() method, Constructor and export as module

Let’s write another component App.jsx, create a file named App.jsx:-

import React from 'react';
import Welcome from './Welcome.jsx'
class App extends React.Component {
   constructor(props) {
        super(props);
       
  }
  render(){
    return <div>
      <Welcome name="Welcome" /> 
      <Welcome name="Frugalis" /> 
      <Welcome name="Minds" />
    
        </div>
  }
}

export default App;

Here we are calling our Welcome component multiple times, in react we are allowed to have only one parent tag and multiple child elements can reside inside this.Now we are going to wire up all our components.

Create a file named main.js:-

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App />, document.getElementById('root'));

So we wired up our App component to render in our browser, you can see the difference between writing code in a conventional way and using ES6 way.

How do you decide what components to be created for your UI?

A simple thumb rule is that if your part of UI is used several times make it a reusable component. If there are complex UI sections then also we can break our UI into components.

Each component has several “lifecycle methods” that you can override to run code at particular times in the process. Methods prefixed with will are called right before something happens, and methods prefixed with did are called right after something happens.

In next article, we will see How we deploy react app to Servlet Containers.

Download Code 

React JS Setup using Npm Babel and Webpack

React JS – introduction to JSX and Internal Working



React JS – introduction to JSX and Internal Working

React JS – introduction to JSX and Internal Working:-

What is JSX:

React JS – introduction to JSX and Internal Working, We will learn about JSX.JSX is One of basic aspect in react.It acts a  kind of templating in react, but it is more than that. JSX is a syntactical extension to javascript, it helps to build your UI components. JSX is a preprocessor step that adds XML syntax to JavaScript. You can definitely use React without JSX but JSX makes React a lot more elegant.We must remember always React is a Library not a framework.

const element = <div class="wrapper">
                <h1 color="blue" className="sidebar" >Hello, world! </h1>
                <h2 color="blue" className="sidebar" >Hey Guys</h2>
                </div>;

This code above is a combination of javascript and HTML. In case of normal coding perspective, it’s unusual. You can’t have javascript and Html together in a single place, but react doesn’t separate the technologies by putting markup and logic in two different places. Instead of that, it separates the concerns, and the concern here is How easy and How good is our UI?





Fundamentally the above JSX code gets compiled as:-

"use strict";

var element = React.createElement(
  "div",
  { "class": "wrapper" },
  " ",
  React.createElement(
    "h1",
    { color: "blue", className: "sidebar" },
    "Hello, world!"
  ),
  React.createElement(
    "h2",
    { color: "blue", className: "sidebar" },
    "Hey Guys"
  )
);

Please Visit this link here to try and convert JSX to Browser compatible javascript.Babel converts the JSX to React.CreateElement code .Babel Converts Jsx Code in to a Javascript code that the browser understands.Look at the example below.

React JS Jsx internal Working



Few Points about JSX for Interview in Short:-

  1. JSX is different from react, its an EmacScript feature provided to you to write your view.
  2. There can be only one parent and multiple child elements/components inside JSX.
  3. You must have an opening and closing elements in the parent component/element of JSX.
  4. We Can embed any javascript expression in JSX  Any javascript expression and operator operations are valid in JSX.

Inline Styles in JSX:- With inline styles, you have to option to combine CSS syntax with JSX code.

var myStyle= {
	color:'red',
	backgroundColor:'black',
	fontWeight:'bold'
};

var element= <div style={myStyle}>Hello World</div>;

Conclusion:-

We must always keep in mind “JSX doesn’t Separates Technologies it separates Concerns” .It helps us to write reusable code . Look at next Article on How to Setup React JS using JSX and Babel.

 

“Its Always Better To Learn and Share Instead Learn and Forget” 







Top 5 Programming Languages to Learn in 2018

Top 5 Programming Languages to Learn in 2018:-

In this competitive market, to be able to compete and stay on top of everything is never easy. Today we are going to check out top 5 Programming languages to learn in 2018. It is completely based upon my experience with different developers and Google search trends.

We have to keep yourself updated to stay on the top of the latest trend of technology and business.There are so many programming languages present in the market, so deciding which one we must use for our business projects is becoming very tough.

We are listing popularity of some of the top languages based completely on our own research and discussion, using Google and Stack Overflow trends .



#1. Java:-

Java is still most popular language among developers around the globe. Its an alternative to C++ and its the world on any programmer.For a programmer learning, Java is like learning ABCD  in childhood. Most of the programmers in today’s world learn and prefer to code in Java.

With the release of Java 6, It was soon thought that it is a dead language and its market started going down. People soon started thinking Scala and Python as the new age technology. But with the release of Java 9, it is back in the game. A lot of new features have been introduced and the learning curve has been redefined with the introduction of Jshell.



#2. Python:

python for data sciencePython is one of the most widely used and fast-growing programming languages. Over the past 5 Years, it has grown pretty rapidly and became second most popular language.Learning Python is an added advantage for your career. Python is best for developing Web Frameworks, Tools and  Data Analytics. Python is easy to use, powerful, and versatile, making it a great choice for beginners. It allows you to think only about the code, it doesn’t have any mysterious syntax. Some of the big tech giants like Google, Microsoft, and Netflix uses Python for Web API and data analytics.

# 3. Javascript:-

Javascript Is the FutureIn Recent years javascript got a boom along with the introduction of Node.js. You can find JavaScript everywhere. One Language to rule, one language for the all. Netscape originally wanted to use JavaScript both client side and server side but that vision only came to fruition with the rise of Node.js. It has a huge repository of libraries that we can use for our projects including backend. It’s the only language in the market which supports both front-end and backend in a practical way. Technology evolves at a huge pace and Javascript has as well.Its potential for the future is massive with ES6 and ES7 features.



#4. Php:-

Php is mostly in use due to WordPress. Covering almost 80% of blogs built on WordPress, Php is most suited for Web development projects.You can use php to create e-commerce applications.It’s an open source language and very easy to learn and start. Suitable for any level of application.Hosting Php is cheap and easy compared to any web programming languages. php codes are much faster than java and ASP.


#5 C#:-

C# is a multi-paradigm programming language following objected oriented approach.Keeping in mind popularity of java it is developed as a rival of Java.We can use to create almost anything but is particularly strong at building Windows desktop applications and games. It has become increasingly popular for mobile apps and game development engines.It is also the 3rd largest community on stack overflow.

Some Users has commented on Facebook post , it looks like old trend .Here i am talking about core Programming languages not libraries .Please check the Screenshot below from StackOverflow Survey which matches my search and interaction with developers.Click here to check stack overflow developers survey and verify your thoughts as well.

Top 5 Programming languages 2018

Featured Posts :-

MVC OR MVVM – Take Your Pick

Get Current Location Android -No GPS and Internet

MVC OR MVVM – Take Your Pick

Custom ClassLoaders In Java

Java Class Loaders and Internal Working

I have Given a list of languages that you must know in 2018.Visit my channel for More videos.

React JS Setup using Npm Babel and Webpack

React JS Setup using Npm Babel and Webpack:-

With the introduction of react JS  , the way we build our UI component has changed. things that we build our components in react so you must be aware that the learning curve of react is very small but there are some tools that we need to understand for going into react , so one of those tools are webpack and Babel.So in this article we will 
do React JS Setup using Npm Babel and Webpack.
 
We will not cover the full understanding of webpack in Babel ,  but we will see how we can use this in our react applications .

 

 
So guys we will be using Windows in our demonstration but you can use Linux as well so the prerequisite of starting this blog post is that you need to have node JS installed .
Let’s go to this URL and download node js. Please download the latest version of node js .
 
So once you have downloaded node JS with you have to go to command  prompt and verify by typing node -v 
v8.7.0

So once you got the output as I have shown above that means your node JS is installed



Now navigate to any of the folder where you want to create your project and create a folder named as hello-world and initialize with npm .
We Will be using npm over here so , npm is a package manager for node based applications , similar to what is knwon as maven for java based applications.
 
  • We Will type npm init to initialize npm .
  • Will be getting one prompt so just accept the default for all the prompts whatever you get and continue.
  • npm init will create a package.json file in your working directory .
  • We Create One folder named as hello-world and then run npm init as shown below.
    mkdir hello-world
    cd hello-orld
    npm init

Configuring Babel :-

React Js Contains ES6 based code which most browsers doesn’t support at this point of time .Hence we need some tool to convert our ES6 code to plain vanilla javascript , and the tool is Babel . Let’s install all babel related dependencies one by one . Type in following commands one by one .

>npm install -g babel
>npm install -g babel-cli
>npm install --save babel-core babel-loader babel-preset-react babel-preset-es2015

Now  install react related dependencies .

npm install --save react
npm install --save react-dom

Configuring Webpack:-

Webpack is the bundler we will use, which will bundle all our javascript files.Its is basically a module bundler which bundles all our Javascript modules and assets into one or more bundles.

let’s install webpack using NPM

npm install --save webpack

Install  webpack dev server , we use it for live reloading . It helps us to provide fast in memory access to assets bundled by webpack.

npm install --save  webpack-dev-server 

Now our webpack requires some config files let’s create a file named webpack.config.js

webpack.config.js:-

config = {
   entry: './main.js',
	
   output: {
      path:'/target',
      filename: 'index.js',
   },
	
   devServer: {
      inline: true,
      port: 8090
   },
	
   module: {
      loaders: [
         {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
				
            query: {
               presets: ['es2015', 'react']
            }
         }
      ]
   }
}

module.exports = config;

You Can see here , entry and output are mandatory to be provided in this config file .Our UI will run on port 8090 as configured in webpack.config.js  Lets go ahead and create a file known as main.js under hello-world directory.

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import Hello from './Hello.jsx';

ReactDOM.render(<Hello />, document.getElementById('hello'));

Create A Basic  React Component :-

Create a file named Hello.jsx .

import React from 'react';

class Hello extends React.Component {

   render() {
     const element=  <div>
            <h1>Hello World from ReactJS</h1>
            <hr/>
            Yo Yo ! Welcome!
         </div>;
                return (element);
   }
}

export default Hello;

This is our basic component which just prints a basic html .You can see we are importing this in our main.js above

Create Index File:-

We are creating a file named as index.html.Our react JS transpiled minified code is added in index.html.

index.html

<!DOCTYPE html>
<html lang = "en">
   <head>
      <meta charset = "UTF-8">
      <title>React App</title>
   </head>
   <body>
      <div id = "hello">
      </div>
      <script src = "index.js"></script>
   </body>
</html>

A important point to remember here is that we have referred index.js here , which is referred from memory .Webpack loads index.js into memory if you are running in dev mode.Update package.json to run webpack dev server as follow add  “start”: “webpack-dev-server –hot” under scripts property in package.json.

{
  "name": "helo-world",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
   "start": "webpack-dev-server --hot"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "webpack": "^3.10.0"
  }
}

Running the Application:-

Type “npm start” , you get following output . If you face any issues kindly comment.

output:- 

npm start

Download Code

“Its Always Better To Learn and Share Instead Learn and Forget” 

Related Posts:-

MVC OR MVVM – Take Your Pick

Overload Or Override Static Methods in Java