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 .










Tuesday 25 October 2016

Spring with Angularjs File Upload & download

Hi Friends.hope you all are fine .today I  am going to demonstrate how to upload multiple file using AngularJS framework. Dependancy of Angularjs can be downloaded from https://angularjs.org/.

I suggest you to use https://jsfiddle.net to get practical examples of each & every concept of Angularjs .some of the concepts like ng-app,ng-controller,ng-model,ng-binding,routing,client side interceptor etc.

Technology Stack being used:
1) JDK 1.7
2) Spring 3.x 
3) Hibernate 3.x
4) Angularjs
5) BootStrap CDN
(6) Tomcat 7.0

Project Structure is as given below :

Let's Move to code :

Hibernate Model entity class  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
package org.fileupload.model;

import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.springframework.web.multipart.MultipartFile;

@Entity
@Table(name="trnimage")
public class FileUpload {
 
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "ID", unique = true, nullable = false)
 private int ID;
  @Column(name = "DATA", unique = false, nullable = false, length = 100000)
 private byte[] data;
 @Column(name = "IMAGE_NAME", unique = false, nullable = false, length = 100)
 private String IMAGE_NAME;
 @Transient 
 public int getID() {
  return ID;
 }

 public void setID(int iD) {
  ID = iD;
 }

 public byte[] getData() {
  return data;
 }

 public void setData(byte[] data) {
  this.data = data;
 } 
 public String getIMAGE_NAME() {
  return IMAGE_NAME;
 }
 public void setIMAGE_NAME(String iMAGE_NAME) {
  IMAGE_NAME = iMAGE_NAME;
 }

 @Transient
  private List<MultipartFile> file;
 public List<MultipartFile> getFile() {
  return file;
 }
 public void setFile(List<MultipartFile> file) {
  this.file = file;
 } 
}

Controller 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
 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
package org.fileupload.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.fileupload.dao.fileUploadDaoImpl;
import org.fileupload.model.FileUpload;
import org.fileupload.model.FileuploadVO;
import org.fileupload.service.fileUploadServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.multipart.MultipartFile;



@Controller
public class FileUploadController { 

 private Logger logger = Logger.getLogger(FileUploadController.class);
 //

 public FileUploadController()
 {
 
  logger.info("File Upload Controller Called : -");
 }
 
          
  //angular js call
 @RequestMapping(value = "/Testupload.htm", method = RequestMethod.POST)
    public String SaveTestImage(
            @ModelAttribute("uploadForm") FileUpload uploadForm,
            Model map,HttpServletRequest request ) throws IllegalStateException, IOException {
  logger.info(" Upload method Called : -");
 
  System.out.println(request.getParameter("filename"));
  WebApplicationContext context =WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
  
  fileUploadServiceImpl  service=(fileUploadServiceImpl) context.getBean("fileuploadService");
  
  
  fileUploadDaoImpl dao=(fileUploadDaoImpl) context.getBean("fileuploadDAO");
  
  
  //ResourceBundle rs =ResourceBundle.getBundle("test.properties");
  
  ResourceBundle rb = ResourceBundle.getBundle("resources/filePath");
  
  
  String saveDirectory = rb.getString("file.fileUploadPath");
        List<MultipartFile> listFiles = uploadForm.getFile();
        List<String> fileNames = new ArrayList<String>();
        int id =0;
        if (null != listFiles && listFiles.size() > 0) {
            for (MultipartFile multipartFile : listFiles) {
                String fileName = multipartFile.getOriginalFilename();
                if (!"".equalsIgnoreCase(fileName)) {
                    // Handle file content - multipartFile.getInputStream()
                    multipartFile
                            .transferTo(new File(saveDirectory + fileName));
                    fileNames.add(fileName);
                   
                    uploadForm.setData(fileName.getBytes());
                    uploadForm.setIMAGE_NAME(fileName);
                 id=  service.SaveTestImage(uploadForm);
                   
                }
            }
            
        } 
       
        map.addAttribute("files", fileNames);
        map.addAttribute("ids", id+"");
        return "uploadfilesuccess";
    }
  
 
 @RequestMapping(value = "/download.htm", method = RequestMethod.GET)
    public String download(  @RequestParam("id") String id,         
            Model map,HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException {
 
  System.out.println("id is  : "+id);
  
WebApplicationContext context =WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
  
  fileUploadServiceImpl  service=(fileUploadServiceImpl) context.getBean("fileuploadService");
  
  FileuploadVO f = service.downloadImg(id);
        response.setContentLength(f.getData().length);
        response.setHeader("Content-Disposition","attachment; filename=\"" + f.getIMAGE_NAME() +"\"");
        FileCopyUtils.copy(f.getData(), response.getOutputStream());
        return null;

 }
 
 
 /*@RequestMapping(value = "/test.htm")
    public String test() throws IOException {
         
        //just throw exception to test the exceptionhandler mapping
        if(true) {
            throw new IOException("this is io exception");
        }
         
        // render index.jsp page
        return "index";
    }*/
}

DAO(Data Access Layer)  : for database Interaction
 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
package org.fileupload.dao;

import org.fileupload.model.FileuploadVO;

public interface fileUploadDao {

