Showing posts with label HTML. Show all posts
Showing posts with label HTML. Show all posts

Friday, December 7, 2018

Setup React.js with sprint boot

In this post I'm going to setup Reactjs project and integrate it with SpringBoot project.

Prerequisites 
  1. You should have install java 1.8 or above.
  2. You should have Eclipse installed in your PC.
  3. Your PC should setup Maven installed and configured.

First of all lets create maven project by click on File-> New -> Maven Project then provide project details (I select create simple project). My project details as follows.



Lets add required dependencies in to the pom file first. I will use the similar pom structure with my inital spring boot project setup.



<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.nirmal.blog</groupId>

  <artifactId>ReacjsApp</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
    </parent>

 <dependencies>

  <!-- Compile -->
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>jstl</artifactId>
  </dependency>

  <!-- Provided -->
  <dependency>
   <groupId>org.apache.tomcat.embed</groupId>
   <artifactId>tomcat-embed-jasper</artifactId>
   <scope>provided</scope>
  </dependency>

  <!-- Runtime -->
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.6</version>
  </dependency>

 </dependencies>
 <build>

  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>  
</project>


But still project will not be able to perform maven install since we have not added springboot initialization class with main method.
Lets add that class with main method in to our project I'll call it as MyApp class. It will contain following details.

package com.nirmal.blog;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class MyApp extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MyApp.class);
}

public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}

}


After our springboot initialization class lets add the spring boot configuration file "application.properties". it should be added it to resource folder.

spring.mvc.view.prefix: /.
spring.mvc.view.suffix: .html



Then lets start develop the Reacjs part of the project. First of all you need to install node in your local machine. You can download nodejs from following location. In my application I'm using node version node-v8.11.3-x64. Install it in your local machine.

Then I  created new folder call "reactjs" and then use following command to create new reactjs project inside our maven project structure.

npx create-react-app my-app

after successful installation you should be able to see similar output to following




Then you can go inside the my-app folder and enter following command

npm run-script build

This will build the web application for us on the build folder in our reactjs project as show in bellow. 




Then lets start reactjs app by entering following command

nmp start

Then your newly created project should started and you should able to see similar output on your browser.






So far our project structure should be similar to bellow image.




First of all lets set the our application context path. Here we have to set context path in two places. One is for ReactJs and other one is for spring boot.

To set context path on ReactJs we have to modify homepage variable in package.json file.

In my example I set as bellow. you can access whole package json on github location.

"homepage": "http://localhost:8080/ReacjsApp/"


Then lets set the context path on Spring boot application we just need to add that configuration in to application.properties file. For my application configuration would be similar to bellow. 

server.servlet.context-path=/ReacjsApp

Then we have to add following configuration to specify the location for static resources which required for the reactjs app to start.

spring.resources.static-locations=classpath:/

Whole pplication.properties file can be access on github location.

Then lets modify this default application application to perform the react installation and build when project perform the maven install. In order to do that we have to add following command in the pom file.

 <build>
  <plugins>

   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
    <plugin>
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>1.6</version>
        <configuration>
            <workingDirectory>src/main/reactjs/my-app</workingDirectory>
<installDirectory>target</installDirectory>
</configuration>
<executions>
<execution>
<id>install node and npm</id>
<goals>
<goal>install-node-and-npm</goal>
</goals>
<configuration>
<nodeVersion>v10.11.0</nodeVersion>
<npmVersion>6.4.1</npmVersion>
</configuration>
</execution>
<execution>
<id>npm install</id>
<goals>
<goal>npm</goal>
</goals>
<configuration>
<arguments>install</arguments>
</configuration>
</execution>
<execution>
<id>npm run</id>
<goals>
<goal>npm</goal>
</goals>
<configuration>
<arguments>run-script build</arguments>
</configuration>
</execution>
</executions>
   </plugin>
   <plugin>
        <artifactId>maven-resources-plugin</artifactId>
        <version>2.6</version>
        <executions>
          <execution>
            <id>copy-resources</id>            
            <phase>validate</phase>
            <goals>
              <goal>copy-resources</goal>
            </goals>
            <configuration>
              <outputDirectory>${basedir}/src/main/webapp</outputDirectory>
              <resources>          
                <resource>
                  <directory>src/main/reactjs/my-app/build</directory>
                  <filtering>true</filtering>
                </resource>
              </resources>              
            </configuration>            
          </execution>
        </executions>
      </plugin>   
  </plugins>


 </build> 

