Friday 18 September 2015

Spring Batch Processing Example

Hello Friends ,hope you all are fine.today i am going to demonstrate you ,how we can configure spring batch application.

Spring batch is useful to  process large volume data.consider scenario where we want to read data from database and write those all data into xml file.in this we can use Spring Batch.Spring Batch Provides classes and api's to read/write resources, transaction management,job processing statistics etc.

Apart from Spring jars, i have used two main jars which will be used for batch processing  :
(1)spring-batch-core-2.2.0.RELEASE.jar,
(2)spring-batch-infrastructure-2.2.0.RELEASE.jar

In this example i have used maven project structure ,i will read all files from particular directory ,make one zip of it and then i will dump all file details of that particular directory in database, apart from that i am also keeping track how many times batch will get executed.

Project Structure is look like given below :


database script ::

(1)

DROP TABLE IF EXISTS `studentdb`.`batchstrn`;
CREATE TABLE  `studentdb`.`batchstrn` (
  `BATCHRUNID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `BATCHID` int(10) unsigned NOT NULL,
  `REQDATE` datetime NOT NULL,
  `PROCSTARTDATE` datetime NOT NULL,
  `STATUSCODE` varchar(45) NOT NULL,
  PRIMARY KEY (`BATCHRUNID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

(2)

DROP TABLE IF EXISTS `studentdb`.`zip_dtl`;
CREATE TABLE  `studentdb`.`zip_dtl` (
  `ZIP_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `FILE_NAME` varchar(45) NOT NULL,
  `FILE_PATH` varchar(45) NOT NULL,
  PRIMARY KEY (`ZIP_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=288 DEFAULT CHARSET=latin1;





Main Class  :
package org.zip;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
//@Component
public class App {

public static void main(String[] args) {

App obj = new App();
obj.run();


}

private void run() {

String[] springConfig = { "spring/batch/jobs/job-zip-gen.xml" }; //xml that contains job configuration parameters

ApplicationContext context = new ClassPathXmlApplicationContext(springConfig);

JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
Job job = (Job) context.getBean("zipGenJob");


try {

JobExecution execution = jobLauncher.run(job, new JobParameters());
System.out.println("Exit Status : " + execution.getStatus());
System.out.println("Exit Status : " + execution.getAllFailureExceptions());

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

}

System.out.println("Done");

}

}


The Configuration file for job is as given below :
job-zip-gen.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/batch
http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/task
        http://www.springframework.org/schema/task/spring-task-3.2.xsd
">


<import resource="../config/context.xml" />

<context:annotation-config/>
<context:component-scan base-package="org.zip"></context:component-scan>


<!-- datasource -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/studentdb" />
<property name="username" value="root" />
<property name="password" value="admin!@#" />
</bean>

<!-- <bean id="baseReader" class="org.springframework.batch.item.database.JdbcCursorItemReader">
        <property name="dataSource" ref="dataSource" />
        <property name="sqlQuery" value="select * from contact" />
</bean> -->


<job id="zipGenJob" xmlns="http://www.springframework.org/schema/batch">

<step id="zipGen">
   <tasklet ref="ZipGenerationTasklet" />
</step>
</job>


<bean id="ZipGenerationTasklet" class="org.zip.tasklet.ZipGenerationTasklet" >

<!-- <property name="dataSource" ref="dataSource"/> -->
<!-- <property name="directory" value="file:csv/inputs/" /> -->
<!--  <property name="SOURCE_FOLDER" value="${zip.batch.output_zip_file}"></property> -->
<!-- <property name="OUTPUT_ZIP_FILE" value="${zip.batch.source_folder}"></property> -->

</bean>



<!-- <task:scheduled-tasks>
   
<task:scheduled ref="zipGenJob" method="run" cron="*/5 * * * * *" />
   </task:scheduled-tasks>   -->

</beans>

context.xml

<beans xmlns="http://www.springframework.org/schema/beans"
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.2.xsd">


<bean id="jobRepository"
class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
<property name="transactionManager" ref="transactionManager" />
</bean>
 
<bean id="transactionManager"
class="org.springframework.batch.support.transaction.ResourcelessTransactionManager" />

<bean id="jobLauncher"
class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
</bean>

<!-- addd by nisarg pathak  -->

<!-- Read property -->

<bean id="envProperties"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:META-INF/i18n/zip-batch.properties</value>
</list>
</property>
</bean>


</beans>

Model Class :

package org.zip.model;

import java.io.Serializable;

public class ZIPGEN implements Serializable {


/**
*
*/
private static final long serialVersionUID = 1L;
private int  ZIP_ID;
private String FILE_NAME;
public int getZIP_ID() {
return ZIP_ID;
}
public void setZIP_ID(int zIP_ID) {
ZIP_ID = zIP_ID;
}
public String getFILE_NAME() {
return FILE_NAME;
}
public void setFILE_NAME(String fILE_NAME) {
FILE_NAME = fILE_NAME;
}
public String getFILE_PATH() {
return FILE_PATH;
}
public void setFILE_PATH(String fILE_PATH) {
FILE_PATH = fILE_PATH;
}
private String FILE_PATH;



}



Tasklet to get files as well as dump those file details is as given below :

package org.zip.tasklet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.sql.DataSource;

import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.stereotype.Component;

@Component
public class ZipGenerationTasklet implements Tasklet, InitializingBean,StepExecutionListener {

/*private Resource directory;*/
List<String> fileList =new ArrayList<String>();
    private  String OUTPUT_ZIP_FILE= "D:\\MyFile.zip";
    private String SOURCE_FOLDER ="D:\\NisargPics";

private JdbcTemplate jdbcTemplate;
int batchid;
BigInteger batch_run_id;
private long batchId=2;

private SimpleJdbcCall simpleJdbcCall;
@Autowired
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
simpleJdbcCall = new SimpleJdbcCall(dataSource).withFunctionName("get_id");
}

@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {



System.out.println("Proc call to get auto incr. value .....!");

SqlParameterSource  mapParam = new MapSqlParameterSource().addValue("name_","zip_dtl");


Map<String,Object> map =  simpleJdbcCall.execute(mapParam);

System.out.println("Executing The Procedure  .....!");
BigInteger id = (BigInteger)map.get("sequence_no_");

// batch_run_id=jdbcTemplate.queryForObject("SELECT sequence_no+1 FROM sequence_generate_tab", BigInteger.class);

String sql="INSERT INTO BATCHSTRN (BATCHRUNID,BATCHID,REQDATE,PROCSTARTDATE,STATUSCODE)"
+ "VALUES (?, ?, ?, ?, 'S')";

jdbcTemplate.update(sql,batch_run_id,batchId,getCurrentTimeStamp(),getCurrentTimeStamp());



System.out.println("Execution Start .....!");

generateFileList(new File(SOURCE_FOLDER));
zipIt(OUTPUT_ZIP_FILE,id);
   


System.out.println("Execution End .....!");

return RepeatStatus.FINISHED;

}
/*
public Resource getDirectory() {
return directory;
}

public void setDirectory(Resource directory) {
this.directory = directory;
}
*/
public void zipIt(String zipFile, BigInteger id){

//System.out.println("id:::::::::->"+id);

String sql = "INSERT INTO ZIP_DTL " +
"(ZIP_ID,FILE_NAME, FILE_PATH) VALUES (?, ?, ?)";
    byte[] buffer = new byte[1024];

    try{

    FileOutputStream fos = new FileOutputStream(zipFile);
    ZipOutputStream zos = new ZipOutputStream(fos);

    System.out.println("Output to Zip : " + zipFile);

    int i =2;
    for(String file : this.fileList){
   
    System.out.println("File Added : " + file);
   
    //
   
    jdbcTemplate.update(sql,new Object[]{id,file,file});
     
    i=i+1;
     
   
    ZipEntry ze= new ZipEntry(file);
        zos.putNextEntry(ze);

        FileInputStream in =
                      new FileInputStream(SOURCE_FOLDER + File.separator + file);

        int len;
        while ((len = in.read(buffer)) > 0) {
        zos.write(buffer, 0, len);
        }

        in.close();
    }

    zos.closeEntry();
    //remember close it
    zos.close();

    System.out.println("Done");
   }catch(IOException ex){
      ex.printStackTrace();  
   }
  }

   /**
    * Traverse a directory and get all files,
    * and add the file into fileList
    * @param node file or directory
    */
   public void generateFileList(File node){

    //add file only
if(node.isFile()){
fileList.add(generateZipEntry(node.getAbsoluteFile().toString()));
}

if(node.isDirectory()){
String[] subNote = node.list();
for(String filename : subNote){
generateFileList(new File(node, filename));
}
}

   }

   /**
    * Format the file path for zip
    * @param file file path
    * @return Formatted file path
    */
   private String generateZipEntry(String file){
    return file.substring(SOURCE_FOLDER.length()+1, file.length());
   }

@Override
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub

}

@Override
public ExitStatus afterStep(StepExecution stepExecution) {
// TODO Auto-generated method stub

stepExecution.getJobExecution().getExecutionContext()
.put("BATCHRUNID", batch_run_id);

return null;
}

@Override
public void beforeStep(StepExecution arg0) {
// TODO Auto-generated method stub

}

public static String getCurrentTimeStamp() {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
return strDate;
}
}




