Spring+Secure+View+Fragments+Using+Security+Taglib+Project

spring+secure+view+fragments+using+security+taglib+project

Click here to download eclipse supported ZIP file



This is accessDenied.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"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>AccessDenied page</title>
</head>
<body>
Dear <strong>${user}</strong>, You are not authorized to access this page
<a href="<c:url value="/logout" />">Logout</a>
</body>
</html>


This is login.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"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login page</title>
<link href="<c:url value='/static/css/bootstrap.css' />"  rel="stylesheet"></link>
<link href="<c:url value='/static/css/app.css' />" rel="stylesheet"></link>
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.css" />
</head>
<body>
<p align="center"><font color="white">Please enter username as dba and password as root123!!! This is for success scenario, perform all operations</font></p>
<p align="center"><font color="white">Please enter username as admin and password as root123!!! This is for success scenario</font></p>
<p align="center"><font color="white">Please enter username as bill and password as  abc123!!! This is for success scenario</font></p>

<div id="mainWrapper">
<div class="login-container">
<div class="login-card">
<div class="login-form">
<c:url var="loginUrl" value="/login" />
<form action="${loginUrl}" method="post" class="form-horizontal">
<c:if test="${param.error != null}">
<div class="alert alert-danger">
<p>Invalid username and password.</p>
</div>
</c:if>
<c:if test="${param.logout != null}">
<div class="alert alert-success">
<p>You have been logged out successfully.</p>
</div>
</c:if>
<div class="input-group input-sm">
<label class="input-group-addon" for="username"><i class="fa fa-user"></i></label>
<input type="text" class="form-control" id="username" name="ssoId" placeholder="Enter Username" required>
</div>
<div class="input-group input-sm">
<label class="input-group-addon" for="password"><i class="fa fa-lock"></i></label> 
<input type="password" class="form-control" id="password" name="password" placeholder="Enter Password" required>
</div>
<input type="hidden" name="${_csrf.parameterName}"  value="${_csrf.token}" />

<div class="form-actions">
<input type="submit"
class="btn btn-block btn-primary btn-default" value="Log in">
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>


This is welcome.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"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome page</title>
</head>
<body>
Dear <strong>${user}</strong>, Welcome to Home Page.
<a href="<c:url value="/logout" />">Logout</a>
<br/>
<br/>
<div>
<label>View all information| This part is visible to Everyone</label>
</div>
<br/>
<div>
<sec:authorize access="hasRole('ADMIN')">
<label><a href="#">Edit this page</a> | This part is visible only to ADMIN</label>
</sec:authorize>
</div>
<br/>
<div>
<sec:authorize access="hasRole('ADMIN') and hasRole('DBA')">
<label><a href="#">Start backup</a> | This part is visible only to one who is both ADMIN & DBA</label>
</sec:authorize>
</div>
</html>



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


 

    
package com.cv.springsecurity.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
/**
 @author Chandra Vardhan
 */
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.cv.springsecurity")
public class HelloWorldConfiguration extends WebMvcConfigurerAdapter {
  
  @Bean(name="HelloWorld")
  public ViewResolver viewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/views/");
    viewResolver.setSuffix(".jsp");

    return viewResolver;
  }

  /*
     * Configure ResourceHandlers to serve static resources like CSS/ Javascript etc...
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("/static/");
    }
}


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


 

    
package com.cv.springsecurity.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
 @author Chandra Vardhan
 */
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

  
  @Autowired
  public void configureGlobalSecurity(AuthenticationManagerBuilder auththrows Exception {
    auth.inMemoryAuthentication().withUser("bill").password("abc123").roles("USER");
    auth.inMemoryAuthentication().withUser("admin").password("root123").roles("ADMIN");
    auth.inMemoryAuthentication().withUser("dba").password("root123").roles("ADMIN","DBA");
  }
  
  @Override
  protected void configure(HttpSecurity httpthrows Exception {
    
    http.authorizeRequests()
      .antMatchers("/""/home").access("hasRole('USER') or hasRole('ADMIN') or hasRole('DBA')")
      .and().formLogin().loginPage("/login")
      .usernameParameter("ssoId").passwordParameter("password")
      .and().exceptionHandling().accessDeniedPage("/Access_Denied");
  }
}


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


 

    
package com.cv.springsecurity.configuration;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
/**
 @author Chandra Vardhan
 */
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {

}


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


 

    
package com.cv.springsecurity.configuration;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/**
 @author Chandra Vardhan
 */
public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

  @Override
  protected Class<?>[] getRootConfigClasses() {
    return new Class[] { HelloWorldConfiguration.class };
  }
 
  @Override
  protected Class<?>[] getServletConfigClasses() {
    return null;
  }
 
  @Override
  protected String[] getServletMappings() {
    return new String[] { "/" };
  }

}


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


 

    
package com.cv.springsecurity.controller;

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

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
 @author Chandra Vardhan
 */
