Sunday, 11 March 2018

Spring Boot Rest service with spring jdbc

Hi Friends,I am going to introduce Rest Service using Spring Boot.

Following technology being used:
1)Spring Boot 1.4.1.RELEASE
2)Spring 4.0
3)Maven 4.0
4)JDK 1.7

Project Structure:


Dependency Management:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="UTF-8"?>
<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>org.demo</groupId>
 <artifactId>test</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>SpringBootHelloWorld</name>
 <description>Demo project for Spring Boot</description>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.4.1.RELEASE</version>
  <relativePath /> <!-- lookup parent from repository -->
 </parent>

Typical Spring boot application is as given below :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package org.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@EnableAutoConfiguration
@SpringBootApplication(scanBasePackages={"org.test"})
public class main {

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

5 Endpoints are exposed in below rest controller .summary of each is as given below :
Endpoints Description
localhost:8098/student/getAll API that returns all student
localhost:8098/student/get/{id} Api that return student based on id 
localhost:8098/student/add/{id} API that adds student
localhost:8098/student/updte/{id} API that updates student
localhost:8098/student/delete/{id} API that deletes student

Rest Controller :


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package org.test.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import org.test.bean.Student;
import org.test.dao.StudentDAOImpl;

@EnableAutoConfiguration
@RestController
public class StudentController {

 @Autowired
 private StudentDAOImpl dao;
 
 @GetMapping("/student/getAll")
 public ResponseEntity<List<Student>> getAllStudents() 
 {
  
 List<Student> listStudents= dao.getAllStudents();
 if(listStudents.size()==0)
  return new ResponseEntity<List<Student>>(HttpStatus.NOT_FOUND);
 
 return new ResponseEntity<List<Student>>(listStudents,HttpStatus.OK);
 }
 @GetMapping("/student/get/{id}")
 public ResponseEntity<Student> getStudent(@PathVariable("id") String id) 
 {
 Student stud = dao.getStudent(id); 
 if(stud==null)
  return new ResponseEntity<Student>(HttpStatus.NOT_FOUND);

 return new ResponseEntity<Student>(stud,HttpStatus.OK);
 
 }
 @PostMapping("/student/add/{id}")
 public ResponseEntity<?> addStudent(@RequestBody Student student, UriComponentsBuilder ucBuilder) 
 {
 Student stud = dao.addStudent(student); 
 if(stud==null)
  return new ResponseEntity<Student>(HttpStatus.NOT_FOUND);
 HttpHeaders headers = new HttpHeaders();
    headers.setLocation(ucBuilder.path("/student/user/{id}").buildAndExpand(student.getId()).toUri());
 return new ResponseEntity<String>(headers,HttpStatus.CREATED);
 
 
 }
 
 @PutMapping("/student/updte/{id}")
 public ResponseEntity<?> updateStudent(@PathVariable("id")String id ,@RequestBody Student student) 
 {
 
 int rowcount=dao.updateStudent(id,student);
 
 if(rowcount==0)
  return new ResponseEntity(new CustomMessage("Unable to upate. Student with id " + id + " not found."),HttpStatus.NOT_FOUND);
 else 
 return new ResponseEntity<Student>(student,HttpStatus.OK);
 
 }
 @DeleteMapping("/student/delete/{id}")
 public ResponseEntity<?> deleteStudent(@PathVariable("id") String id) 
 {
 Student obj = dao.getStudent(id); 
 if(obj==null)
  return new ResponseEntity(new CustomMessage("Unable to delete Student with id " + id + " not found."),HttpStatus.NOT_FOUND);
  

 dao.deleteStudent(id);
 return new ResponseEntity<Student>(HttpStatus.NO_CONTENT); 
 } 
}

DAO layer is given below :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package org.test.dao;

import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.test.bean.Student;

@Repository
public class StudentDAOImpl {

 @Autowired
 public  JdbcTemplate template;

 public Student addStudent(Student student) {
  // TODO Auto-generated method stub
  
  String sql="insert into student(id,name,college,status) values(?,?,?,'A')"; 
        template.update(sql,new Object[]{student.getId(),student.getName(),student.getCollege()});
  return student;
 }