for the sake of simplicity , I have shared the  project ,you can download it from following link
Download Project


for any query ping me on npjava90@gmail.com
Happy Learning...!!

Thanks

Friday 1 May 2015

Multiple File Upload Using Spring MVC and Hibernate

Hello Friends,Hope you all are fine,its been very long i posted new post,very hactic schedule,i am going  to demonstrate how we can upload file using future provided by Spring 3.0 with hibernate as a backend.

The Code is as given below :

MODEL CLASS 
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 FileuploadVO {

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;
}

@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

private List<MultipartFile> Files;

public List<MultipartFile> getFiles() {
return Files;
}

public void setFiles(List<MultipartFile> files) {
Files = files;
}

 
}


Controller :

package org.fileupload.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.fileupload.dao.fileUploadDaoImpl;
import org.fileupload.model.FileuploadVO;
import org.fileupload.service.fileUploadServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.multipart.MultipartFile;



@Controller
public class FileUploadController {

//

@RequestMapping(value = "/upload.htm", method = RequestMethod.POST)
    public String SaveImage(
            @ModelAttribute("uploadForm") FileuploadVO uploadForm,
            Model map,HttpServletRequest request ) throws IllegalStateException, IOException {

WebApplicationContext context =WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
fileUploadServiceImpl  service=(fileUploadServiceImpl) context.getBean("fileuploadService");
fileUploadDaoImpl dao=(fileUploadDaoImpl) context.getBean("fileuploadDAO");
ResourceBundle rb = ResourceBundle.getBundle("resources/filePath");  //filePath is Property file
String saveDirectory = rb.getString("file.fileUploadPath");

        List<MultipartFile> listFiles = uploadForm.getFiles();
        List<String> fileNames = new ArrayList<String>();
        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);
                   service.saveImage(uploadForm);
                   
                }
            }
            
        } 
       
        map.addAttribute("files", fileNames);
        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;

}

}


