Spring

Spring MVC HelloWorld Example

a) Libraries required:

spring-context - 4.1.6
spring-aop - 4.1.6
spring-webmvc - 4.1.6
spring-web 4.1.6
jstl - 1.2


b) Create web.xml file in WEB-INF folder and write following lines of code:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>


c) Create a xml file named as spring-servlet.xml inside WEB-INF folder and write following lines of code:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.cloudsmartz.controller" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>



d) Create a package named as com.cloudsmartz.controller (or any other name) and inside this package Create a new class named as HelloWorldController.java and write following code:

package com.cloudsmartz.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorldController {

@RequestMapping("/hello")
public ModelAndView helloWorld() {
String message = "HELLO SPRING MVC HOW R U";
System.out.println("Here.............");
return new ModelAndView("hellopage", "message", message);
}
}


e) Create a folder inside WEB-INF named as jsp and inside this folder Create a new JSP named as hellopage.jsp and write following code in it:


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page isELIgnored="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>${message}
</body>
</html>



Spring MVC Multiple Controller Example


a) Libraries to be used:

spring-core - 4.1.6
spring-web - 4.1.6
spring-webmvc - 4.1.6
javax.servlet-api - 3.1.0
jstl - 1.2


b) Create a xml file named as web.xml in WEB-INF folder and write the following code in it:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>

</web-app>


c) Create a xml file named as spring-servlet.xml in WEB-INF folder and write following code in it:


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.cloudsmartz.controller" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>  


d) Create an index.jsp and do following code in it:

<html>
<body>
<h2>Hello World!</h2>
<a href="hello.html">Hello Controller</a>
<a href="welcome.html">Welcome Controller</a>
</body>
</html>


e) Create a folder named jsp in WEB-INF folder and Create following JSP pages in this folder:
data.jsp 

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Hi you have arrived on Hello COntroller.....</h1>

</body>
</html>


and gagandeep.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Hii..you have arrived on Welcome Controller....</h1>

</body>
</html>


e) Create a package named as com.cloudsmartz.controller and within this package Create following classes in it:

HelloController.java


package com.cloudsmartz.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloController {
@RequestMapping("/hello")
public ModelAndView helloWorld() {
String message = "HELLO CONTROLLER";
System.out.println("Heloooo..........");
return new ModelAndView("data", "message", message);
}
}


WelcomeController.java


package com.cloudsmartz.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class WelcomeController {
@RequestMapping("/welcome")
public ModelAndView helloWorld() {
String message = "WELCOME CONTROLLER";
System.out.println("Welcome.........");
return new ModelAndView("gagandeep", "message", message);
}
}


In our earlier post, we developed a small application using REST and AngularJS. Follow this link for help http://techs4.blogspot.in/2016/06/restful-webservice-using-jersey.html Now, we are going to use Spring 4 to handle REST as it is used now a days in most IT-Software projects.

We would be using Spring Controller to handle REST request/response. In Spring 4, there is a new concept of @RestController Annotation.

Overview of our application:



Our front-end would look like as below:







Follow below steps to create this small application:

a) Libraries required:

jersey-server 1.9
mysql-connector-java 5.1.10
com.google.code.gson (gson) 2.2.1
spring-core 4.1.6
spring-web 4.1.6
spring-webmvc 4.1.6
javax.servlet-api 3.1.0

b) Create a xml file named as spring-servlet.xml in WEB-INF folder and write following code in it:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<mvc:annotation-driven />
<context:component-scan base-package="com.cloudsmartz" />

</beans>


c) Create another xml file named as web.xml in WEB-INF folder and write following code in it:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>


d) Create a properties file named as configuration.properties and write following code in it:

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql:///um
jdbc.user = root

e) Create a package named as com.cloudsmartz and within this package Create a class (POJO) named as Customer.java in it:

package com.cloudsmartz;

public class Customer {

private Integer id;
private String name, email;

public String getName() {
return name;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public void setName(String name) {
this.name = name;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}
}


f) Create a class named as ReadFromPropertiesFile.java in which following code is to be written:


package com.cloudsmartz;

import java.io.InputStream;
import java.util.Properties;

public class ReadFromPropertiesFile {

Properties properties = null;

ReadFromPropertiesFile() {
try {
InputStream is = ReadFromPropertiesFile.class.getClassLoader()
.getResourceAsStream("configuration.properties");
properties = new Properties();
properties.load(is);
} catch (Exception e) {
System.out.println("aaaa " + e);
}
}

public String getURL() {
try {
return properties.getProperty("jdbc.url");
} catch (Exception e) {
System.out.println("getURL:" + e);
}
return "";
}

}


g) Create another class named as ConnectDB.java in which database connectivity is performed:

package com.cloudsmartz;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.logging.Logger;

