spring+mvc+hibernate+java+based
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>
<a href="delete?id=${user.id}">Delete</a>
</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
|
This is ApplicationContextConfig.java file having the source code to execute business logic.
package com.cv.spring.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.cv.spring.dao.UserDAO;
import com.cv.spring.dao.UserDAOImpl;
import com.cv.spring.model.User;
/**
* @author Chandra Vardhan
*/
@Configuration
@ComponentScan("com.cv.spring")
@EnableTransactionManagement
public class ApplicationContextConfig {
private static final Logger LOGGER = Logger.getLogger(ApplicationContextConfig.class);
@Bean(name = "viewResolver")
public InternalResourceViewResolver getViewResolver() {
LOGGER.info("Entered into ApplicationContextConfig.getViewResolver()");
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
LOGGER.info("Exiting from ApplicationContextConfig.getViewResolver()");
return viewResolver;
}
@Bean(name = "dataSource")
public DataSource getDataSource() {
LOGGER.info("Entered into ApplicationContextConfig.getDataSource()");
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/hibernate");
dataSource.setUsername("root");
dataSource.setPassword("root");
LOGGER.info("Exiting from ApplicationContextConfig.getDataSource()");
return dataSource;
}
private Properties getHibernateProperties() {
LOGGER.info("Entered into ApplicationContextConfig.getHibernateProperties()");
Properties properties = new Properties();
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.hbm2ddl.auto", "update");
LOGGER.info("Exiting from ApplicationContextConfig.getHibernateProperties()");
return properties;
}
@Autowired
@Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource dataSource) {
LOGGER.info("Entered into ApplicationContextConfig.getSessionFactory(-)");
LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
sessionBuilder.addProperties(getHibernateProperties());
sessionBuilder.addAnnotatedClasses(User.class);
LOGGER.info("Exiting from ApplicationContextConfig.getSessionFactory(-)");
return sessionBuilder.buildSessionFactory();
}
@Autowired
@Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(
SessionFactory sessionFactory) {
LOGGER.info("Entered into ApplicationContextConfig.getTransactionManager()");
HibernateTransactionManager transactionManager = new HibernateTransactionManager(
sessionFactory);
LOGGER.info("Exiting from ApplicationContextConfig.getTransactionManager(-)");
return transactionManager;
}
@Autowired
@Bean(name = "userDao")
public UserDAO getUserDao(SessionFactory sessionFactory) {
LOGGER.info("Entered into ApplicationContextConfig.getUserDao(-)");
return new UserDAOImpl(sessionFactory);
}
} |
This is SpringWebAppInitializer.java file having the source code to execute business logic.
package com.cv.spring.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.apache.log4j.Logger;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
/**
* @author Chandra Vardhan
*/
public class SpringWebAppInitializer implements WebApplicationInitializer {
private static final Logger LOGGER = Logger.getLogger(SpringWebAppInitializer.class);
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
LOGGER.info("Entered into SpringWebAppInitializer.onStartup()");
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(ApplicationContextConfig.class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
"SpringDispatcher", new DispatcherServlet(appContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
LOGGER.info("Exiting from SpringWebAppInitializer.onStartup(-)");
}
} |
This is HomeController.java file having the controller logic and it will have the services defined in it.
package com.cv.spring.controller;
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 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.apache.log4j.Logger;
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 User.java file having the source code to execute business logic.
package com.cv.spring.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author Chandra Vardhan
*/
@Entity
@Table(name = "USERS2")
public class User {
private int id;
private String username;
private String password;
private String email;
@Id
@GeneratedValue
@Column(name = "USER_ID")
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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cv.spring</groupId>
<artifactId>SpringMvcHibernateJavaBased</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<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>
<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>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</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>
</project> |
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