This article demonstrates how to develop a dynamic web application using Spring and Mybatis. As we know that Spring is a front end framework and Mybatis is a persistence framework. By using both of these two technologies let us see how to create a dynamic web application which performs CRUD operations.

Steps to be followed:

Step 1: Create a dynamic web project

Step 2: Configure web.xml and spring-servlet.xml file

Step 3: Download the required jars and add it to lib folder

Step 4: Create 4 packages, Controller, DAO, Entity and Util

Step 5: Create 1 Resources folder, add mybatis-config.xml file to it. Inside that file specify jdbc properties

Step 6: Create folder named jsps inside the WEB-INF

Let’s design the DB first,

database design

NOTE: I am using MySQL DB throughout this article, you can use any other DB.

Let’s create a DB first by executing this command


create database strutscrud;

Let’s get into the DB


use strutscrud;

Let’s design our employee table


create table employee

(

id int not null primary key auto_increment,

fullname varchar(50) not null,

email varchar(50) not null,

gender varchar(50) not null,

hobbies varchar(50) not null,

country varchar(50) not null,

address varchar(50) not null

)

Next step is to create a dynamic web project in eclipse

Open eclipse->File->New->Dynamic web project->Project name->Select web module version 2.5->Finish

project structure

These are the jar files that i used in this project,

jars

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"
xmlns:web="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">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<display-name>Spring3-Mybatis</display-name>
<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>/</url-pattern>
</servlet-mapping>
</web-app>

spring-servlet.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
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/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<!-- Add support for conversion, formatting and validation support -->
<context:component-scan base-package="com.work" />
<mvc:annotation-driven />

<!-- Define Spring MVC view resolver -->
<beans:bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<beans:property name="prefix" value="/WEB-INF/jsps/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>

</beans:beans>

Employee.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="s"%>
<!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>
<center>
<h1>Provide Employee Information</h1>

<hr />

<s:form action="saveProcess" modelAttribute="employee">
<s:hidden path="id" />
<s:hidden path="" value = "${employee.hobbies}" id = "hobbies"/>
<table>
<tr>
<th>Full Name:</th>
<td><s:input path="fullname"/></td>
</tr>
<tr>
<th>Email:</th>
<td><s:input path="email"/></td>
</tr>
<tr>
<th>Gender:</th>
<td>
<s:radiobutton path="gender" value="Male"/>Male&nbsp;
<s:radiobutton path="gender" value="Female"/>Female</td>
</tr>
<tr>
<th>Hobbies:</th>
<td>
<s:checkbox path="hobbies" value="Sports"/>Sports

<s:checkbox path="hobbies" value="Browsing"/>Browsing

<s:checkbox path="hobbies" value="Running"/>Running

<s:checkbox path="hobbies" value="Chatting"/>Chatting</td>
</tr>
<tr>
<th>Country:</th>
<td>
<s:select path="country">
<s:option value="0">--Select--</s:option>
<s:option value="India">India</s:option>
<s:option value="Australia">Australia</s:option>
<s:option value="Japan">Japan</s:option>
<s:option value="America">America</s:option>
<s:option value="South Africa">South Africa</s:option>
<s:option value="Sri Lanka">Sri Lanka</s:option>
</s:select></td>
</tr>
<tr>
<th>Address:</th>
<td><s:textarea path="address"/></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Save" />&nbsp;
<input type="reset" value="Reset" /></td>
</tr>
</table>
</s:form>
</center>

<hr />

<a href = "listOfEmployee">Back to List</a>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
<script type = "text/javascript">
$(document).ready(function() {
var hobbies = $("#hobbies").val().split(",");
var $checkboxes = $("input[type=checkbox]");
$checkboxes.each(function(idx, element){
if(hobbies.indexOf(element.value) != -1){
element.setAttribute("checked", "checked");
$("#hobbies").val("");
}
else{
element.removeAttribute("checked");
}
});
});
</script>
</body>
</html>

ListEmployees.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="s"%>
<!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>
<center>
<h1>Employee Details</h1>
<p align="right"><button onclick="window.location.href = 'showFormForAdd.html'; return false;">Add Employee</button></p>


<hr />

<table border="1">
<tr>
<th>Full Name</th>
<th>Email</th>
<th>Gender</th>
<th>Hobbies</th>
<th>Country</th>
<th>Address</th>
<th>Actions</th>
</tr>
<c:forEach items="${employeeList}" var="e">
<c:url var="updateLink" value="/employee/displayUpdateForm.html">
<c:param name="employeeId" value="${e.id}" />
</c:url>

<c:url var="deleteLink" value="/employee/displayDeleteForm.html">
<c:param name="employeeId" value="${e.id}" />
</c:url>
<tr>
<td>${e.fullname}</td>
<td>${e.email}</td>
<td>${e.gender}</td>
<td>${e.hobbies}</td>
<td>${e.country}</td>
<td>${e.address}</td>
<td>
<a href="${updateLink}">Update</a>
|
<a href="${deleteLink}" onclick="if(!(confirm('Are you sure want to delete this Employee permanently?'))) return false">Delete</a></td>
</tr>
</c:forEach></table>
</center>

