Contents
WEB DEVELOPMENT PROJECT BY USING SPRING FRAMEWORK
This is the project to insert, list, delete, edit the data in the database by using spring framework. This is also called as CRUD (create, retrieve, update, delete) operation. Let us see about the architecture of spring. There are 5 components we have such as front controller, controller, handler mapping, view resolver and view. Let us see the flow of spring framework.
- Front controller is used control the entire flow of the architecture.
- Handler mapping is the part that helps us to identify the controller to front controller,
- After the Mapping Process the front controller search the view page with the help of view resolver class.
SPRING FRAMEWORK ARCHITECTURE:
FRONT CONTROLLER:
This is the controller of entire program and it is also called as dispatcher servlet.
Here we are going to create .xml file as front controller(for ex: frontcontrollername.xml).
In the front controller we have 5 sections those are view resolver, data source, Session Factory, hibernate properties. We already known view resolver is used to find out the view page (JSP page).The data source contain user name, password of the database which is also configured with resource file (database properties). For example:
RESOURCE FILE:
database.driver=oracle.jdbc.driver.OracleDriver database.url=jdbc:oracle:thin:@localhost:1521:xe database.user=system database.password=root hibernate.dialect=org.hibernate.dialect.OracleDialect hibernate.show_sql=true hibernate.hbm2ddl.auto=update |
Session Factory is the class which is used to create connection with hibernate. The front controller also have hibernate transaction manager which is used to maintain the connection with resource. First the jvm check the hibernate transaction manager by this order execute the page, every block is connected another block by using “ref”. Inside the session factory we need to give entire package and file name of model (pojo)class.
WEB.xml:
This is the xml file which is used to find out the location of front controller.the web.xml file is create by default at the tme of project creation. Here the following Servlet code “spring” is the front controller name.
SOURCE CODE OF WEB.XML:
<?xml version=”1.0″ encoding=”UTF-8″?> <web-app xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns=”http://java.sun.com/xml/ns/javaee” 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>Saturday</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list>
<servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
<servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
</web-app> |
SOURCE CODE OF FRONTROLLER:
<?xml version=”1.0″ encoding=”UTF-8″?> <beans xmlns=”http://www.springframework.org/schema/beans” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:context=”http://www.springframework.org/schema/context” xmlns:tx=”http://www.springframework.org/schema/tx” xsi:schemaLocation=” http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd”> <context:property-placeholder location=”classpath:resources/database.properties” /> <context:component-scan base-package=”com.saturday” /> <tx:annotation-driven transaction-manager=”hibernateTransactionManager”/> <bean id=”jspViewResolver” class=”org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name=”viewClass” value=”org.springframework.web.servlet.view.JstlView” /> <property name=”prefix” value=”/WEB-INF/view/” /> <property name=”suffix” value=”.jsp” /> </bean> <bean id=”dataSource” class=”org.springframework.jdbc.datasource.DriverManagerDataSource”> <property name=”driverClassName” value=”${database.driver}” /> <property name=”url” value=”${database.url}” /> <property name=”username” value=”${database.user}” /> <property name=”password” value=”${database.password}” /> </bean> <bean id=”sessionFactory” class=”org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean”> <property name=”dataSource” ref=”dataSource” /> <property name=”annotatedClasses”> <list> <value>com.saturday.model.SaturdayModel</value> </list> </property> <property name=”hibernateProperties”> <props> <prop key=”hibernate.dialect”>${hibernate.dialect}</prop> <prop key=”hibernate.show_sql”>${hibernate.show_sql}</prop> <prop key=”hibernate.hbm2ddl.auto”>${hibernate.hbm2ddl.auto}</prop> </props> </property> </bean> <bean id=”hibernateTransactionManager” class=”org.springframework.orm.hibernate3.HibernateTransactionManager”> <property name=”sessionFactory” ref=”sessionFactory” /> </bean> </beans> |
GENERAL FLOW OF PROGRAM:
First user enter the request through URL, the URL comes to the dispatcher servlet first then based on this URL dispatcher servlet search the pattern in the controller class. The request mapping map the request with the URL after get the corresponding URL the corresponding process is performed and finally the corresponding jsp page is return.
CONTROLLER:
Controller is the class which is used to control the layer of spring frame work. There are 4 layers in spring framework.
- Controller class
- Service layer
- Dao layer
- Pojo class
CONTROLLER CLASS:
In controller class we have request mapping which is used to map the pattern with the user request. Request method is based on URL. The default request method is GET method. Model attribute annotation is used to pass the set of values, here we are using model attribute instead of request param, why because we can’t pass group of values in request param.Bindrequest is the method which is used to bind the result with reference variable.her we are using autowiring technology this is the advantage of spring framework which is used to inject the bean automatically.it’s act as a bridge between 4 layers. Here we need to auto wire the service layer interface.
The every request mapping block should be mapped with jsp page.Here in this program “file” is the jsp name.
SOURCE CODE OF CONTROLLER:
package com.saturday.controller; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; 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.servlet.ModelAndView; import com.saturday.model.SaturdayModel; import com.saturday.service.SaturdayServiceInter; @Controller public class SaturdayController { @Autowired public SaturdayServiceInter saturdayServiceInter; @RequestMapping(value = “/insert”, method = RequestMethod.GET) public ModelAndView enter( @ModelAttribute(“command”) Saturday Model saturdayModel, BindingResult result) { Map<String, Object> map = new HashMap<String, Object>(); map.put(“call”, saturdayServiceInter.listval()); return new ModelAndView(“file”, map); } @RequestMapping(value = “/add”, method = RequestMethod.POST) public ModelAndView enter1( @ModelAttribute(“command”) Saturday Model saturdayModel) { saturdayServiceInter.insertVal(saturdayModel); return new ModelAndView(“redirect:/insert.html”); } @RequestMapping(value = “/index”, method = RequestMethod.GET) public ModelAndView welcome() { return new ModelAndView(“index”); } @RequestMapping(value = “/delete”, method = RequestMethod.GET) public ModelAndView dele( @ModelAttribute(“command”) Saturday Model saturdayModel, BindingResult result) { saturdayServiceInter.deleteval(saturdayModel); Map<String, Object> map = new HashMap<String, Object>(); map.put(“call”, saturdayServiceInter.listval()); return new ModelAndView(“file”, map); } @RequestMapping(value = “/edit”, method = RequestMethod.GET) public ModelAndView update( @ModelAttribute(“command”) Saturday Model saturdayModel, BindingResult result) { Map<String, Object> map = new HashMap<String, Object>(); map.put(“saturdayModel”, saturdayServiceInter.editval(saturdayModel.getPepId())); map.put(“call”, saturdayServiceInter.listval()); return new ModelAndView(“file”, map); } @RequestMapping(value = “/login”, method = RequestMethod.GET)
public ModelAndView check( @ModelAttribute(“command”) Saturday Model saturdayModel, BindingResult result) { return new ModelAndView(“Login”); } @RequestMapping(value = “/logincheck”, method = RequestMethod.POST) public ModelAndView checklog( @ModelAttribute(“command”) Saturday Model saturdayModel, BindingResult result) { String loginchec = saturdayServiceInter.loginCheck(saturdayModel); if (loginchec.equals(“success”)) {
return new ModelAndView(“file”); } else { return new ModelAndView(“Login”); } } } |
SERVICE LAYER:
In service layer we have one interface and one class which is implementing from this interface. In service layer we need to autowire the dao interface.
SERVICE INTERFACE:
We already known when we need only requirement specification we need to go Interface concept.
SOURCE CODE:
package com.saturday.service; import java.util.List; import com.saturday.model.SaturdayModel; public interface SaturdayServiceInter { public void insertVal(SaturdayModel saturdayModel); public List<SaturdayModel> listval();
public void deleteval(SaturdayModel saturdayModel);
public SaturdayModel editval(String pepId);
public String loginCheck(SaturdayModel saturdayModel); } |
SERVICE CLASS:
package com.saturday.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.saturday.dao.SaturdayDaoInter; import com.saturday.model.SaturdayModel; @Service(“saturdayServiceInter”) @Transactional(propagation=Propagation.SUPPORTS, readOnly = true) public class SaturdayServiceImple implements SaturdayServiceInter {
@Autowired public SaturdayDaoInter saturdayDaoInter;
@Transactional(propagation=Propagation.REQUIRED, readOnly = false) public void insertVal(SaturdayModel saturdayModel) { saturdayDaoInter.insertVal(saturdayModel); } public List<SaturdayModel> listval() { return saturdayDaoInter.listval(); } public void deleteval(SaturdayModel saturdayModel) { saturdayDaoInter.deleteval(saturdayModel); }
public SaturdayModel editval(String pepId) { return saturdayDaoInter.editval(pepId); }
public String loginCheck(SaturdayModel saturdayModel) { return saturdayDaoInter.loginCheck(saturdayModel); } } |
DAO LAYER:
In dao also we have one interface and one implement class. In dao layer we need need to auto wire the session factory because of creating hibernate connection.
DAO INTERFACE:
package com.saturday.dao; import java.util.List; import com.saturday.model.SaturdayModel; public interface SaturdayDaoInter { public void insertVal(SaturdayModel saturdayModel); public List<SaturdayModel> listval(); public void deleteval(SaturdayModel saturdayModel);
public SaturdayModel editval(String pepId);
public String loginCheck(SaturdayModel saturdayModel); } |
DAO CLASS:
package com.saturday.dao; import java.util.List; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.hibernate.classic.Session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.saturday.model.SaturdayModel; @Repository(“saturdayDaoInter”) public class SaturdayDaoImple implements SaturdayDaoInter { @Autowired public SessionFactory sessionFactory; public void insertVal(SaturdayModel saturdayModel) { sessionFactory.getCurrentSession().save(saturdayModel); } @SuppressWarnings(“unchecked”) public List<SaturdayModel> listval() { return (List<SaturdayModel>) sessionFactory.getCurrentSession() .createCriteria(SaturdayModel.class).list(); }
public void deleteval(SaturdayModel saturdayModel) { sessionFactory.getCurrentSession().createQuery(“DELETE FROM SaturdayModel WHERE pepId =”+saturdayModel.getPepId()).executeUpdate(); } public SaturdayModel editval(String pepId) { return (SaturdayModel) sessionFactory.getCurrentSession().get( SaturdayModel.class, pepId); } public String loginCheck(SaturdayModel saturdayModel) { String flag = null; Session session = sessionFactory.openSession(); String SQL = ” from SaturdayModel as o where o.pepName=? and o.pass=?”; Query query = session.createQuery(SQL); query.setParameter(0, saturdayModel.getPepName()); query.setParameter(1, saturdayModel.getPass()); List list = query.list(); if ((list != null) && (list.size() > 0)) { flag = “success”; } else { flag = “fail”; } return flag; } } |
MODEL CLASS:
This is the source class here we create a table name and declare the variable which are you want to insert and generate getter and setter.In this layer we use @ID,@column annotations.
SOURCE CODE OF MODEL CLASS:
package com.saturday.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name=”Table0007″) public class SaturdayModel implements Serializable{ /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name=”pepId”) private String pepId; @Column(name=”pepName”) private String pepName; @Column(name=”pass”) private String pass;
@Column(name=”pepAge”) private String pepAge; @Column(name = “pepSalary”) private String pepSalary;
public String getPepId() { return pepId; } public void setPepId(String pepId) { this.pepId = pepId; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; }
public String getPepName() { return pepName; } public void setPepName(String pepName) { this.pepName = pepName; } public String getPepAge() { return pepAge; } public void setPepAge(String pepAge) { this.pepAge = pepAge; } public String getPepSalary() { return pepSalary; } public void setPepSalary(String pepSalary) { this.pepSalary = pepSalary; }
} |
VIEW PAGES:
This is the front end process also called as view page.The page is written in jsp language.here we are using two jsp named as “file” and “login”.
SOURCE CODE OF JSP FOR INSERT:
<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″ pageEncoding=”ISO-8859-1″%> <%@taglib uri=”http://www.springframework.org/tags/form” prefix=”form”%> <%@taglib uri=”http://java.sun.com/jsp/jstl/core” prefix=”c”%> <!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> <form:form action=”add.html” method=”POST” commandName=”command”> <table> <tr> <td><form:label path=”pepId”>PEOPLE ID</form:label></td> <td><form:input path=”pepId” value=”${saturdayModel.pepId}” readonly=”true”/></td> </tr> <tr> <td><form:label path=”pepName”>PEOPEL NAME</form:label></td> <td><form:input path=”pepName” value=”${saturdayModel.pepName}”/></td> </tr> <tr> <td><form:label path=”pass”>PEOPEL PASS</form:label></td> <td><form:input path=”pass” value=”${saturdayModel.pass}”/></td> </tr> <tr> <td><form:label path=”pepAge”>PEOPLE AGE</form:label></td> <td><form:input path=”pepAge” value=”${saturdayModel.pepAge}”/></td> </tr> <tr> <td><form:label path=”pepSalary”>PEOPLE SALARY</form:label></td> <td><form:input path=”pepSalary” value=”${saturdayModel.pepSalary}”/></td> </tr> <tr> <td><input type=”submit” value=”Submit”/></td> </tr> <c:if test = “${!empty call}”> <table align=”left” border=”1″> <tr> <th>PEOPLE ID</th> <th>PEOPEL NAME</th> <th>PEOPEL PASS</th> <th>PEOPLE AGE</th> <th>PEOPLE SALARY</th> </tr> <c:forEach items=”${call}” var=”people”> <tr> <td><c:out value=”${people.pepId}”></c:out></td> <td><c:out value=”${people.pepName}”></c:out></td> <td><c:out value=”${people.pass}”></c:out></td> <td><c:out value=”${people.pepAge}”></c:out></td> <td><c:out value=”${people.pepSalary}”></c:out></td> <td><a href=”delete.html?pepId=${people.pepId}”>Delete</a> <a href=”edit.html?pepId=${people.pepId}”>edit</a></td> </tr> </c:forEach> </table> </c:if> </table> </form:form> </body> </html> |
SOURCE CODE OF JSP FOR LOGIN:
<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″ pageEncoding=”ISO-8859-1″%> <%@taglib uri=”http://www.springframework.org/tags/form” prefix=”form”%> <%@taglib uri=”http://java.sun.com/jsp/jstl/core” prefix=”c”%> <!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> <form:form action=”logincheck.html” method=”POST” commandName=”command”> <table> <tr>
<td><form:label path=”pepName”>PEOPEL NAME</form:label></td> <td><form:input path=”pepName” value=”${saturdayModel.pepName}”/></td> </tr> <tr> <td><form:label path=”pass”>PEOPEL PASS</form:label></td> <td><form:input path=”pass” value=”${saturdayModel.pass}”/></td> </tr>
<tr> <td><input type=”submit” value=”Submit”/></td> </tr> </table> </form:form> </body> </html> |
OUTPUT OF THE CODE:
Here click ADD DATA and set the username password here.I select my name and phone as my username and password.
Leave a Reply