Spring 4 MVC Image Jquery Date Upload

spring+4+mvc+image+jquery+data+upload

Click here to download eclipse supported ZIP file



This is index.jsp JSP file and it is used display the output for the application.



<jsp:forward page="customers.html"></jsp:forward>

This is customer.jsp JSP file and it is used display the output for the application.



<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="UTF-8" />
<title>A Customer registration form</title>
<link
href="http://netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"
rel="stylesheet">
<link rel="stylesheet" type="text/css" media="all"
href="css/daterangepicker.css" />
<link rel="stylesheet" type="text/css" media="all" href="css/demo.css" />
<script type="text/javascript"
src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript"
src="http://netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/moment.js"></script>
<script type="text/javascript" src="js/daterangepicker.js"></script>
</head>
<script language="javascript">
$(document).ready(
function() {
$('.configurator input, .configurator select').change(
function() {
updateConfig();
});
$('.demo i').click(function() {
$(this).parent().find('input').click();
});
updateConfig();
function updateConfig() {
var options = {};
$('#dobVal')
.daterangepicker(
options,
function(start, end, label) {
console.log('New date range selected: '
+ start.format('YYYY-MM-DD')
+ ' to '
+ end.format('YYYY-MM-DD')
+ ' (predefined range: '
+ label + ')');
});
}
});
function Validate() {
var image = document.getElementById("image").value;
if (image != '') {
var checkimg = image.toLowerCase();
if (!checkimg.match(/(\.jpg|\.png|\.JPG|\.PNG|\.jpeg|\.JPEG)$/)) {
alert("Please enter Image File Extensions .jpg,.png,.jpeg");
document.getElementById("image").focus();
return false;
}
}
return true;
}
</script>
<body>
<h2>Customer Saving...</h2>
<form:form method="post" action="addCustomer.html"
modelAttribute="customerPojo">
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-2 demo">
<input type="hidden" class="form-control"
id="timePickerIncrement">
<b>Select Date </b><form:input path="dobVal" id="dobVal" class="form-control" />
<i class="glyphicon glyphicon-calendar fa fa-calendar"></i>
</div>
</div>
</div>
<br>
<table align="center">
<tr>
<td><form:label path="firstName">First Name</form:label></td>
<td><form:input path="firstName" id="firstName" /></td>
</tr>
<tr>
<td><form:label path="lastName">Last Name</form:label></td>
<td><form:input path="lastName" id="lastName" /></td>
</tr>
<tr>
<td><form:label path="email">Email</form:label></td>
<td><form:input path="email" id="email" /></td>
</tr>
<tr>
<td><form:label path="phone">Telephone</form:label></td>
<td><form:input path="phone" id="phone" /></td>
</tr>
<tr>
</tr>
<tr>
<td><form:label for="image" path="image">Select Image to upload</form:label><br />
</td>
<td><form:input path="image" id="image" type="file" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Add Customer" /></td>
</tr>
</table>
</form:form>
<br>
<h4 align="center">
<a href="./showCustomer.html">View Customers</a>
</h4>
</body>
</html>

This is findCustomer.jsp JSP file and it is used display the output for the application.



<%@ page language="java" import="com.cv.spring.poc.model.*,java.util.*" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<% Customer customer= (Customer)request.getAttribute("viewCustomer");
%>
<table border="1">
<tr><td>ID</td><td>First Name</td><td>Last Name</td><td>Email</td><td>Phone</td><td>Date</td></tr>
<tr><td><%=customer.getCustomerId()%></td><td><%=customer.getFirstName()%></td><td><%=customer.getLastName()%></td><td><%=customer.getEmail()%></td><td><%=customer.getPhone()%></td><td><%=customer.getCreatedate()%></td></tr>
</table>
<br><br>
<a href="./customers.html">Go to Home</a>

This is showCustomer.jsp JSP file and it is used display the output for the application.