Now we are ready to install our application using maven. When performing the maven install you can see its executes the npm install and npm run-script build as show in bellow.




After successful maven installation you can see the war file generated on the target folder and you can run the we application using following command without any servlet container.

java -jar ReacjsApp-0.0.1-SNAPSHOT.war

Then you will be able to see spring application starting run and after its completed you will be able to access first reactjs app on SpringBoot on following http://localhost:8080/ReacjsApp/.





Project source can be access on following github location.

Thursday, August 6, 2015

Use static resource folder in Tomcat

In this post I will explain how to use static resource folder in tomcat application server. Normally resources like Cascading Style Sheet (CSS) files, JavaScript files and images store inside the web application. That means when we deploy WAR file in to application server that WAR file contains resources inside it. It here I will explain how to access resources from static folder outside from WAR file.

Prerequisites 
  1. You should have install java(It requires to have JVM 6 or higher version ) in your PC and set path variable correctly (JAVA_HOME, PATH)
  2. You should have install Eclipse Java EE IDE in your PC
  3. You should have Apache Tomcat in your machine and it should be added to Run Time Environments in Eclipse
Step 1 Create Dynamic web project
As first step lets create simple Dynamic Web Project using Eclipse. Go to File->New->New Dynamic Web Project. Give prefered name to the project (Here I will user project name as SharedResourceWeb as Figure 1) Then click finish. 
Figure 1: Provide project name

Then click next and next interface also click next and last interface tick box "Generate Web.xml for deployment descriptor". Then Click Finish button.
Figure 2 : Folder structure of new project
Then right click on WEBContent folder under your project node and go to New->HTML File then provide file name as "index.html". Then add some content to index.html. I will add following content

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Shared Web</title>
</head>
<body>
My Test web project
</body>
</html>


Then lets check all the things work correctly by deploy this web app into tomcat. First right click project you create and go to Export->WAR file the next interface provide WAR file name and location you need to create file. I will use "webapps" folder inside the tomcat folder stucture as WAR file creation location. Then select appropriate  target run time. If you have the tomcat v6 or v7 select correct run time. I'm using tomcat v7 (Figure 3)
Figure 3: Create WAR file using Eclipse
Then click on Finish you can see generated WAR file inside the selected location. If you not generated inside the webapps folder in tomcat folder structure copy WAR file in to
"webapps" folder.
Then start the tomcat server and you will be able to access your web project according to following URL format.

http://localhost:[tomcat running port]/[ProjectName]/

for my project it's

http://localhost:8888/SharedResourceWeb/

You can see interface similar to figure 4.
Figure 4: Project I deployed to tomcat



Then go to conf folder inside the tomcat directory and open server.xml file. Then add following line in between <HOST></HOST>.
        <Context docBase="/SharedResource" path="/SharedResource" reloadable="true"/>
Then go to webapps folder and create SharedResource folder and create anther folder as css then add new styles.css file with following content.


b {
    font-size : 16 px ;
}
.div1 {
    background-color: yellow;
    font-size: large;
}
.div2 {
    background-color: lime;
    font-size: x-large;
}
i {
    color : red ;
}


Then restart the tomcat server and try to access the css file through following link.

http://localhost:[tomcat running port]/SharedResource/css/styles.css

for my project link will be http://localhost:8888/SharedResource/css/styles.css