DAO LAYER

package org.fileupload.dao;

import org.fileupload.model.FileuploadVO;

public interface fileUploadDao {

public void saveImage(FileuploadVO fileupload);
 public FileuploadVO downloadImg(String id);
}



package org.fileupload.dao;

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

public class fileUploadDaoImpl  implements fileUploadDao{

private HibernateTemplate template;
public fileUploadDaoImpl(HibernateTemplate template) {
this.template = template;
}
@Override
public void saveImage(FileuploadVO fileupload) {
template.save(fileupload);
}
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;
}
}

SERVICE LAYER:

package org.fileupload.service;

import org.fileupload.model.FileuploadVO;

public interface fiileUploadService {

public void saveImage(FileuploadVO fileupload);
public FileuploadVO downloadImg(String id);
}

package org.fileupload.service;

import org.fileupload.dao.fileUploadDaoImpl;
import org.fileupload.model.FileuploadVO;
import org.springframework.beans.factory.annotation.Autowired;

public class fileUploadServiceImpl  implements fiileUploadService{

@Autowired
private fileUploadDaoImpl fileuploadDAO;
@Override
public void saveImage(FileuploadVO fileupload) {
fileuploadDAO.saveImage(fileupload);
}
public FileuploadVO downloadImg(String id) {

return fileuploadDAO.downloadImg(id);

}

}