<hr />

</body>
</html>

mybatis-config.xml


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias type="com.work.entity.Employee" alias="employee"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/strutscrud"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/work/dao/EmployeeMapper.xml" />
</mappers>
</configuration>

MyBatisUtil.java


package com.work.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisUtil {
private static SqlSessionFactory sqlSessionFactory;
static {
Reader reader;
try {
reader = Resources.getResourceAsReader("resources/mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSqlSessionFactory(){
return sqlSessionFactory;
}
}

Employee.java


package com.work.entity;

public class Employee {

private Integer id;
private String fullname;
private String email;
private String gender;
private String hobbies;
private String country;
private String address;

public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getHobbies() {
return hobbies;
}
public void setHobbies(String hobbies) {
this.hobbies = hobbies;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}

}

EmployeeMapper.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.work.dao.EmployeeMapper">

<resultMap type="employee" id="result">
<id property="id" column="id" />
<result property="fullname" column="fullname" />
<result property="email" column="email" />
<result property="gender" column="gender" />
<result property="hobbies" column="hobbies" />
<result property="country" column="country" />
<result property="address" column="address" />
</resultMap>

<select id="getAllEmployees" resultType="employee" resultMap="result">
SELECT * FROM employee
</select>

<insert id="insertEmployee" parameterType="employee" keyProperty="id" useGeneratedKeys="true">
INSERT INTO employee(fullname, email, gender, hobbies, country, address)
VALUES(#{fullname}, #{email}, #{gender}, #{hobbies}, #{country}, #{address})
</insert>

<update id="updateEmployee" parameterType="employee">
UPDATE employee SET fullname = #{fullname}, email = #{email}, gender = #{gender}, hobbies = #{hobbies}, country = #{country}, address = #{address}
WHERE id = #{id}
</update>

<delete id="deleteEmployee" parameterType="int">
DELETE FROM employee WHERE id = #{employeeId}
</delete>

<select id="findById" parameterType="int" resultType="employee" resultMap="result">
SELECT * FROM employee WHERE id = #{employeeId}
</select>
</mapper>

EmployeeMapper.java


<strong></strong>package com.work.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;

import com.work.entity.Employee;
import com.work.util.MyBatisUtil;

@Repository
public class EmployeeMapper {

public void saveEmployee(Employee employee){
SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession();
session.insert("insertEmployee", employee);
session.commit();
session.close();
}

public void updateEmployee(Employee employee){
SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession();
session.update("updateEmployee", employee);
session.commit();
session.close();
}

public void deleteEmployee(int employeeId){
SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession();
session.delete("deleteEmployee", employeeId);
session.commit();
session.close();
}

public List<Employee> getAllEmployees(){
SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession();
@SuppressWarnings("unchecked")
List<Employee> employeesList = session.selectList("getAllEmployees");
session.commit();
session.close();
return employeesList;
}

public Employee findById(int employeeId){
SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession();
Employee employee = (Employee) session.selectOne("findById", employeeId);
session.commit();
session.close();
return employee;
}
}

EmployeeController.java


package com.work.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.work.dao.EmployeeMapper;
import com.work.entity.Employee;

@Controller @RequestMapping("/employee")
public class EmployeeController {

@Autowired
EmployeeMapper employeeMapper;

private static final String EMPLOYEE = "Employee";
private static final String EMPLOYEELIST = "ListEmployees";

@RequestMapping("/listOfEmployee")
public String showListOfEmployees(Model model){
model.addAttribute("employeeList", employeeMapper.getAllEmployees());
return EMPLOYEELIST;
}

@RequestMapping("/showFormForAdd")
public String addEmployee(Model model){
model.addAttribute("employee", new Employee());
return EMPLOYEE;
}

@RequestMapping("/saveProcess")
public String saveEmployee(@ModelAttribute("employee") Employee employee){
if(employee.getId() == null){
employeeMapper.saveEmployee(employee);
}else{
employeeMapper.updateEmployee(employee);
}

return "redirect:/employee/listOfEmployee";
}

@RequestMapping("/displayUpdateForm")
public String showUpdateForm(@RequestParam("employeeId") int employeeId, Model model){
model.addAttribute("employee", employeeMapper.findById(employeeId));
return EMPLOYEE;
}

@RequestMapping("/displayDeleteForm")
public String deleteEmployee(@RequestParam("employeeId") int employeeId){
employeeMapper.deleteEmployee(employeeId);
return "redirect:/employee/listOfEmployee";
}
}

index.jsp


<% response.sendRedirect("employee/listOfEmployee.html"); %>

Finally, run the project on server.

Here are some of the screenshots of the final project

Thanks and Regards,

Bushan Sirgur

Advertisements