public class ConnectDB {

static ReadFromPropertiesFile obj = new ReadFromPropertiesFile();

public static Connection connect() {

Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(obj.getURL(), "root", "");
} catch (Exception e) {
Logger.getLogger(ConnectDB.class + "");
}
return conn;
}
}

h) Create a service layer class named as CustomerServices.java and write following code in it:

package com.cloudsmartz;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class CustomerServices {

public List<Customer> getAllCustomers() {
List<Customer> lst = new ArrayList();
try {
Connection conn = ConnectDB.connect();
PreparedStatement pstmt = conn
.prepareStatement("select * from customer order by id");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
Customer obj = new Customer();
obj.setId(rs.getInt("id"));
obj.setName(rs.getString("name"));
obj.setEmail(rs.getString("email"));
lst.add(obj);
}
} catch (Exception e) {
System.out.println(e);
}
return lst;
}

public String addCustomer(Customer obj) {
try {
Connection conn = ConnectDB.connect();
PreparedStatement pstmt = conn
.prepareStatement("insert into customer values(?,?,?)");
pstmt.setInt(1, obj.getId());
pstmt.setString(2, obj.getName());
pstmt.setString(3, obj.getEmail());
int i = pstmt.executeUpdate();
if (i > 0) {
return "Customer Created";
}
} catch (Exception e) {
System.out.println("addCustomer: " + e);
}
return "Failed to  Create Customer";
}

public String updateCustomer(Customer obj) {
try {
Connection conn = ConnectDB.connect();
PreparedStatement pstmt = conn
.prepareStatement("update customer set name=?,email = ? where id = ?");
pstmt.setString(1, obj.getName());
pstmt.setString(2, obj.getEmail());
pstmt.setInt(3, obj.getId());
int i = pstmt.executeUpdate();
if (i > 0) {
return "Customer Updated";
}
} catch (Exception e) {
System.out.println("updateCustomer: " + e);
}
return "Failed to  Update Customer";
}

public String delCustomer(int id) {
try {
Connection conn = ConnectDB.connect();
PreparedStatement pstmt = conn
.prepareStatement("delete from customer where id = ?");
pstmt.setInt(1, id);
int i = pstmt.executeUpdate();
if (i > 0) {
return "Customer Deleted";
}
} catch (Exception e) {
System.out.println("delCustomer: " + e);
}
return "Failed to  Delete Customer";
}
}


i) Create a class named as CustomerAPI.java and write following code in it:

package com.cloudsmartz;

import java.util.List;

import javax.ws.rs.core.MediaType;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;

@RestController
public class CustomerAPI {

@RequestMapping(value = "/getCustomers", method = RequestMethod.GET, produces = "application/json")
public String feed() {
String feeds = null;
try {
List<Customer> lstCustomers = null;
CustomerServices customerServices = new CustomerServices();
lstCustomers = customerServices.getAllCustomers();
Gson gson = new Gson();
feeds = gson.toJson(lstCustomers);
} catch (Exception e) {
System.out.println("Exception Error"); // Console
}
return feeds;
}

@RequestMapping(value = "/addCustomer", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON)
public ResponseEntity createCustomer(@RequestBody Customer obj) {
String result = "";
try {
CustomerServices customerServices = new CustomerServices();
result = customerServices.addCustomer(obj);
} catch (Exception e) {
System.out.println("Exception Error  " + e); // Console
}
return new ResponseEntity(HttpStatus.CREATED);
}

@RequestMapping(value = "/updateCustomer/id/{id}/name/{name}/email/{email}", method = RequestMethod.PUT)
public ResponseEntity<String> updateCustomer(@PathVariable("id") int id,
@PathVariable("name") String name,
@PathVariable("email") String email) {
String result = "";
try {
CustomerServices customerServices = new CustomerServices();
Customer obj = new Customer();
obj.setId(id);
obj.setName(name);
obj.setEmail(email);
result = customerServices.updateCustomer(obj);
} catch (Exception e) {
System.out.println("Exception Error  " + e); // Console
}
return new ResponseEntity<String>(HttpStatus.CREATED);
}

@RequestMapping(value = "/delCustomer/id/{id}", method = RequestMethod.DELETE)
public ResponseEntity<String> delCustomer(@PathVariable("id") Integer id) {
if (id > 0) {
String result = "";
System.out.println("Id:: " + id);
try {
CustomerServices customerServices = new CustomerServices();
result = customerServices.delCustomer(id);
} catch (Exception e) {
System.out.println("Exception Error  " + e); // Console
}
return new ResponseEntity<String>(HttpStatus.CREATED);
} else {
return new ResponseEntity<String>(HttpStatus.NOT_ACCEPTABLE);
}
}
}


j) Create an index.jsp file and write following code in it:

<html>
<head>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
<script type="text/javascript">
var myapp = angular.module("myApp", []);