 public int updateStudent(String id, Student stud) {
  // TODO Auto-generated method stub
        int[] types = {Types.VARCHAR, Types.VARCHAR,Types.VARCHAR};
  String sql = "update student set name = ? ,college =? where id = ?";
  int rows = template.update(sql,new Object[]{stud.getName(),stud.getCollege(),id},types);
  
        System.out.println(rows + " row(s) updated.");        
  return rows;
 }

 public void deleteStudent(String id) {
  String sql="delete from student where id=?";
  template.update(sql,id);  
 }

 public Student getStudent(String id) {
  
  String sql = "SELECT * FROM student WHERE id = ?";

  Student customer = (Student) template.queryForObject(
    sql, new Object[] { id },
    new BeanPropertyRowMapper(Student.class));

  return customer;  
 }

 public List<Student> getAllStudents() {
  String sql = "select * FROM student";

  List<Student> listStudent = new ArrayList<Student>();

  List<Map<String, Object>> rows = template.queryForList(sql);
  for (Map row : rows) {
   Student stud = new Student();
   stud.setId((String)(row.get("id")));
   stud.setName((String)row.get("name"));
   stud.setCollege((String)row.get("college"));
   listStudent.add(stud);
  }

  return listStudent; 
 }
 
}

Test the API:
I will use external client POSTMAN to test the endpoints exposed .

1. Get All Students



2. Get Specific Student


3.Add student : one need to provide request body and content type as "application/json'.


4.Delete Student : No Response in Response body . HttpStatus.NO_CONTENT is returned .



Hope you like this article .for any query ping me on  npjava90@gmail.com

Sunday, 20 August 2017

JMS Asynchrounous Message Send/receive using servlet with Oracle WebLogic


Hi Friends .Hope you are fine. Today i am going to demonstrate how JMS Queues  are configured in Oracle WebLogic Server.Considering reader's have basic knowledge about Weblogic Server and Message driven beans of EJB.

JMS is a Standard API for accessing enterprise messaging systems.
You need to configure JMS Server, JMS Modules like Queues/Topics and Connection Factories and in order to get connect to the JMS Server you need to create write client  by creating class in java.\

JMS Server will act as a managed container for JMS Modules where Administrator objects has been defined.
JMS  Modules  have resources defined that can be accessed using JMS Clients.

Technology Stack being used:
1) JDK 1.7
2) Oracle weblogic Server 12C
3) JMS (Java Messaging Service)
4) Message Driven Beans(part of EJB)
5) J2EE

First of all you need to create Enterprise Application Project. where eclipse will ask you to define new module  as screenshot attached.


in order to learn how to configure JMS resources you can always visit official oracle site as given below:
https://blogs.oracle.com/soaproactive/jms-step-1-how-to-create-a-simple-jms-queue-in-weblogic-server-11g
below is the configuration screenshot for JMS Configuration  which shows JMS Servers,JMS Queues,Connection Factory :






I  will going to define Message-Driven Bean  which will be called when message is received.

Now i will going to show you a servlet which will connect to the administrator object defined in JMS server. Project Structure is as given below :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package org.test.mdb;

import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

/**
 * Message-Driven Bean implementation class for: MessageQueue1
 */