 public int saveImage(FileuploadVO fileupload);
 public FileuploadVO downloadImg(String id);
 int saveImage1(FileuploadVO fileupload);
}
Service is as 
DAO Implementation  is as given below :

package org.fileupload.dao;

import org.fileupload.model.FileUpload;
import org.fileupload.model.FileuploadVO;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class fileUploadDaoImpl  implements fileUploadDao{

 
 private HibernateTemplate template;
 //@Autowired
 //private JdbcTemplate jdbcTemplate;
 
 public fileUploadDaoImpl(HibernateTemplate template ) {
  this.template = template;
  //template.getSessionFactory().openSession().load("", "");
 }
 
 @Override
 public int saveImage1(FileuploadVO fileupload) {
 
  template.save(fileupload);
  
  return fileupload.getID();
 }
 public FileuploadVO downloadImg(String id)
 {
//  String  query = "select * from  trnimage where ID = ?";
  FileuploadVO file  = (FileuploadVO) template.getSessionFactory().openSession().load(FileuploadVO.class, new Integer(id));
  
  return file;

 }

 @Override
 public int saveImage(FileuploadVO fileupload) {
  // TODO Auto-generated method stub
  return 0;
 }

 public int SaveTestImage(FileUpload fileupload) {

  template.save(fileupload);
  
  return fileupload.getID();
 }
}

Service Implementation 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
public class fileUploadServiceImpl  implements fiileUploadService{
 
 @Autowired 
 private fileUploadDaoImpl fileuploadDAO;

 @Override
 public int saveImage(FileuploadVO fileupload) {
  // TODO Auto-generated method stub
  return fileuploadDAO.saveImage(fileupload);
 }
 @Override
 public FileuploadVO downloadImg(String id) {
  // TODO Auto-generated method stub
  return fileuploadDAO.downloadImg(id);
 }
 @Override
 public int SaveTestImage(FileUpload fileupload) {
  // TODO Auto-generated method stub
  return fileuploadDAO.SaveTestImage(fileupload);
 }
}

Property files are as given below:
1
2
3
4
5
6
7
8
9
dbConfig.properties
 jdbc.driverClassName = com.mysql.jdbc.Driver
 jdbc.url = jdbc:mysql://localhost:3306/studentdb
 jdbc.username = root
 jdbc.password = admin!@#

filePath.properties
file.fileUploadPath = D:/NisargPics/
file.filedownloadPath =  D:/NisargPics/download

applicationcontext-servlet.xml
 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
<?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:context="http://www.springframework.org/schema/context"
 xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context.xsd
     http://www.springframework.org/schema/mvc 
     http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<context:annotation-config></context:annotation-config>
<mvc:annotation-driven></mvc:annotation-driven>
 <context:component-scan base-package="org.fileupload.controller"></context:component-scan>
 
 <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
   <property name="location"><value>classpath:resources/dbConfig.properties</value> </property> 
   
 </bean> 

