Hi Friends,
Today I am here with most important and valuable topic in Java, its SPRING MVC
Here I am going to explain example with JDBC Template with Maven
Project Structure-1.
2.pom.xml
<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.neesri</groupId>
<artifactId>neeraj</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>nee</name>
<properties>
<java.version>1.7</java.version>
<spring.version>4.0.3.RELEASE</spring.version>
<cglib.version>2.2.2</cglib.version>
</properties>
<dependencies>
<!-- Spring core & mvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- CGLib for @Configuration -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>${cglib.version}</version>
<scope>runtime</scope>
</dependency>
<!-- Servlet Spec -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
</dependencies>
</project>
3. Contacts
package com.neesri.bean;
public class Contacts {
private int id;
private String name;
private String email;
private String mobile;
public Contacts() {
}
public Contacts(int id, String name, String email, String mobile) {
super();
this.setId(id);
this.setName(name);
this.setEmail(email);
this.setMobile(mobile);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
}
public class Contacts {
private int id;
private String name;
private String email;
private String mobile;
public Contacts() {
}
public Contacts(int id, String name, String email, String mobile) {
super();
this.setId(id);
this.setName(name);
this.setEmail(email);
this.setMobile(mobile);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
}
4. ContactDAO
package com.neesri.bean;
import java.util.List;
public interface ContactDAO {
public void saveOrUpdate(Contacts contact);
public void delete(int contactId);
public Contacts get(int contactId);
public List<Contacts> list();
}
import java.util.List;
public interface ContactDAO {
public void saveOrUpdate(Contacts contact);
public void delete(int contactId);
public Contacts get(int contactId);
public List<Contacts> list();
}
5. ContactsDaoImplment
package com.neesri.bean;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
public class ContactsDaoImplment implements ContactDAO{
private JdbcTemplate jdbctemp;
public ContactsDaoImplment(DataSource datasource) {
jdbctemp = new JdbcTemplate(datasource);
}
public void saveOrUpdate(Contacts contact) {
if (contact.getId() > 0) {
// update
String sql = "UPDATE contacts SET name=?, email=?, "
+ "mobile=? WHERE id=?";
jdbctemp.update(sql, contact.getName(), contact.getEmail(),
contact.getMobile(), contact.getId());
} else {
// insert
String sql = "INSERT INTO contacts (name, email, mobile)"
+ " VALUES (?, ?, ?)";
jdbctemp.update(sql, contact.getName(), contact.getEmail(),
contact.getMobile());
}
}
public void delete(int contactId) {
String sql = "DELETE FROM contacts WHERE id=?";
jdbctemp.update(sql, contactId);
}
public List<Contacts> list() {
final String sql = "SELECT * FROM contacts";
List<Contacts> listContact = jdbctemp.query(sql,
new RowMapper<Contacts>() {
public Contacts mapRow(ResultSet rs, int rowNum)
throws SQLException {
Contacts aContact = new Contacts();
aContact.setId(rs.getInt("id"));
aContact.setName(rs.getString("name"));
aContact.setEmail(rs.getString("email"));
aContact.setMobile(rs.getString("mobile"));
return aContact;
}
});
return listContact;
}
public Contacts get(final int contactId) {
final String sql = "SELECT * FROM contacts WHERE id="
+ contactId;
return jdbctemp.query(sql, new ResultSetExtractor<Contacts>() {
public Contacts extractData(ResultSet rs) throws SQLException,
DataAccessException {
if (rs.next()) {
Contacts contact = new Contacts();
contact.setId(rs.getInt("id"));
contact.setName(rs.getString("name"));
contact.setEmail(rs.getString("email"));
contact.setMobile(rs.getString("mobile"));
return contact;
}
return null;
}
});
}
}
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
public class ContactsDaoImplment implements ContactDAO{
private JdbcTemplate jdbctemp;
public ContactsDaoImplment(DataSource datasource) {
jdbctemp = new JdbcTemplate(datasource);
}
public void saveOrUpdate(Contacts contact) {
if (contact.getId() > 0) {
// update
String sql = "UPDATE contacts SET name=?, email=?, "
+ "mobile=? WHERE id=?";
jdbctemp.update(sql, contact.getName(), contact.getEmail(),
contact.getMobile(), contact.getId());
} else {
// insert
String sql = "INSERT INTO contacts (name, email, mobile)"
+ " VALUES (?, ?, ?)";
jdbctemp.update(sql, contact.getName(), contact.getEmail(),
contact.getMobile());
}
}
public void delete(int contactId) {
String sql = "DELETE FROM contacts WHERE id=?";
jdbctemp.update(sql, contactId);
}
public List<Contacts> list() {
final String sql = "SELECT * FROM contacts";
List<Contacts> listContact = jdbctemp.query(sql,
new RowMapper<Contacts>() {
public Contacts mapRow(ResultSet rs, int rowNum)
throws SQLException {
Contacts aContact = new Contacts();
aContact.setId(rs.getInt("id"));
aContact.setName(rs.getString("name"));
aContact.setEmail(rs.getString("email"));
aContact.setMobile(rs.getString("mobile"));
return aContact;
}
});
return listContact;
}
public Contacts get(final int contactId) {
final String sql = "SELECT * FROM contacts WHERE id="
+ contactId;
return jdbctemp.query(sql, new ResultSetExtractor<Contacts>() {
public Contacts extractData(ResultSet rs) throws SQLException,
DataAccessException {
if (rs.next()) {
Contacts contact = new Contacts();
contact.setId(rs.getInt("id"));
contact.setName(rs.getString("name"));
contact.setEmail(rs.getString("email"));
contact.setMobile(rs.getString("mobile"));
return contact;
}
return null;
}
});
}
}
6. MvcConfiguration - i have used this class instead of spring.xml, dont be confuse
package com.neesri.config;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
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 com.neesri.bean.ContactDAO;
import com.neesri.bean.ContactsDaoImplment;
@Configuration
@ComponentScan(basePackages="com.neesri")
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter {
@Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver=new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
return resolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
//super.addResourceHandlers(registry);
}
@Bean
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/contact_spring");
dataSource.setUsername("neeraj");
dataSource.setPassword("neeraj");
return dataSource;
}
@Bean
public ContactDAO getcoContactDAO(){
return new ContactsDaoImplment(getDataSource());
}
}
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
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 com.neesri.bean.ContactDAO;
import com.neesri.bean.ContactsDaoImplment;
@Configuration
@ComponentScan(basePackages="com.neesri")
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter {
@Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver=new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
return resolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
//super.addResourceHandlers(registry);
}
@Bean
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/contact_spring");
dataSource.setUsername("neeraj");
dataSource.setPassword("neeraj");
return dataSource;
}
@Bean
public ContactDAO getcoContactDAO(){
return new ContactsDaoImplment(getDataSource());
}
}
7. HomeController -this is controller class
package com.neesri.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
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.neesri.bean.ContactDAO;
import com.neesri.bean.Contacts;
@Controller
public class HomeController {
@Autowired
private ContactDAO contactDAO;
@RequestMapping(value="/")
public ModelAndView listcontacts(ModelAndView model) throws IOException{
List<Contacts>listContacts=contactDAO.list();
model.addObject("listContact", listContacts);
model.setViewName("home");
return model;
}
@RequestMapping(value="/saveContact", method = RequestMethod.POST)
public ModelAndView savecontact(@ModelAttribute Contacts contacts){
contactDAO.saveOrUpdate(contacts);
return new ModelAndView("redirect:/");
}
@RequestMapping(value = "/editContact", method = RequestMethod.GET)
public ModelAndView editContact(HttpServletRequest request) {
int contactId = Integer.parseInt(request.getParameter("id"));
Contacts contact = contactDAO.get(contactId);
ModelAndView model = new ModelAndView("ContactForm");
model.addObject("contact", contact);
return model;
}
@RequestMapping(value = "/deleteContact", method = RequestMethod.GET)
public ModelAndView deleteContact(HttpServletRequest request) {
int contactId = Integer.parseInt(request.getParameter("id"));
contactDAO.delete(contactId);
return new ModelAndView("redirect:/");
}
@RequestMapping(value = "/newContact", method = RequestMethod.GET)
public ModelAndView newContact(ModelAndView model) {
Contacts newContact = new Contacts();
model.addObject("contact", newContact);
model.setViewName("ContactForm");
return model;
}
}
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
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.neesri.bean.ContactDAO;
import com.neesri.bean.Contacts;
@Controller
public class HomeController {
@Autowired
private ContactDAO contactDAO;
@RequestMapping(value="/")
public ModelAndView listcontacts(ModelAndView model) throws IOException{
List<Contacts>listContacts=contactDAO.list();
model.addObject("listContact", listContacts);
model.setViewName("home");
return model;
}
@RequestMapping(value="/saveContact", method = RequestMethod.POST)
public ModelAndView savecontact(@ModelAttribute Contacts contacts){
contactDAO.saveOrUpdate(contacts);
return new ModelAndView("redirect:/");
}
@RequestMapping(value = "/editContact", method = RequestMethod.GET)
public ModelAndView editContact(HttpServletRequest request) {
int contactId = Integer.parseInt(request.getParameter("id"));
Contacts contact = contactDAO.get(contactId);
ModelAndView model = new ModelAndView("ContactForm");
model.addObject("contact", contact);
return model;
}
@RequestMapping(value = "/deleteContact", method = RequestMethod.GET)
public ModelAndView deleteContact(HttpServletRequest request) {
int contactId = Integer.parseInt(request.getParameter("id"));
contactDAO.delete(contactId);
return new ModelAndView("redirect:/");
}
@RequestMapping(value = "/newContact", method = RequestMethod.GET)
public ModelAndView newContact(ModelAndView model) {
Contacts newContact = new Contacts();
model.addObject("contact", newContact);
model.setViewName("ContactForm");
return model;
}
}
8. ContactForm.jsp- this must be in WEB-INF/view folder
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!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>
<div align="center">
<h1>New/Edit Contact</h1>
<form:form action="saveContact" method="post" modelAttribute="contact">
<table>
<form:hidden path="id"/>
<tr>
<td>Name:</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Email:</td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td>Telephone:</td>
<td><form:input path="mobile" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Save"></td>
</tr>
</table>
</form:form>
</div>
</body>
</html>
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!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>
<div align="center">
<h1>New/Edit Contact</h1>
<form:form action="saveContact" method="post" modelAttribute="contact">
<table>
<form:hidden path="id"/>
<tr>
<td>Name:</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Email:</td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td>Telephone:</td>
<td><form:input path="mobile" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Save"></td>
</tr>
</table>
</form:form>
</div>
</body>
</html>
9. home.jsp- this must be in WEB-INF/view folder
<%@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>Contact Manager Home</title>
</head>
<body>
<div align="center">
<h1>Contact List</h1>
<c:set var="root" value="${pageContext.request.contextPath}"/>
<h3><a href="${root}/newContact">New Contact</a></h3>
<table border="1">
<th>No</th>
<th>Name</th>
<th>Email</th>
<th>Mobile</th>
<th>Action</th>
<c:forEach var="contact" items="${listContact}" varStatus="status">
<tr>
<td>${status.index + 1}</td>
<td>${contact.name}</td>
<td>${contact.email}</td>
<td>${contact.mobile}</td>
<td>
<a href="${root}/editContact?id=${contact.id}">Edit</a>
<a href="${root}/deleteContact?id=${contact.id}">Delete</a>
</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
<!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>Contact Manager Home</title>
</head>
<body>
<div align="center">
<h1>Contact List</h1>
<c:set var="root" value="${pageContext.request.contextPath}"/>
<h3><a href="${root}/newContact">New Contact</a></h3>
<table border="1">
<th>No</th>
<th>Name</th>
<th>Email</th>
<th>Mobile</th>
<th>Action</th>
<c:forEach var="contact" items="${listContact}" varStatus="status">
<tr>
<td>${status.index + 1}</td>
<td>${contact.name}</td>
<td>${contact.email}</td>
<td>${contact.mobile}</td>
<td>
<a href="${root}/editContact?id=${contact.id}">Edit</a>
<a href="${root}/deleteContact?id=${contact.id}">Delete</a>
</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
10 web.xml -the most important xml file , where we write about dispatherservlet
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>neeraj</display-name>
<!--
- Location of the XML file that defines the root application context.
- Applied by ContextLoaderListener.
-->
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>SpringDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.neesri.config</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringDispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
.
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>neeraj</display-name>
<!--
- Location of the XML file that defines the root application context.
- Applied by ContextLoaderListener.
-->
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>SpringDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.neesri.config</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringDispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
Result is:
If any query then make a comment
Thanks
Neeraj Srivastava
Java Developer
Happy Learning :) :)
Keep Smiling :) :) :)
No comments:
Post a Comment