@MessageDriven(activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue") }, mappedName = "qjndi1")
public class MessageQueue1 implements MessageListener {

 @Resource
 private MessageDrivenContext mdc;

 /**
  * Default constructor.
  */
 public MessageQueue1() {
  // TODO Auto-generated constructor stub
 }

 /**
  * @see MessageListener#onMessage(Message)
  */
 public void onMessage(Message inMessage) {
  System.out.println("onMessage method");
  TextMessage msg = null;
  try {
   if (inMessage instanceof TextMessage) {
    msg = (TextMessage) inMessage;
    System.out.println("MDB Queue1: " + msg.getText());
   } else {
    System.out.println("Message of wrong type: "
      + inMessage.getClass().getName());
   }
  } catch (JMSException e) {
   e.printStackTrace();
   mdc.setRollbackOnly();
  } catch (Throwable te) {
   te.printStackTrace();
  }
 }
}

below is the Sender Servlet:
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package org.test.sender;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;
import java.util.UUID;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class QueueSenderServlet
 */
public class QueueSenderServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;

 // Defines the JNDI context factory.
 public final static String JNDI_FACTORY = "weblogic.jndi.WLInitialContextFactory";

 // Defines the JMS context factory.
 public final static String JMS_FACTORY = "cfjndi";

 // Defines the queue.
 public final static String QUEUE = "qjndi1";

 private QueueConnectionFactory qconFactory;
 private QueueConnection qcon;
 private QueueSession qsession;
 private QueueSender qsender;
 private Queue queue;
 private TextMessage msg;

 public QueueSenderServlet() {
  super();

 }

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
  *      response)
  */
 protected void doGet(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {

  QueueConnection queueconnection = null;
  QueueSession qsession = null;
  

  Hashtable env = new Hashtable();
  env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
  env.put(Context.PROVIDER_URL, "t3://localhost:7001/");

  InitialContext ctx = null;
  try {
   ctx = new InitialContext(env);
  } catch (NamingException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
  PrintWriter pw = response.getWriter();
  pw.println("Message Sending from Web client");

  try {

   qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
   qcon = qconFactory.createQueueConnection();
   qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
   queue = (Queue) ctx.lookup(QUEUE);
   qsender = qsession.createSender(queue);
   msg = qsession.createTextMessage();

   String data = request.getParameter("msg");

   msg.setJMSCorrelationID(UUID.randomUUID().toString());
   msg.setJMSMessageID("ch001"); 
   msg.setJMSExpiration(10000);
   qsender.setDeliveryMode(DeliveryMode.PERSISTENT);
   
   msg.setText(data);
            
   qsender.send(msg);
   pw.println("To see message go to server console");

  } catch (JMSException e) {
   System.out.println("Exception occurred: " + e.toString());
  } catch (NamingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } finally {
   if (queueconnection != null) {
    try {
     queueconnection.close();
    } catch (JMSException e) {
     e.printStackTrace();
    }
   }
  }
 }
 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
  *      response)
  */
 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
 }
}

Index.jsp is as given below:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<%@ 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> Queue DEMO</title>
</head>
<body>
<form action="QueueSenderServlet">
 <input type="text" name="msg">
 <input type="submit" value="send Message"/>
 
</form>
</body>
</html>

Deployment Descriptor  :Web.xml 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>EJB3MDBQueueWeb</display-name>
  <welcome-file-list>
    
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>QueueSenderServlet</display-name>
    <servlet-name>QueueSenderServlet</servlet-name>
    <servlet-class>org.test.sender.QueueSenderServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>QueueSenderServlet</servlet-name>
    <url-pattern>/QueueSenderServlet</url-pattern>
  </servlet-mapping>
</web-app>

one can monitor message coming to JMS server in below location:
Thanks for reading this article .for any query ping me on npjava90@gmail.com








Monday, 8 May 2017

Rest Service using Angularjs and Spring MVC with deployment in JBOSS 7 Server

Hello Friends .hope you all are fine.today i am going to demonstrate how one can call rest service using angularjs.  i am going to use one of the directive called ng-resource for same. I am using bootstrap for look and feel.

for detailed document you can refer below link :
https://docs.angularjs.org/api/ngResource/service/$resource

Technology Stack being used:
1) JDK 1.7
2) JBOSS 7.1
3) Spring 3.x 
4) Angularjs
5) BootStrap CDN

Note that I am calling Rest service without any database interaction (by putting dummy data in controller itself)

Project Structure is as given below :





The Model class is as given below :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package org.demo.model;

public class Book { 
 private String id;
 private String name;
 private String isbn;
 public String getId() {
  return id;
 }
 public void setId(String id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 
 public String getIsbn() {
  return isbn;
 }
 public void setIsbn(String isbn) {
  this.isbn = isbn;
 }
 public void setName(String name) {
  this.name = name;
 }
}

Controller:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package org.demo.controller;
import java.util.ArrayList;
import java.util.List;
import org.demo.model.Book;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
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.util.UriComponentsBuilder;

@Controller
public class BookController {
 static List<Book> bookList = new ArrayList<>();
 static Book s1 = null;
 static Book s2 = null;
 static Book s3 = null;