 <!-- Hibernate Configuration -->
 <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
  destroy-method="close">
  <property name="driverClassName" value="${jdbc.driverClassName}" />
  <property name="url" value="${jdbc.url}" />
  <property name="username" value="${jdbc.username}" />
  <property name="password" value="${jdbc.password}" />
 </bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
<property name="dataSource" ref="myDataSource"></property>  
</bean> 
 <bean id="mySessionFactory"
  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="dataSource" ref="myDataSource" />

  <property name="annotatedClasses">
   <list>
   <value>org.fileupload.model.FileuploadVO</value>
    <value>org.fileupload.model.FileUpload</value>
   </list>
  </property>

  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect</prop>
     <prop key="hibernate.show_sql">true</prop>      
      <prop key="hibernate.dbcp.initialSize">8</prop>
      <prop key="hibernate.dbcp.maxActive">20</prop>
      <prop key="hibernate.dbcp.maxIdle">20</prop>
      <prop key="hibernate.dbcp.minIdle">0</prop>
    <prop key="hibernate.hbm2ddl.auto">none</prop>
   </props>
  </property>
  
 </bean>
 <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
  <constructor-arg ref="mySessionFactory" />
 </bean>

 <!-- list of bean definations -->
 <bean id="fileuploadDAO" class="org.fileupload.dao.fileUploadDaoImpl">
  <constructor-arg  ref="hibernateTemplate" />
   <!-- <constructor-arg  index ="1" ref="jdbcTemplate" ></constructor-arg> --> 
 </bean> 
  
<bean id="fileuploadService" class="org.fileupload.service.fileUploadServiceImpl">
 </bean>                          

 <bean
  class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  <property name="cacheSeconds" value="0" />
 </bean>
  
 <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="5242880" />
    </bean> 

</beans>
 

Deployment Descriptor - web.xml 

 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
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 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></display-name>

 <welcome-file-list>
  <welcome-file>FileUpload.jsp</welcome-file>
 </welcome-file-list> 
 
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/applicationcontext-servlet.xml</param-value>
 </context-param>

 <listener>
  <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
 </listener>

 <servlet>
  <servlet-name>applicationcontext</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>applicationcontext</servlet-name>
  <url-pattern>*.htm</url-pattern>
 </servlet-mapping>

</web-app>

JSP for uploading file 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
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
<!DOCTYPE html>
<html>
<head>
  <title>File Upload Example using AngularJS</title>
 <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> 
<script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>
<script type="text/javascript">

 var myApp = angular.module('uploadApp', []);

    myApp.controller('uploadController', function ($scope) {

        // GET THE FILE INFORMATION.
        $scope.getFileDetails = function (e) {

            $scope.files = [];
            $scope.$apply(function () {

                // STORE THE FILE OBJECT IN AN ARRAY.
                for (var i = 0; i < e.files.length; i++) {
                    $scope.files.push(e.files[i]);
                }

            });
        };

        // NOW UPLOAD THE FILES.
        $scope.uploadFiles = function () {

            //FILL FormData WITH FILE DETAILS.
            var data = new FormData();

            for (var i in $scope.files) {
                data.append("file", $scope.files[i]);
    console.log($scope.files[i]);
            }

            // ADD LISTENERS.
            var objXhr = new XMLHttpRequest();
            objXhr.addEventListener("progress", updateProgress, false);
            objXhr.addEventListener("load", transferComplete, false);

            // SEND FILE DETAILS TO tHE API.
           objXhr.open("POST", "/SpringFileUpload_Download/Testupload.htm");
            objXhr.send(data);
        }

        // UPDATE PROGRESS BAR.
        function updateProgress(e) {
            if (e.lengthComputable) {
                document.getElementById('pro').setAttribute('value', e.loaded);
                document.getElementById('pro').setAttribute('max', e.total);
            }
        }

        // CONFIRMATION.
        function transferComplete(e) {
            alert("Files uploaded successfully.");
        }
    }); 
</script>
<body ng-app="uploadApp">