<%@ page language="java" import="com.cv.spring.poc.model.*,java.util.*"
contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
ArrayList<Customer> customers = (ArrayList<Customer>) request
.getAttribute("viewCustomers");
%>
<table border="1">
<tr>
<td>ID</td>
<td>First Name</td>
<td>Last Name</td>
<td>Email</td>
<td>Phone</td>
<td>Date of joined with Us</td>
<td>Date of Birth</td>
</tr>
<%
for (int i = 0; i < customers.size(); ++i) {
Customer customer = customers.get(i);
%>
<tr>
<td><%=customer.getCustomerId()%></td>
<td><%=customer.getFirstName()%></td>
<td><%=customer.getLastName()%></td>
<td><%=customer.getEmail()%></td>
<td><%=customer.getPhone()%></td>
<td><%=customer.getCreatedate()%></td>
<td><%=customer.getDob()%></td>
</tr>
<%} %>
</table>
<br><br>
<a href="./customers.html">Go to Home</a>

This is success.jsp JSP file and it is used display the output for the application.



<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
File save successfully...
<a href="./customers.html">Go to Home</a>
</body>
</html>


This is RestController.java file having the controller logic and it will have the services defined in it.


 

    
package com.cv.spring.mvc;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
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.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.cv.spring.poc.model.Attachment;
import com.cv.spring.poc.model.Customer;
import com.cv.spring.poc.model.CustomerPojo;
import com.cv.spring.poc.services.DataServices;

/**
 @author Chandra Vardhan
 */
@Controller
@SessionAttributes
public class RestController {
  
  private final static Logger LOGGER = Logger.getLogger(RestController.class);
  
  

  @Autowired
  ServletContext servletContext;

  @Autowired
  DataServices dataServices;


  // checks for a valid user and used to login the user