myapp.controller("umcontroller", function($scope, $http) {
$scope.employees = [];
$scope.form = {
id : "",
name : "",
email : ""
};
_refreshPageData();
$scope.check = "";
$scope.submitCustomer = function() {
if ($scope.form.check == "check") {
method = "PUT";
url = 'updateCustomer/id/' + $scope.form.id + "/name/"
+ $scope.form.name + "/email/" + $scope.form.email;
} else {
method = "POST";
url = 'addCustomer';
}
$http({
method : method,
url : url,
data : angular.toJson($scope.form),
headers : {
'Content-Type' : 'application/json'
}
}).then(function successCallback(response) {
$scope.form.check = "";
_success(response);
});
};
$scope.removeEmployee = function(employee) {
$http({
method : 'DELETE',
url : 'delCustomer/id/' + employee.id
}).then(function successCallback(response) {
_success(response);
});
};
$scope.editEmployee = function(employee) {
$scope.form.name = employee.name;
$scope.form.email = employee.email;
$scope.form.id = employee.id;
$scope.form.check = "check";
};

function _refreshPageData() {
$http({
method : 'GET',
url : 'getCustomers'
}).then(function successCallback(response) {
$scope.employees = response.data;
}, function errorCallback(response) {
console.log(response.statusText);
});
}

function _success(response) {
_refreshPageData();
_clearForm()
}

function _error(response) {
console.log(response.statusText);
}

function _clearForm() {
$scope.form.name = "";
$scope.form.email = "";
$scope.form.id = "";
}

$scope.clearForm = function() {
_clearForm();
}
});
</script>
</head>
<body ng-app="myApp" ng-controller="umcontroller">

<div class="generic-container" ng-controller="umcontroller">
<div class="panel panel-default">
<div class="panel-heading">
<span class="lead">User Registration Form </span>
</div>
<div class="formcontainer">
<form ng-submit="submitCustomer()">
<div class="row">
<input type="hidden" ng-model="form.id" /> <input type="hidden"
ng-model="form.check" />
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="id">Id</label>
<div class="col-md-7">
<input type="text" ng-model="form.id" name="id"
class="username form-control input-sm"
placeholder="Enter your Id" required ng-minlength="1" />

</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="name">Name</label>
<div class="col-md-7">
<input type="text" ng-model="form.name" id="name"
class="username form-control input-sm"
placeholder="Enter your name" required ng-minlength="3" />

</div>
</div>
</div>


<div class="row">
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="email">Email</label>
<div class="col-md-7">
<input type="text" ng-model="form.email" id="email" name="email"
class="form-control input-sm"
placeholder="Enter your Email [This field is validation free]" />
</div>
</div>
</div>



<div class="row">
<div class="form-actions floatRight">
<input type="submit" value="{{!form.check ? 'Add' : 'Update'}}"
class="btn-sm" ng-disabled="myForm.$invalid">
<button type="button" ng-click="clearForm()"
class="btn-sm">Reset Form</button>
</div>
</div>

</form>
</div>
</div>
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">
<span class="lead">List of Users </span>
</div>
<div class="tablecontainer">
<table class="table table-hover">
<thead>
<tr>
<th>ID.</th>
<th>Name</th>
<th>Email</th>
<th width="20%"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="u in employees">
<td><span ng-bind="u.id"></span></td>
<td><span ng-bind="u.name"></span></td>
<td><span ng-bind="u.email"></span></td>
<td>
<button type="button" ng-click="editEmployee(u)"
class="btn btn-success custom-width">Edit</button>
<button type="button" ng-click="removeEmployee(u)"
class="btn btn-danger custom-width">Remove</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>

</body>
</html>




Spring and RESTful webservice Integration

Earlier, we had developed an application using Spring and Rest. But, this is a basic app which shows integration of Spring with Rest at a beginner level. This demo app is for freshers.




Following below steps to create this application:

1) Libraries required:

spring-core 4.1.6 RELEASE
spring-web 4.1.6 RELEASE
spring-webmvc 4.1.6 RELEASE
jstl 1.2


2) Create a xml file named as web.xml in WEB-INF folder and write following code:


<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>springrest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>springrest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>


3) Create a xml file named as springrest-servlet.xml in WEB-INF folder and write following code in it:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<mvc:annotation-driven />
<context:component-scan base-package="com.cloudsmartz.controller" />

</beans>


4) Create a package named as com.cloudsmartz.controller and Create a class named as SpringRestController.java and write following code in it:

package com.cloudsmartz.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/hello")
public class SpringRestController {
@RequestMapping(value = "/{name}", method = RequestMethod.GET)
public String hello(@PathVariable String name) {
String result = "Hello " + name;
return result;
}
}


5) Create a JSP or any html file and write following code in it:

<html>
<body>
<a href="hello/Gagan">Say Hello</a>
</body>
</html>


Our output would be like as below:





This is an anchor tag on which you would click and a Hello Message is shown:







No comments:

Post a Comment