    <div ng-controller="uploadController" >
           <p><progress id="pro" value="0"></progress></p>
     <div class="form-group  form-horizontal">
        <input type="file" id="file" name="file" multiple
            onchange="angular.element(this).scope().getFileDetails(this)" class="input-file"/>

  </div>
  <div class="col-md-4">
        <input type="button" ng-click="uploadFiles()" value="Upload"  class="btn btn-primary"/>

</div>
     
    </div>

</body>

success file for upload 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
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>

        <p>Awesome.. Following file  is uploaded successfully.</p>
         <table width="80%" border="1" cellspacing="0" cellpadding="5">
        <tr>
            <th width="4%">No</th>
            <th width="30%">Filename</th>
            
            <th width="20%">&nbsp;</th>
        </tr>
        <c:choose>
            <c:when test="${files != null}">
                <c:forEach var="file" items="${files}" varStatus="counter">
                    <tr>
                        <td>${counter.index + 1}</td>
                        <td>${file}</td>
                        
                       <td><div align="center"><a href="download.htm?id=${ids}">Download</a> </div></td>
                        
                    </tr>
                </c:forEach>
            </c:when>
        </c:choose>
    </table>
</body>
</html>

screen will look like given below:






Thanks for reading this article 
for any query ping me on npjava90@gmail.com



Tuesday 16 February 2016

Struts with jasper Report Example

Hello Friends hope you all are fine.now its time to move towards struts framework.i will update about struts . i hope you all have basic understanding of struts framework.in this example i will be using Struts 2.x.


Struts  is also MVC Framework  like Spring.in this Example i will be integrating Jasper Report with Struts Framework. Enjoy Code guys.

Apart from struts 2.x distribution ,jasper Jars also required to  make application runnable.you can get jasper jars from http://community.jaspersoft.com/project/jasperreports-library/releases.

one additional jar is required struts2-jasperreports-plugin-2.3.jar


Project Structure will look like given below :


in Spring mvc we have model ,view,controller. where as Struts is also mvc. but we call controller as Action Class.

Action Class is given below :
package org.jasper;
import java.util.HashMap;
import java.util.Map;
import com.opensymphony.xwork2.ActionSupport;

public class StudentJasperAction extends ActionSupport {

/**
*
*/
private static final long serialVersionUID = 1L;

private Map<String, Object> param=null;

private String studId;
private String rptFmt;
 
public String getRptFmt() {
return rptFmt;
}

public void setRptFmt(String rptFmt) {
this.rptFmt = rptFmt;
}





public String getStudId() {
return studId;
}

public void setStudId(String studId) {
this.studId = studId;
}

public Map<String, Object> getParam() {
return param;
}


public void setParam(Map<String, Object> param) {
this.param = param;
}


public String execute() throws Exception {
   
        try {
    param = new HashMap<String,Object>();
   
    param.put("studid", new Integer(studId));
    param.put("Title", "Student  Details");
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }

        return SUCCESS;
    }

 
}