Then lets add some content and styles in to index.html. I will add following content in to index.html.

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Shared Web</title>
<link rel="stylesheet" href="http://localhost:8888/SharedResource/css/styles.css">
</head>
<body>
<b>This is Title</b>
<div class="div1">
<p>This is first paragraph in the web page</p>
<p>This is second paragraph in the web page</p>
</div>
<div class="div2">
<p class="p3">This is last paragraph in the web page</p>
<i>EXIT</i>

</div>
</body>
</html>


Then create the new war file and placed it inside the webapps folder. Then restart tomcat after that refresh the web page (http://localhost:8888/SharedResourceWeb/) you created. It will show the content with styles. You can see similar page to Figure 5.


Figure 5: Web page with Styles


This kind of shared folder will help to change the styles of project without deploying project.

Tuesday, June 30, 2015

Enable click event on disabled html element

This post will explain steps to trigger click event on disable html elements. Generally disable HTML elements will not fire any javascripts events but some times we needs to disable HTML elements initially and then in click event we may need to enable element. That kind of scenarios we can use following steps to archive it.

Whole example will be available in JSFiddle and you can try it your self. 
For this example I will use simple button to change a select field enable/disable function. Initially select field will be disabled and on the click event it will get enable. But actually user click on a another div placed in front of the select field but user will not have any idea about that. This div will be enable only when select field is disable.

<button id="enbDesBtn">Enable Passengers</button>
<div id="wrapper">
    <select id="passengers" disabled>
        <option value="1">Lakshan</option>
        <option value="2">Udara</option>
        <option value="3">Devmini</option>
        <option value="4">Nimasha</option>
    </select>
    <div id="overlay"></div>
</div>

Figure 1: HTML file view

Then we have to add following CSS and JavaScript in to HTML to archive our target. 

Javascript

var button = document.getElementById('enbDesBtn'),
    cars = document.getElementById('passengers'),
    overlay = document.getElementById('overlay');

button.addEventListener('click', function () {
    cars.disabled = !cars.disabled;
    var value="";
    if (cars.disabled) {
        button.textContent = 'Enable';
        value = 'Disable';
    } else {
        button.textContent = 'Disable';
        value = 'Enable';
    }
    alert(value);
}, true);

cars.addEventListener('change', function (evt) {
    console.log(evt.target.value);
}, true);

overlay.addEventListener('click', function () {
    alert('Disabled');
}, true);


CSS

#wrapper {
    display:inline-block;
    position:relative;
}
#overlay {
    display:none;
    width:100%;
    height:100%;
    position:absolute;
    top:0
    left:0;
    bottom:0;
    right:0;
}
#passengers:disabled + #overlay {
    display:block;
}

After adding above CSS and Javascripts in to HTML whole file will be similar to following.

<html>
<head>
<script>
window.onload=function(){
var button = document.getElementById('enbDesBtn'),
    cars = document.getElementById('passengers'),
    overlay = document.getElementById('overlay');

button.addEventListener('click', function () {
    cars.disabled = !cars.disabled;
    var value="";
    if (cars.disabled) {
        button.textContent = 'Enable';
        value = 'Disable';
    } else {
        button.textContent = 'Disable';
        value = 'Enable';
    }
    alert(value);
}, true);

cars.addEventListener('change', function (evt) {
    console.log(evt.target.value);
}, true);

overlay.addEventListener('click', function () {
    alert('Disabled');
}, true);
}
</script>
<style>
#wrapper {
    display:inline-block;
    position:relative;
}
#overlay {
    display:none;
    width:100%;
    height:100%;
    position:absolute;
    top:0
    left:0;
    bottom:0;
    right:0;
}
#passengers:disabled + #overlay {
    display:block;
}
</style>
</head>
<body>
<button id="enbDesBtn">Enable Passengers</button>
<div id="wrapper">
    <select id="passengers" disabled>
        <option value="1">Lakshan</option>
        <option value="2">Udara</option>
        <option value="3">Devmini</option>
        <option value="4">Nimasha</option>
    </select>
    <div id="overlay"></div>
</div>
</body>
</html>

As above example shows this functionality can be integrate with any other kind of HTML elements such as input fields, radio buttons etc.