dbConfig.properties

jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/studentdb
jdbc.username = root
jdbc.password = admin!@#


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" 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>Optic Solution</display-name>

<welcome-file-list>
<welcome-file>index.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>

applicationcontext-servlet.xml

<?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: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="mySessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />

<property name="annotatedClasses">
<list>

<value>org.fileupload.model.FileuploadVO</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" />
</bean>

<bean id="fileuploadService" class="org.fileupload.service.fileUploadServiceImpl">
</bean> 

<bean id="JsonMapper" class="org.optical.handler.JsonMapper"></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>



index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
  <head><title>Upload and Download files using Spring</title></head>
  <body>
   
    <h2>Add New File</h2>
    
   <%--  <form action="upload.htm" method="post" enctype="multipart/form-data">
        <table width="60%" border="1" cellspacing="0">
            <tr>
                <td width="35%"><strong>File to upload</strong></td>
                <td width="65%"><input type="file" name="file" /></td>
            </tr>
            <tr>
                <td><strong>Notes</strong></td>
                <td><input type="text" name="notes" width="60" /></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input type="submit" name="submit" value="Add"/></td>
            </tr>
        </table>
    </form> --%>
     <form:form method="post" action="upload.htm"
            modelAttribute="uploadForm" enctype="multipart/form-data">
            <p>Select files to upload. Press Add button to add more file
                inputs.</p>
            <table id="fileTable">
                <tr>
                    <td><input name="files[0]" type="file" /></td>
                </tr>
                <tr>
                    <td><input name="files[1]" type="file" /></td>
                </tr>
            </table>
            <br />
            <input type="submit" value="Upload" />
            <input id="addFile" type="button" value="Add File" />
        </form:form>
  </body>
</html>


uploadfilesuccess.jsp

<%@ 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>
                        </td>
                    </tr>
                </c:forEach>
            </c:when>
        </c:choose>
    </table>
</body>
</html>



Screenshot of application is as given below: 






Thanks for reading this article 
for any query ping me on pathak.nisarg@yahoo.com










Thursday 16 October 2014

Spring MVC with Jqgrid Subgrid using Hibernate ORM

Hello Friends hope you all are fine.today i am going to demonstrate you example of subgrid using spring mvc framework.the table structure will look like given below :