@Controller
public class HelloWorldController {

  
  @RequestMapping(value = "/""/home" }, method = RequestMethod.GET)
  public String homePage(ModelMap model) {
    model.addAttribute("user", getPrincipal());
    return "welcome";
  }

  @RequestMapping(value = "/Access_Denied", method = RequestMethod.GET)
  public String accessDeniedPage(ModelMap model) {
    model.addAttribute("user", getPrincipal());
    return "accessDenied";
  }

  @RequestMapping(value = "/login", method = RequestMethod.GET)
  public String loginPage() {
    return "login";
  }

  @RequestMapping(value="/logout", method = RequestMethod.GET)
  public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null){    
      new SecurityContextLogoutHandler().logout(request, response, auth);
    }
    return "redirect:/login?logout";
  }

  private String getPrincipal(){
    String userName = null;
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    if (principal instanceof UserDetails) {
      userName = ((UserDetails)principal).getUsername();
    else {
      userName = principal.toString();
    }
    return userName;
  }

}




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.springsecurity</groupId> <artifactId>SpringSecureViewFragmentsUsingSecurityTaglib</artifactId> <version>1.0</version> <packaging>war</packaging> <name>SpringSecureViewFragmentsUsingSecurityTaglib</name> <properties> <springframework.version>4.1.6.RELEASE</springframework.version> <springsecurity.version>4.0.1.RELEASE</springsecurity.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>${springsecurity.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${springsecurity.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-taglibs</artifactId> <version>${springsecurity.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.3.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-c3p0</artifactId> <version>4.3.5.Final</version> </dependency> <dependency> <artifactId>hibernate-core</artifactId> <groupId>org.hibernate</groupId> <version>4.3.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.2.0.Final</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <warSourceDirectory>src/main/webapp</warSourceDirectory> <warName>SpringSecureViewFragmentsUsingSecurityTaglib</warName> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </pluginManagement> <finalName>SpringSecureViewFragmentsUsingSecurityTaglib</finalName> </build> </project>


This is employee.hbm.xml file having the spring configuration properties.


 
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.cv.spring.mvc.hibernate.model.Employee" table="Employee_new22">
<id name="empId" column="empId" type="java.lang.Long">
<generator class="identity" />
</id>
<property name="empName" column="empName" type="java.lang.String" />
<property name="empAddress" column="empAddress" type="java.lang.String" />
<property name="salary" column="salary" type="java.lang.Long" />
<property name="empAge" column="empAge" type="java.lang.Long" />
</class>
</hibernate-mapping>



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


Spring MVC Hibernate XML

spring+mvc+hibernate+xml

Click here to download eclipse supported ZIP file



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



<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>New or Edit User</title>
</head>
<body>
<div align="center">
<h1>New/Edit User</h1>
<table>
<form:form action="save" method="post" modelAttribute="user">
<form:hidden path="id"/>
<tr>
<td>Username:</td>
<td><form:input path="username"/></td>
</tr>
<tr>
<td>Email:</td>
<td><form:input path="email"/></td>
</tr>
<tr>
<td>Password:</td>
<td><form:password path="password"/></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Save">
</td>
</tr>
</form:form>
</table>
</div>
</body>
</html>

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



<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Home</title>
    </head>
    <body>
        <div align="center">
        <h1>Users List</h1>
        <h2><a href="new">New User</a></h2>
        
         <table border="1">
         <th>No</th>
         <th>Username</th>
         <th>Email</th>
         <th>Actions</th>
        
<c:forEach var="user" items="${result}" varStatus="status">
         <tr>
         <td>${status.index + 1}</td>
<td>${user.username}</td>
<td>${user.email}</td>
<td>
<a href="edit?id=${user.id}">Edit</a>
&nbsp;&nbsp;&nbsp;&nbsp;
<a href="delete?id=${user.id}">Delete</a>
</td>
         </tr>
</c:forEach>         
         </table>
        </div>
    </body>
</html>


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


 

    
package com.cv.spring.dao;

import java.util.List;

import com.cv.spring.model.User;
/**
@author Chandra Vardhan
*/
public interface UserDAO {
  public List<User> list();
  
  public User get(int id);
  
  public void saveOrUpdate(User user);
  
  public void delete(int id);
}

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


 

    
package com.cv.spring.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.cv.spring.model.User;
/**
@author Chandra Vardhan
*/
@Repository
public class UserDAOImpl implements UserDAO {
  
  
  @Autowired
  private SessionFactory sessionFactory;

  public UserDAOImpl() {
    
  }
  
  public UserDAOImpl(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
  }

  @Override
  @Transactional
  public List<User> list() {
    @SuppressWarnings("unchecked")
    List<User> listUser = (List<User>sessionFactory.getCurrentSession()
        .createCriteria(User.class)
        .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();

    return listUser;
  }

  @Override
  @Transactional
  public void saveOrUpdate(User user) {
    sessionFactory.getCurrentSession().saveOrUpdate(user);
  }

  @Override
  @Transactional
  public void delete(int id) {
    User userToDelete = new User();
    userToDelete.setId(id);
    sessionFactory.getCurrentSession().delete(userToDelete);
  }

  @Override
  @Transactional
  public User get(int id) {
    String hql = "from User where id=" + id;
    Query query = sessionFactory.getCurrentSession().createQuery(hql);
    
    @SuppressWarnings("unchecked")
    List<User> listUser = (List<User>query.list();
    
    if (listUser != null && !listUser.isEmpty()) {
      return listUser.get(0);
    }
    
    return null;
  }
}

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


 

    
package com.cv.spring;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
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.servlet.ModelAndView;


import com.cv.spring.dao.UserDAO;
import com.cv.spring.model.User;

/**
 * Handles requests for the application home page.
 */

/**
@author Chandra Vardhan
*/


@Controller
public class HomeController {

private static final Logger LOGGER = Logger.getLogger(HomeController.class);
  
  @Autowired
  private UserDAO userDao;

  @RequestMapping("/")
  public ModelAndView handleRequest() throws Exception {
    LOGGER.info("Entered into HomeController.handleRequest()");
    List<User> listUsers = userDao.list();
    ModelAndView model = new ModelAndView("result");
    model.addObject("result", listUsers);
    LOGGER.info("Exiting from HomeController.handleRequest()");  
    return model;
  }
  
  @RequestMapping(value = "/new", method = RequestMethod.GET)
  public ModelAndView newUser() {
    LOGGER.info("Entered into HomeController.newUser()");
    ModelAndView model = new ModelAndView("form","user"new User());
    LOGGER.info("Exiting from HomeController.newUser()");  
    return model;    
  }
  
  @RequestMapping(value = "/edit", method = RequestMethod.GET)
  public ModelAndView editUser(HttpServletRequest request) {
    LOGGER.info("Entered into HomeController.editUser()");
    int userId = Integer.parseInt(request.getParameter("id"));
    User user = userDao.get(userId);
    ModelAndView model = new ModelAndView("form");
    model.addObject("user", user);
    LOGGER.info("Exiting from HomeController.editUser()");  
    return model;    
  }
  
  @RequestMapping(value = "/delete", method = RequestMethod.GET)
  public ModelAndView deleteUser(HttpServletRequest request) {
    LOGGER.info("Entered into HomeController.deleteUser()");
    int userId = Integer.parseInt(request.getParameter("id"));
    userDao.delete(userId);
    LOGGER.info("Exiting from HomeController.deleteUser()");  
    return new ModelAndView("redirect:/");    
  }
  
  @RequestMapping(value = "/save", method = RequestMethod.POST)
  public ModelAndView saveUser(@ModelAttribute User user) {
    LOGGER.info("Entered into HomeController.saveUser()");
    userDao.saveOrUpdate(user);
    LOGGER.info("Exiting from HomeController.saveUser()");  
    return new ModelAndView("redirect:/");
  }
  
}

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


 

    
package com.cv.spring.model;

public class User {
  private int id;
  private String username;
  private String password;
  private String email;

  public int getId() {
    return id;
  }

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

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public String getEmail() {
    return email;
  }

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

}



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">.0" encoding="UTF-8"?> <modelVersion>4.0.0</modelVersion> <groupId>com.cv</groupId> <artifactId>SpringMvcHibernateXML</artifactId> <name>SpringMvcHibernateXML</name> <packaging>war</packaging> <version>1.0</version> <properties> <log4j-version>1.2.16</log4j-version> <java.version>1.8</java.version> <org.springframework-version>4.2.0.RELEASE</org.springframework-version> <hibernate.version>4.3.5.Final</hibernate.version> <log4j-version>1.2.17</log4j-version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${org.springframework-version}</version> jar compile </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.5.Final</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> provided </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> provided </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.30</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> </dependencies> <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> </project>


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


 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

<!-- Enables the Spring MVC @Controller programming model -->
<mvc:annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>

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

<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<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>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>

<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="userDao" class="com.cv.spring.dao.UserDAOImpl">
<constructor-arg>
<ref bean="sessionFactory" />
</constructor-arg>
</bean>
</beans>

This is root-context.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:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- Root Context: defines shared resources visible to all other web components -->

</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="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>

<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</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

download ZIP : spring+mvc+hibernate+xml