  @RequestMapping(value = "/addCustomer", method = RequestMethod.POST)
  public String addContact(
      @ModelAttribute("customerPojo"CustomerPojo customerPojo,
      BindingResult result, Model model) {
    LOGGER.info("Entered into RestController.addContact(-)");
    try {
      if (customerPojo != null) {
        String image = customerPojo.getImage();
        Attachment attachment = new Attachment();
        Customer customer = new Customer();
        customer.setCreatedate(new Date());
        customer.setEmail(customerPojo.getEmail());
        customer.setFirstName(customerPojo.getFirstName());
        customer.setLastName(customerPojo.getLastName());
        customer.setPhone(customerPojo.getPhone());
        customer.setDob(customerPojo.getDob());
        if (image != null) {
          String imageStoragePath = writeImageToFileSystem(image);
          if (imageStoragePath != null) {
            attachment.setPath(imageStoragePath);
            attachment.setCustomer(customer);
          }
        }
        dataServices.saveAttachments(attachment);
        model.addAttribute("attachment", attachment);
      }
      LOGGER.info("save Successful");
      LOGGER.info("Exiting from RestController.addContact(-)");
      return "success";

    catch (Exception e) {
      return "fail";
    }
    

  }

  private String writeImageToFileSystem(String image) {
    LOGGER.info("Entered into RestController.writeImageToFileSystem(-)");
    if (image != null) {
      BufferedImage bImage = null;
      try {
        File initialImage = new File(image);
        if (initialImage != null) {
          String imageName = initialImage.getName();
          bImage = ImageIO.read(initialImage);
          String fileSystemPath = getFileSystemPath();
          String imageType = null;
          if (imageName != null) {
            String[] paths = imageName.split("\\.");
            imageType = paths[1];
          }
          if (fileSystemPath != null && imageType != null) {

            ImageIO.write(bImage, imageType, new File(
                fileSystemPath + "\\" + imageName));
            return fileSystemPath + "\\" + imageName;
          }
        }
      catch (IOException e) {
        LOGGER.info("Exception occured :" + e.getMessage());
      }
      LOGGER.info("Images were written succesfully.");
    }
    LOGGER.info("Exiting from RestController.writeImageToFileSystem(-)");
    return image;

  }

  private String getFileSystemPath() {
    LOGGER.info("Entered into RestController.getFileSystemPath(-)");
    String path = null;
    if (servletContext != null) {
      String imageStoragePath = servletContext
          .getInitParameter("imageStoragePathInFileSystem");
      if (imageStoragePath != null) {
        File file = new File(imageStoragePath);
        if (!file.exists()) {
          try {
            file.createNewFile();
          catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
      path = imageStoragePath;
    }
    LOGGER.info("Exiting from RestController.getFileSystemPath(-)");
    return path;

  }

  // display the list of users from db
  @RequestMapping(value = "/findCustomer", method = RequestMethod.GET)
  public ModelAndView findCustomer(@RequestParam("id"int id, Model model) {
    LOGGER.info("Entered into RestController.findCustomer(-)");
    ModelAndView modelAndView = new ModelAndView();
    Customer customer = null;

    try {
      customer = dataServices.findCustomer(id);
      modelAndView.addObject("viewCustomer", customer);
      LOGGER.info("user " + customer.getCustomerId()
          + customer.getEmail());
    catch (Exception e) {

    }
    modelAndView.setViewName("findCustomer");
    LOGGER.info("Exiting from RestController.findCustomer(-)");
    return modelAndView;
  }
  
  // display the list of users from db
    @RequestMapping(value = "/showCustomer", method = RequestMethod.GET)
    public ModelAndView showCustomer(Model model) {
      LOGGER.info("Entered into RestController.showCustomer(-)");
      ModelAndView modelAndView = new ModelAndView();
      List<Customer> customers = null;

      try {
        customers = dataServices.showCustomers();
        modelAndView.addObject("viewCustomers", customers);
        /*LOGGER.info("user " + customer.getCustomerId()
            + customer.getEmail());*/
      catch (Exception e) {

      }
      modelAndView.setViewName("showCustomer");
      LOGGER.info("Exiting from RestController.showCustomer(-)");
      return modelAndView;
    }

  @RequestMapping("/customers")
  public ModelAndView showContacts() {
    return new ModelAndView("customer""customerPojo"new CustomerPojo());
  }
}

This is DataDao.java file having the DAO logic to access the database information.


 

    
package com.cv.spring.poc.dao;

import java.util.List;

import com.cv.spring.poc.model.Attachment;
import com.cv.spring.poc.model.Customer;
/**
@author Chandra Vardhan
*/
public interface DataDao {

  public List<Customer> showCustomers();

  public Customer findCustomer(int id);

  public void saveCustomer(Customer customer);
  
  public void saveAttachments(Attachment attachment);
}

This is DataDaoImpl.java file having the DAO logic to access the database information.


 

    
package com.cv.spring.poc.dao;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.cv.spring.mvc.RestController;
import com.cv.spring.poc.model.Attachment;
import com.cv.spring.poc.model.Customer;
/**
@author Chandra Vardhan
*/
public class DataDaoImpl implements DataDao {

  private final static Logger LOGGER = Logger.getLogger(DataDaoImpl.class);
  
  @Autowired
  SessionFactory sessionFactory;
  Session session = null;
  Transaction tx = null;

  // adds the user to db
  public void saveCustomer(Customer customer) {
    LOGGER.info("Entered into DataDaoImpl.saveCustomer(-)");
    LOGGER.info(customer);
    session = sessionFactory.openSession();
    if (customer.getFirstName() != null) {
      tx = session.beginTransaction();
      session.save(customer);
      tx.commit();
      session.close();

    else {
      LOGGER.info("email exists");
      error();
    }
    LOGGER.info("Exiting from DataDaoImpl.saveCustomer(-)");

  }

  private String error() {
    return "/error.jsp";

  }

  @Transactional
  public List<Customer> showCustomers() {
    LOGGER.info("Entered into DataDaoImpl.showCustomers(-)");
    session = sessionFactory.openSession();
    Query query = session.createQuery("from Customer");
    List<Customer> customers = query.list();
    // List<Customer> customers = new ArrayList<Customer>();
    LOGGER.info(customers);
    for (Customer customer : customers) {
      LOGGER.info(customer.getEmail());
      LOGGER.info(customer.getCustomerId());
    }
    LOGGER.info("ExitinG from DataDaoImpl.showCustomers(-)");
    return customers;

  }

  // load the user details from database
  public Customer findCustomer(int id) {
    session = sessionFactory.openSession();
    Customer customer = (Customersession.load(Customer.class, new Long(id));
    return customer;
  }

  public void saveAttachments(Attachment attachment) {
    LOGGER.info("Entered into DataDaoImpl.saveAttachments(-)");
    LOGGER.info(attachment);
    session = sessionFactory.openSession();
    if (attachment != null) {
      tx = session.beginTransaction();
      session.save(attachment);
      tx.commit();
      session.close();

    else {
      LOGGER.info("email exists");
      error();
    }
    LOGGER.info("Exiting from DataDaoImpl.saveAttachments(-)");
  }

  

}

This is Attachment.java file having the source code to execute business logic.


 

    
package com.cv.spring.poc.model;

import java.io.Serializable;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
/**
@author Chandra Vardhan
*/
@Entity
@Table(name = "ATTACHMENTS")
public class Attachment implements Serializable {

  private static final long serialVersionUID = 1L;

  @Id
  @GeneratedValue
  @Column(name = "id")
  private long id;

  @OneToOne(cascade = CascadeType.ALL)
  @JoinColumn(name = "CUSTOMER_ID")
  private Customer customer;

  @Column(name = "PATH")
  private String path;

  public long getId() {
    return id;
  }

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


  public Customer getCustomer() {
    return customer;
  }

  public void setCustomer(Customer customer) {
    this.customer = customer;
  }

  public String getPath() {
    return path;
  }

  public void setPath(String path) {
    this.path = path;
  }

}

This is Customer.java file having the source code to execute business logic.


 

    
package com.cv.spring.poc.model;

import java.util.Date;

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

import org.hibernate.annotations.Type;

/**
 @author Chandra Vardhan
 */
@Entity
@Table(name = "CUSTOMER")
public class Customer {
  @Id
  @GeneratedValue
  @Column(name = "CUSTOMER_ID")
  private long customerId;

  @Column(name = "FIRST_NAME")
  private String firstName;

  @Column(name = "LAST_NAME")
  private String lastName;

  @Column(name = "EMAIL", unique = true)
  private String email;

  @Column(name = "PHONE_NUMBER")
  private String phone;

  @Column(name = "CREATED_DATE")
  @Type(type = "date")
  private Date createdate;

  @Column(name = "DOB")
  @Type(type = "date")
  private Date dob;

  public long getCustomerId() {
    return customerId;
  }

  public void setCustomerId(long customerId) {
    this.customerId = customerId;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public String getEmail() {
    return email;
  }

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

  public String getPhone() {
    return phone;
  }

  public void setPhone(String phone) {
    this.phone = phone;
  }

  public Date getCreatedate() {
    return createdate;
  }

  public void setCreatedate(Date createdate) {
    this.createdate = createdate;
  }

  public Date getDob() {
    return dob;
  }

  public void setDob(Date dob) {
    this.dob = dob;
  }

}

This is CustomerPojo.java file having the source code to execute business logic.


 

    
package com.cv.spring.poc.model;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 @author Chandra Vardhan
 */
public class CustomerPojo {

  private long customerId;
  private String firstName;
  private String lastName;
  private String email;
  private String phone;
  private Date createdate;
  private String image;
  private String dobVal;
  private Date dob;

  public long getCustomerId() {
    return customerId;
  }

  public void setCustomerId(long customerId) {
    this.customerId = customerId;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public String getEmail() {
    return email;
  }

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

  public String getPhone() {
    return phone;
  }

  public void setPhone(String phone) {
    this.phone = phone;
  }

  public Date getCreatedate() {
    return createdate;
  }

  public void setCreatedate(Date createdate) {
    this.createdate = createdate;
  }

  public String getImage() {
    return image;
  }

  public void setImage(String image) {
    this.image = image;
  }

  public String getDobVal() {
    return dobVal;
  }

  public void setDobVal(String dobVal) {
    this.dobVal = dobVal;    
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");    
    if(dobVal != null) {
      String[] splits = dobVal.split("-");
      String startDate = splits[0];
      if(startDate != null) {
        startDate = startDate.trim();    
        try {
          setDob(sdf.parse(startDate));
        catch (ParseException e) {
          e.printStackTrace();
        }
      }
    }
    
    
  }

  public Date getDob() {
    return dob;
  }

  public void setDob(Date dob) {
    this.dob = dob;
  }

}

This is DataServices.java file having the service/business logic to call the DAO layer and get the information from database.


 

    
package com.cv.spring.poc.services;

import java.util.List;

import com.cv.spring.poc.model.Attachment;
import com.cv.spring.poc.model.Customer;
/**
@author Chandra Vardhan
*/
public interface DataServices {  
  
  public List<Customer> showCustomers();

  public Customer findCustomer(int id);

  public void saveCustomer(Customer customer);
  
  public void saveAttachments(Attachment attachment);
}

This is DataServicesImpl.java file having the service/business logic to call the DAO layer and get the information from database.


 

    
package com.cv.spring.poc.services;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.cv.spring.poc.dao.DataDao;
import com.cv.spring.poc.model.Attachment;
import com.cv.spring.poc.model.Customer;
/**
@author Chandra Vardhan
*/
public class DataServicesImpl implements DataServices {

  @Autowired
  DataDao dataDao;

  @Autowired
  SessionFactory sessionFactory;

  Session session = null;


  @Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.DEFAULT, timeout = 60)
  public List<Customer> showCustomers() {
    return dataDao.showCustomers();

  }
  public Customer findCustomer(int id) {
    return dataDao.findCustomer(id);
  }
  @Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.DEFAULT, readOnly = true, timeout = 60)
  public void saveCustomer(Customer customer) {
     dataDao.saveCustomer(customer);
     
  }
  @Override
  public void saveAttachments(Attachment attachment) {
    dataDao.saveAttachments(attachment);
  }
}



This is pom.xml file having the entries of dependency jars and information to build the application .


	
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cv.spring</groupId> <artifactId>Spring4MVCImageJqueryDateUpload</artifactId> <version>1.0</version> <packaging>war</packaging> <properties> <log4j-version>1.2.16</log4j-version> <java.version>1.8</java.version> <spring.version>4.2.0.RELEASE</spring.version> <hibernate.version>4.3.5.Final</hibernate.version> <log4j-version>1.2.17</log4j-version> </properties> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <warSourceDirectory>src/main/webapp</warSourceDirectory> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> provided </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20090211</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> </dependencies> </project>


This is spring-servlet.xml spring configuration file and these entries are used in the application.


 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<context:component-scan base-package="com.cv.spring.mvc"></context:component-scan>

<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>



<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/hibernate" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!-- This bean requires to handle the JSON serialization
and deserialization. Purposely marked as [Non-Singleton] -->

<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.cv.spring.poc.model.Customer</value>
<value>com.cv.spring.poc.model.Attachment</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>

<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="dataDao" class="com.cv.spring.poc.dao.DataDaoImpl"></bean>
<bean id="dataServices" class="com.cv.spring.poc.services.DataServicesImpl"></bean>
</beans>


This is web.xml deployment descriptor file and it describes how the web application should be deployed.


	
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>Spring3MVC</display-name>
<context-param>
<param-name>imageStoragePathInFileSystem</param-name>
<param-value>C:\temp\images\</param-value>
</context-param>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>


This is log4j.properties file having the entries for logging the information into the console/file.



#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, stdout

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n

# Redirect log messages to a log file
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\servlet-application.log
#log4j.appender.file.MaxFileSize=5MB
#log4j.appender.file.MaxBackupIndex=10
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

No comments:

Post a Comment