DROP TABLE IF EXISTS `studentdb`.`student`;
CREATE TABLE  `studentdb`.`student` (
  `id` varchar(20) NOT NULL,
  `name` varchar(50) NOT NULL,
  `college` varchar(45) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

DROP TABLE IF EXISTS `studentdb`.`location`;
CREATE TABLE  `studentdb`.`location` (
  `id` varchar(20) NOT NULL,
  `name` varchar(40) NOT NULL,
  `code` varchar(45) NOT NULL,
  `address` varchar(45) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Spring Controller will look given below :

package org.subgrid.controller;

import java.io.IOException;
import java.util.Map;

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

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.subgrid.dao.SubgridDaoImpl;
import org.subgrid.handler.JsonMapper;
import org.subgrid.service.SubgridService;


@Controller
public class SubgridController {

   
    //for subgrid demo
    @RequestMapping(value = "/getstudentDetails", method = RequestMethod.GET)
     public @ResponseBody void getstudentDetails( HttpServletRequest req,HttpServletResponse res,String para) throws IOException
     {
         //try{
               int page = Integer.valueOf(req.getParameter("page"));
               int limit =Integer.valueOf(req.getParameter("rows"));
               String sidx = req.getParameter("sidx");
               String sord =req.getParameter("sord");
             
             
               WebApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(req.getSession().getServletContext());
                     
               SubgridDaoImpl dao=(SubgridDaoImpl) context.getBean("SubgridDaoImpl");
               SubgridService service =(SubgridService) context.getBean("SubgridService");
              
               Map<String, Object>map=service.getstudentDetails(dao, page, limit, sidx, sord, req, para);
          
               JsonMapper mapper=(JsonMapper) context.getBean("JsonMapper");
               mapper.WritecInJson(res, map);
             
     }
   
   //for subgrid demo
   
    @RequestMapping(value = "/getLocationDetails", method = RequestMethod.GET)
     public @ResponseBody void getLocationDetails(HttpServletRequest req,HttpServletResponse res,String para) throws IOException
     {
         //try{
             
               String id = req.getParameter("id");
            
               WebApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(req.getSession().getServletContext());
                     
               SubgridDaoImpl dao=(SubgridDaoImpl) context.getBean("SubgridDaoImpl");
               SubgridService service =(SubgridService) context.getBean("SubgridService");

               Map<String, Object>map=service.getLocationDetails(dao, req, para,id);
         
               JsonMapper mapper=(JsonMapper) context.getBean("JsonMapper");
               mapper.WritecInJson(res, map);
     }
   
}

DAO layer will look like given below:
package org.subgrid.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.subgrid.entity.LocationDetail;
import org.subgrid.entity.Student;


@Repository
public class SubgridDaoImpl {

    private HibernateTemplate template;
   
       
        public SubgridDaoImpl(HibernateTemplate template) {
            this.template = template;
        }   
   
        public Map<String, Object> getstudentDetails(int page, int limit, String sidx,
                String sord, HttpServletRequest req, String para)
        {
            List<Student> acclist=template.find("from Student");
            Map<String, Object> map=new HashMap<String, Object>();
            map.put("page", page);
            map.put("list", acclist);
            return map;   

        }
        public Map<String, Object> getLocationDetails(HttpServletRequest req, String para,
                String id) {
           
            List<LocationDetail> acclist=template.find("from LocationDetail where id='"+id+"'");
            Map<String, Object> map=new HashMap<String, Object>();
            map.put("list", acclist);
            return map;   
           
        }
}
Service Layer:

package org.subgrid.service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.subgrid.dao.SubgridDaoImpl;
import org.subgrid.entity.LocationDetail;
import org.subgrid.entity.Student;

@Service
public class SubgridService {


    //for subgrid by nisarg pathak
    public Map<String, Object> getstudentDetails(SubgridDaoImpl dao, int page,
            int limit, String sidx, String sord, HttpServletRequest req,
            String para) {
      
        Map<String, Object> map = dao.getstudentDetails(page, limit, sidx, sord,
                req, para);

        List<Student> list = (List<Student>) map
                .get("list");

        Map<String, Object> AccountingPeriodMap = new LinkedHashMap<String, Object>();
        List<Map<String, Object>> AccountingPeriodList = new ArrayList<Map<String, Object>>();

        Map<String, Object> AccountingPeriodSubMap = null;
        List<String> cell = null;
        int i = 0;
        for (Student supp : list) {
            i++;
            AccountingPeriodSubMap = new LinkedHashMap<String, Object>();
            AccountingPeriodSubMap.put("id", i);
            cell = new ArrayList<String>();
            cell.add(supp.getId()+ "");
            cell.add(supp.getName()+ "");
            cell.add(supp.getCollege()+ "");
           
            AccountingPeriodSubMap.put("cell", cell);
            AccountingPeriodList.add(AccountingPeriodSubMap);
        }
        AccountingPeriodMap.put("rows", AccountingPeriodList);
        AccountingPeriodMap.put("page", map.get("page"));
        AccountingPeriodMap.put("total", map.get("total"));
        AccountingPeriodMap.put("records", map.get("records"));
        return AccountingPeriodMap;
    }
    //for subgrid demo
    public Map<String, Object> getLocationDetails(SubgridDaoImpl dao,
            HttpServletRequest req, String para, String id) {
      
        Map<String, Object> map = dao.getLocationDetails(req, para,id);

        List<LocationDetail> list = (List<LocationDetail>) map
                .get("list");

        Map<String, Object> AccountingPeriodMap = new LinkedHashMap<String, Object>();
        List<Map<String, Object>> AccountingPeriodList = new ArrayList<Map<String, Object>>();

        Map<String, Object> AccountingPeriodSubMap = null;
        List<String> cell = null;
        int i = 0;
        for (LocationDetail supp : list) {
            i++;
            AccountingPeriodSubMap = new LinkedHashMap<String, Object>();
            AccountingPeriodSubMap.put("id", i);
            cell = new ArrayList<String>();
            cell.add(supp.getId() + "");
            cell.add(supp.getName()+ "");
            cell.add(supp.getAddress()+ "");

            AccountingPeriodSubMap.put("cell", cell);
            AccountingPeriodList.add(AccountingPeriodSubMap);
        }
        AccountingPeriodMap.put("rows", AccountingPeriodList);
        AccountingPeriodMap.put("page", map.get("page"));
        AccountingPeriodMap.put("total", map.get("total"));
        AccountingPeriodMap.put("records", map.get("records"));
        return AccountingPeriodMap;
    }

   
}
Json Handler Class:

package org.subgrid.handler;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;

    public class JsonMapper {
       
        public void WritecInJson(HttpServletResponse res,Object object)
        {
        MappingJacksonHttpMessageConverter jsonConverter = new MappingJacksonHttpMessageConverter();
        MediaType jsonMimeType = MediaType.APPLICATION_JSON;
       
        if(jsonConverter.canWrite(object.getClass(), jsonMimeType)){
            try{
            jsonConverter.write(object , jsonMimeType, new ServletServerHttpResponse(res));
       
            }catch(IOException e){
                e.printStackTrace();
            }catch(HttpMessageNotWritableException e){
                e.printStackTrace();
            }catch(Exception e){
                e.printStackTrace();
            }
        }else{
            System.out.println("reached in else");
        }

        }
    }

 Entity Classes:
package org.subgrid.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="student")
public class Student {

    @Id @Column @GeneratedValue
    private String id;
    public String getId() {
        return id;
    }


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


    public String getName() {
        return name;
    }


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


    public String getCollege() {
        return college;
    }


    public void setCollege(String college) {
        this.college = college;
    }


    @Column
    private String name;
    @Column
    private String college;
   
   
    public Student() {
        // TODO Auto-generated constructor stub
    }
   
   
}

package org.subgrid.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity
@Table(name="location")
public class LocationDetail {

    @Id @Column @GeneratedValue
    private String id;
    @Column
    private String name;
    @Column
    private String code;
    @Column
    private String address;
   
    public LocationDetail() {
        // TODO Auto-generated constructor stub
    }

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
   
   
   
   
   
}

Db Configuration Property File:

jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/studentdb
jdbc.username = root
jdbc.password = admin!@#


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" 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>Optic Solution</display-name>

    <welcome-file-list>
        <welcome-file>index.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>*.html</url-pattern>
    </servlet-mapping>


</web-app>

applicationcontext-servlet.xml

<?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:component-scan base-package="org.subgrid.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="mySessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />

        <property name="annotatedClasses">
            <list>

                <value>org.subgrid.entity.LocationDetail</value>
                <value>org.subgrid.entity.Student</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>
   
    <bean id="SubgridDaoImpl" class="org.subgrid.dao.SubgridDaoImpl">
        <constructor-arg ref="hibernateTemplate" />
    </bean>
   
    <bean id="SubgridService" class="org.subgrid.service.SubgridService">
    </bean>
   
    <bean id="JsonMapper" class="org.subgrid.handler.JsonMapper"></bean>
   
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="cacheSeconds" value="0" />
    </bean>
</beans>
   
index.jsp


<link rel="shortcut icon" href="images/icon.png">
<link type="text/css" rel="stylesheet" href="css/layout-default-latest.css" />
<link type="text/css" rel="stylesheet" href="css/bootstrap.min.css" id="default">

<link type="text/css" rel="stylesheet" href="css/font-awesome.min.css">
<link type="text/css" rel="stylesheet" href="css/jquery-ui.css">
<link type="text/css" rel="stylesheet" href="css/style.css" />
<link type="text/css" rel="stylesheet" href="css/ui.jqgrid.css"/>

    <link rel="stylesheet" type="text/css" href="css/smart-forms.css">
  <link rel="stylesheet" type="text/css" href="css/tabs.css">



<script type="text/javascript" src="script/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="script/bootstrap.js"></script>
<script type="text/javascript" src="script/jquery-ui.min.js"></script>
<script type="text/javascript" src="script/jquery.layout-latest.js"></script>
<script type="text/javascript" src="script/local/grid.locale-en.js" ></script>
<script type="text/javascript" src="script/jquery.jqGrid.min.js"></script>
<script type="text/javascript" src="script/jquery-ui-messageBox.js"></script>
<script type="text/javascript" src="script/jquery.blockUI.js"></script>
<script type="text/javascript" src="script/js/tabs.js"></script>


<script type="text/javascript" src="script/js/javascript.js"></script>



<script type="text/javascript">
jQuery(document).ready(function(){
 
    jQuery("#list14").jqGrid({
        url:'getstudentDetails.html',
                datatype: "json",
                colNames:['id',' Name','College'],
                colModel:[ {name:'id',index:'id'},
                           {name:'name',index:'name'},
                           {name:'college',index:'college'}
                           ],
                           rowNum:10,
                           rowList:[10,20,30],
                           pager: '#pager14', sortname: 'id', viewrecords: true,
                           sortorder: "desc", multiselect: false, subGrid : true,
                           subGridUrl: 'getLocationDetails.html?q=3',
                              subGridModel: [{ name : ['id','Name','Address'], width : [55,200,80],
                              params:['id']} ] ,
                              caption: "Subgrid with JSON Data" });
    jQuery("#list14").jqGrid('navGrid','#pager14',{edit:false,add:false,del:false});
});
</script>




<table id="list14"></table> <div id="pager14"></div>


it will look like given below :

Thanks for Reading this article .. For Any Query Ping me on pathak.nisarg@yahoo.com
Haappy Learning

Sunday 20 July 2014

Spring MVC with Jasper Report Integration

Hello Friends Hope you all are Fine.its been long time that i have posted a new post .well Reporting Tool always plays a major role in enterprise applications. I will going to demonstrate you Jasper Reports. for Designing & configuring Jasper Report i am using Ireport Designer 5.5.0 ,i will be using Traditional Student Application for showing reports.
The Project Structure is look like given below :





for connecting to db using ireport you need to go through https://www.netiq.com/documentation/idm401/reporting/data/bpbyf5y.html

The Report Layout in ireport designer will look like given below :

 You can download japer report jars from http://sourceforge.net/projects/jasperreports/files/

you have to put .jrxml and .jasper file into project classpath . Spring Controller will look like given below:

StudentController.java

package org.demo.controller;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.dbcp.BasicDataSource;
import org.dao.StudentDAO;
import org.demo.model.Student;
import org.springframework.stereotype.Controller;
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.ResponseBody;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

       

@Controller

public class StudentController
{
        @RequestMapping(method = RequestMethod.POST , value = "/GenerateReport")
        public @ResponseBody void generatePdfReport(ModelAndView modelAndView,HttpServletRequest request,HttpServletResponse response) throws SQLException{
   
            WebApplicationContext context =WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
            StudentDAO dao=(StudentDAO)context.getBean("studentDAO");
         
            BasicDataSource dataSource = (BasicDataSource)context.getBean("myDataSource");
            String contextPath = request.getServletContext().getRealPath("report/StudentReport.jrxml");
            dao.generatePdfReport(dataSource,contextPath);
         
         }
       
}
Dao Layer will be as given below :
StudentDAO.java

package org.dao;


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.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.xml.JRXmlLoader;

import org.apache.commons.dbcp.BasicDataSource;
import org.demo.model.Student;
import org.springframework.orm.hibernate3.HibernateTemplate;



public class StudentDAO
{
    private HibernateTemplate template;

    public HibernateTemplate getTemplate() {
        return template;
    }

    public void setTemplate(HibernateTemplate template) {
        this.template = template;
    }

    public StudentDAO(HibernateTemplate template) {
        this.template = template;
    }

     public void generatePdfReport(BasicDataSource dataSource, String contextPath) throws SQLException {
       
        Connection conn= dataSource.getConnection();
       

 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);

            System.out.println("Creating JasperPrint Object");
            Map<String, String> parameters = new HashMap<String, String>();
            parameters.put("ReportTitle", "PDF JasperReport");

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

           // File f = new File("report/StudentReport.pdf");
         
            File f = new File("d:\\StudentReport.pdf");
             f.createNewFile();
         
            //Exporting the report
            OutputStream output = new FileOutputStream(f);

            JasperExportManager.exportReportToPdfStream(jasperPrint, output);

            System.out.println("Report Generation Complete");
            conn.close();
            }
             catch (Exception e) {
            e.printStackTrace();
            }
    }
}