 static {
  s1 = new Book();

  s1.setId("1");
  s1.setName("Don Quixote by Miguel de Cervantes");
  s1.setIsbn("12");

  s2 = new Book();

  s2.setId("2");
  s2.setName("In Search of Lost Time by Marcel Proust");
  s2.setIsbn("44");

  s3 = new Book();

  s3.setId("3");
  s3.setName("Ulysses by James Joyce");
  s3.setIsbn("33");

  bookList.add(s1);
  bookList.add(s2);
  bookList.add(s3);
 }

 @RequestMapping(value = "/book", method = RequestMethod.GET)
 public ResponseEntity<List<Book>> getAllBooks() {

  return new ResponseEntity<List<Book>>(bookList, HttpStatus.OK);
 }

 @RequestMapping(value = "/book", method = RequestMethod.POST)
 public ResponseEntity<Void> addBook(@RequestBody Book Student, UriComponentsBuilder builder) {

  HttpHeaders headers = new HttpHeaders();
  headers.setLocation(builder.path("/book/{id}").buildAndExpand(Student.getId()).toUri());
  return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
 }

 @RequestMapping(value="/book/{id}", method = RequestMethod.PUT ) 
 public ResponseEntity<Book> updateBook(@RequestBody Book book) {
   
 return new   ResponseEntity<Book>(book, HttpStatus.OK);
  
 }