 I have used StrutsResultSupport to  customize view.the below code render jasper report .
package org.jasper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.query.JRQueryExecuterFactory;
import net.sf.jasperreports.engine.util.JRProperties;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.StrutsResultSupport;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.util.ValueStack;

public class LoadJasperReportAction extends StrutsResultSupport {

protected String parameters;
protected String rptFormat;

protected String studId;

public String getRptFormat() {
return rptFormat;
}

public void setRptFormat(String rptFormat) {
this.rptFormat = rptFormat;
}

public String getParameters() {
return parameters;
}

public void setParameters(String parameters) {
this.parameters = parameters;
}

public String findParam(String key, Map<String, Object> params) {
Object obj = params.get(key);
if (obj != null) {
String[] values = (String[]) obj;
return values.length > 0 ? values[0] : null;
}
return (String) obj;
}

@Override
protected void doExecute(String arg0, ActionInvocation arg1)
throws Exception {
ActionContext context = ActionContext.getContext();
Map<String, Object> params = context.getParameters();
String studentId = findParam("studId", params);

try {
String reportFileName = "StudentReport";
Connection conn = null;

Class.forName("com.mysql.jdbc.Driver");

conn = DriverManager
.getConnection("jdbc:mysql://localhost:3306/studentdb",
"root", "admin!@#");

HttpServletRequest request = ServletActionContext.getRequest();

ValueStack stack = arg1.getStack();


parameters = conditionalParse(parameters, arg1);
String contextPath = request.getSession().getServletContext()
.getRealPath("/report/" + reportFileName + ".jrxml");
try {

InputStream input = new FileInputStream(new File(contextPath));

System.out.println("Context Path is  : =" + contextPath);
JasperDesign jasperDesign = JRXmlLoader.load(input);

System.out.println("Compiling Report Designs");

JasperReport jasperReport = JasperCompileManager
.compileReport(jasperDesign);

jasperReport.setProperty(
"net.sf.jasperreports.query.executer.factory.plsql",
"com.jaspersoft.jrx.query.PlSqlQueryExecuterFactory");

JRProperties.setProperty(
JRQueryExecuterFactory.QUERY_EXECUTER_FACTORY_PREFIX
+ "plsql",
"com.jaspersoft.jrx.query.PlSqlQueryExecuterFactory");
System.out.println("Creating JasperPrint Object");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("studId", studentId);

JasperPrint jasperPrint = JasperFillManager.fillReport(
jasperReport, parameters, conn);

int pages = jasperPrint.getPages().size();
if (pages != 0) {
File f = new File("d:\\struts1.pdf");
f.createNewFile();

// Exporting the report
OutputStream output = new FileOutputStream(f);

JasperExportManager.exportReportToPdfStream(jasperPrint,
output);

System.out.println("Report Generation Complete");
} else {
System.out.println(" NO DATA FOUND TO EXPORT .....");
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}

} catch (Exception e) {
e.printStackTrace();
}
}

}

Configration file is given below.

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />

<package name="default" extends="struts-default" namespace="/">
 
  <result-types>
    <result-type name="jasper1" class="org.jasper.LoadJasperReportAction"/>
  </result-types>