add_student.jsp



<script type="text/javascript" src="script/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="script/bootstrap.js"></script>
<script type="text/javascript" src="script/jquery-ui.min.js"></script>
<script type="text/javascript" src="script/jquery.layout-latest.js"></script>
<script type="text/javascript" src="script/local/grid.locale-en.js" ></script>
<script type="text/javascript" src="script/jquery.blockUI.js"></script>



<script type="text/javascript" src="script/js/javascript.js"></script>

<script type="text/javascript" src="script/js/InitStudent.js"></script>

<script type="text/javascript" src="script/js/StudentLogic.js"></script>

<script type="text/javascript">

    $(document).ready(function(){
       
 $('#GenerateReport').click(function()
             {  
               
    $.ajax({
       
           url: "GenerateReport.html",
           dataType:'json',
           type:'post',
           data:  {},
           success: function (dataCheck)
           {
              },
               error: function (xhr, ajaxOptions, thrownError) {}
        });             
    });
    });
</script>
   
   
   
        <table>
            <tr>
                <td>id:<input type="text" id="txtid" name="txtid"></td>
            </tr>
           
            <tr>
                <td>Name:<input type="text" id="txtname" name="txtname"></td>
            </tr>
           
            <tr>
                <td><input type="button"  id="AddStudent" name="AddStudent" value="submit"></td>
            </tr>
           
            <tr>
                <td><input type="button"  id="GenerateReport" name="GenerateReport" value="Report"></td>
            </tr>
           
           
        </table>


The First page will look like given below:




 You can Refer my earlier Post redirect get Pattern using spring mvc example for xml configuration required for project .

when you click on generate report button file will be stored on D:/.Report will look like given below:






Thanks for Reading this article. for any query ping me on pathak.nisarg@yahoo.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...