 @RequestMapping(value = "/book/{id}", method = RequestMethod.DELETE)
 public ResponseEntity<Void> deleteBook(@PathVariable("id") Integer id) {
  
  return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
 }
}

app.js
- contains rest calls using Angularjs
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
(function() {
  angular.module("myApp", ['ui.bootstrap','ngResource']);

  angular.module("myApp").controller("CoversCtrl", function($scope, BookSvc, $modal) {
    $scope.books = BookSvc.query();
    
    $scope.openDialog = function() {
      var modalInstance = $modal.open({
        templateUrl: 'addbook.html',
        controller: ModalInstanceCtrl
      });

      modalInstance.result.then(function (newBook) {
        $scope.books.push(newBook);
      }, function () {
        console.log('Modal dismissed at: ' + new Date());
      });

    };
    
    $scope.editDialog = function(book){
      var modalInstance = $modal.open({
        templateUrl: 'editbook.html',
        controller: EditBookCtrl,
        resolve: {
        oldBook: function () {
          return book;
        }
       }
      });

      // modalInstance.result.then(function (newBook) {

      //   $scope.books.push(newBook);
      // }, function () {
      //   console.log('Modal dismissed at: ' + new Date());
      // });
    }
    
    $scope.removeBook = function(book) {
      BookSvc.remove(book, function(res) {
        $scope.books.splice($scope.books.indexOf(book), 1);
      });

    };
  });
  
  var ModalInstanceCtrl = function ($scope, $modalInstance, BookSvc) {

  $scope.addBook = function (formData) {

    BookSvc.save(formData, function(res){
      $modalInstance.close(res); 
    });
   
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
};

  var EditBookCtrl = function ($scope, $modalInstance, oldBook, BookSvc) {
  $scope.formData = oldBook;

  $scope.updateBook = function(){
  /*  var postingsResource = $resource('http://localhost:8080/SpringWithAngularjs/person/:id', { id: '3'});
       postingsResource.delete();*/
       
  BookSvc.update(JSON.stringify($scope.formData), function(res){
    $modalInstance.close(res); 
  });
   
  };


  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
};
  
})();

Service for calling rest service is as given below :
1
2
3
4
5
6
7
8
(function(){
  
    angular.module("myApp").constant("baseUrl", "http://localhost:8080/SpringWithAngularjs/book/");
    
    angular.module("myApp").factory("BookSvc", function($resource, baseUrl){
      return $resource(baseUrl+":id", {}, { update: {method: "PUT", isArray: false}});
    });
})();

web.xml is as given below:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>SpringWithAngularjs</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>    
  </welcome-file-list>
  
   <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>

Applicationcontext file named springrest-servlet.xml is as given below :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<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:resources mapping="/app-resources/**" location="/resources/"
 cache-period="31556926"/>
 
 
 <mvc:annotation-driven/>
 <context:annotation-config></context:annotation-config>
<context:component-scan base-package="org.demo.controller" />
 <bean
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix">
   <value>/WEB-INF/</value>
  </property>
  <property name="suffix">
   <value>.jsp</value>
  </property>
 </bean>

<mvc:default-servlet-handler/>

</beans>

main page of application named index.jsp is as given below :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<!DOCTYPE html>
<html ng-app="myApp">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>CRUD with Angular JS</title>

  <link href="http://bootswatch.com/cosmo/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div class="container" ng-controller="CoversCtrl">

    <div class="page-header">
      <h1>Book Cart </h1>
      <button class="btn btn-default" ng-click="openDialog()">Add New Book</button>
    </div>
    <div class="table-responsive">
      <table class="table table-striped table-hover">
      <thead>
        <tr>
          <th>Name</th>
          <th>ISBN NO</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="book in books">
          <td>{{ book.name }}</td>
          <td>{{ book.isbn }}</td>
          <td>
            <button type="button" class="btn btn-danger" ng-click="removeBook(book)">Delete</button>
            <button type="button" class="btn btn-info" ng-click="editDialog(book)">Edit</button>
          </td>
        </tr>
      </tbody>
    </table>    
    </div>

  </div>
<%-- <script src="${pageContext.request.contextPath}/app-resources/js/lib/angular.min.js"></script>
    <script src="${pageContext.request.contextPath}/app-resources/js/lib/angular-resource.min.js"></script> --%>
      <script src="https://code.angularjs.org/1.2.26/angular.min.js"></script>
  <script src="https://code.angularjs.org/1.2.26/angular-resource.min.js"></script>
 <script src="${pageContext.request.contextPath}/app-resources/js/app.js"></script> 
 <script src="${pageContext.request.contextPath}/app-resources/js/BookSvc.js"></script>
 
 <script src="${pageContext.request.contextPath}/app-resources/js/ui-bootstrap-custom-tpls-0.10.0.min.js"></script>
 <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/app-resources/css/style.css"/>
  

</body>

</html>

Modal for add book is as given below :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
addbook.html

<div class="modal-header">
  <h3 class="modal-title">Add Book</h3>
</div>
<div class="modal-body">
  <form role="form" novalidate name="addBookForm">
    <div class="form-group">
      <label for="name">Name</label>
      <input type="text" class="form-control" id="name" placeholder="Enter Book Name" ng-model="formData.name">
    </div>
    <div class="form-group">
      <label for="isbn">ISBN No.</label>
      <input type="text" class="form-control" id="isbn" name="isbn" placeholder="ISBN" ng-model="formData.isbn">
    </div>
  </form>
</div>
<div class="modal-footer">
  <button class="btn btn-primary" type="submit" form="addBookForm"  ng-click="addBook(formData)">Add Book</button>
  <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>

Modal for editing book is as given below :

editbook.html

<div class="modal-header">
  <h3 class="modal-title">Edit Book</h3>
</div>
<div class="modal-body">
  <form role="form" novalidate name="editBookForm">
    <div class="form-group">
      <label for="name">Name</label>
      <input type="text" class="form-control" id="name" placeholder="Enter Book Name" ng-model="formData.name">
    </div>
    <div class="form-group">
      <label for="isbn">ISBN No.</label>
      <input type="text" class="form-control" id="isbn" name="isbn" placeholder="ISBN" ng-model="formData.isbn">
    </div>
  </form>
</div>
<div class="modal-footer">
  <button class="btn btn-primary" type="submit" form="editBookForm"  ng-click="updateBook(formData)">Update Book</button>
  <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>

once development is done ,you need to make war from the eclipse. if you are not familiar how to make war  please go to  http://www.codejava.net/ides/eclipse/eclipse-create-deployable-war-file-for-java-web-application
(Note : make sure that Compiler version of project is compitable. otherwise you will end up with having error like unsupported version Error.)

if you are not familiar with jboss Installation  and deployments than please go to their official site  to know about how to install & deploy application in the JBOSS Server.

Screenshot of application is as given below :



i will soon going to update this blog where database interaction is made  for rest service.for any query ping me on  npjava90@gmail.com

I  hope this article will help you .










Spring Boot SSL configuration -Tomcat Server

Hi Friends hope you all are doing well. Today I am going to demonstrate about how to configure SSL in Spring boot web Application. Need o...