  <action name="studentJasperCall" class="org.jasper.StudentJasperAction">
        <result name="success" type="jasper1">
            <param name="parameters">parameters</param>
            <param name="rptFormat">rptFmt</param>
        </result>
    </action>

</package>



</struts>

JSP PAGE : 

Student.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Jasper Report Using struts 2.x</title>

</head>
<body>

<s:actionerror/>

<s:form name="reportForm" action="studentJasperCall.action" metod="post" >

<TABLE id="reptbl" width="400px" border="2">
  <TR>
  <td>
Enter Student id : <s:textfield name="studId" label="stud" /> <s:submit  value="Generate Student Report" type="button"/>
 </td>
 <td>
 <s:radio label="format" name="rptFmt" list="#{'pdf':'PDF'}" value="pdf" />
 </td>

</TR>

</TABLE>

</s:form>

</body>

</html>

Deployment Descriptor File
web.xml

<?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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Struts2JasperExample</display-name>
  <welcome-file-list>
    <welcome-file>/Student.jsp</welcome-file>
  </welcome-file-list>
 <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>

</filter-mapping>


</web-app>

i am putting .jrxml file also .you can check and change according to your need using Ireport Tool :
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="StudentReport" pageWidth="500" pageHeight="600" columnWidth="450" leftMargin="5" rightMargin="5" topMargin="10" bottomMargin="1" uuid="71627f29-0436-4965-9e9b-c02d851e0893">
<property name="ireport.zoom" value="1.0"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="0"/>
<style name="Arial" isDefault="true" fontName="Arial" isBold="false" isItalic="false" isUnderline="false" isStrikeThrough="false" pdfFontName="Helvetica" pdfEncoding="Cp1252" isPdfEmbedded="false"/>
<parameter name="Title" class="java.lang.String"/>
<parameter name="studid" class="java.lang.Integer"/>
<queryString>
<![CDATA[select id,name,college from student]]>
</queryString>
<field name="id" class="java.lang.String"/>
<field name="name" class="java.lang.String"/>
<field name="college" class="java.lang.String"/>
<title>
<band height="50" splitType="Stretch">
<textField isBlankWhenNull="true">
<reportElement style="Arial" x="40" y="0" width="370" height="30" uuid="aab52a34-7a15-413b-812b-0f5413d160cf"/>
<textElement textAlignment="Center">
<font size="22"/>
</textElement>
<textFieldExpression><![CDATA[$P{Title}]]></textFieldExpression>
</textField>
</band>
</title>
<pageHeader>
<band height="20" splitType="Stretch">
<textField>
<reportElement style="Arial" mode="Opaque" x="0" y="5" width="490" height="15" forecolor="#999999" backcolor="#777765" uuid="221943d8-6682-4b54-9096-de22d99fde6a"/>
<textElement textAlignment="Center"/>
<textFieldExpression><![CDATA["Student Details "]]></textFieldExpression>
</textField>
</band>
</pageHeader>
<columnHeader>
<band height="20" splitType="Stretch">
<staticText>
<reportElement style="Arial" mode="Opaque" x="0" y="4" width="170" height="15" backcolor="#e3d9b4" uuid="4f05471d-ee17-42bc-afc7-4e474112b80f"/>
<textElement textAlignment="Left"/>
<text><![CDATA[ID]]></text>
</staticText>
<staticText>
<reportElement style="Arial" positionType="Float" mode="Opaque" x="170" y="4" width="170" height="15" backcolor="#e3d9b4" uuid="eb3e1f67-d402-432f-9faa-4174561d41cd"/>
<text><![CDATA[Name]]></text>
</staticText>
<staticText>
<reportElement style="Arial" positionType="Float" mode="Opaque" x="340" y="4" width="150" height="15" backcolor="#CBB453" uuid="ed2ace5c-9d4f-4c2d-baa9-c3a304949b60"/>
<text><![CDATA[College]]></text>
</staticText>
</band>
</columnHeader>
<detail>
<band height="20" splitType="Stretch">
<textField>
<reportElement x="0" y="4" width="170" height="15" uuid="818a285b-f0a1-42a0-95e5-04e630bf965e"/>
<textElement textAlignment="Left"/>
<textFieldExpression><![CDATA[$F{id}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow="true">
<reportElement positionType="Float" x="170" y="4" width="170" height="15" uuid="8d258287-9e74-44d6-9756-a5dfe7b98c25"/>
<textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow="true">
<reportElement positionType="Float" x="340" y="4" width="150" height="15" uuid="cb56f92e-f5ab-4510-891b-8c2d8f864f33"/>
<textFieldExpression><![CDATA[$F{college}]]></textFieldExpression>
</textField>
</band>
</detail>
<pageFooter>
<band height="40" splitType="Stretch">
<textField>
<reportElement x="200" y="20" width="85" height="15" uuid="a22dda99-774c-497f-9295-fe2a487b7373"/>
<textElement textAlignment="Right"/>
<textFieldExpression><![CDATA["Page " + String.valueOf($V{PAGE_NUMBER})]]></textFieldExpression>
</textField>
<textField evaluationTime="Report">
<reportElement x="285" y="20" width="75" height="15" uuid="51a9c0af-8bd0-447e-a492-ef0e7df1fdd8"/>
<textElement textAlignment="Left"/>
<textFieldExpression><![CDATA[" of " + String.valueOf($V{PAGE_NUMBER})]]></textFieldExpression>
</textField>
</band>
</pageFooter>
<summary>
<band height="35" splitType="Stretch">
<textField isStretchWithOverflow="true">
<reportElement style="Arial" x="175" y="20" width="165" height="15" uuid="87b3c116-0ea9-4bcc-b3f4-9cbb1a5f5e2b"/>
<textElement textAlignment="Center"/>
<textFieldExpression><![CDATA["Total Number of Students : " +
String.valueOf($V{REPORT_COUNT})]]></textFieldExpression>
</textField>
</band>
</summary>
</jasperReport>


snapshot of application :



Any Suggetion will be appreciated.Thanks for reading this article.
For any Query get in touch with me on npjava90@gmail.com









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...