How to get the data from database to display on view page by using Angular JS in Spring MyBatis
What
is Spring?
The
Spring Framework is an application framework and inversion of control
container for the Java platform. The framework's core features can be
used by any Java application, but there are extensions for building
web applications on top of the Java EE platform.
I
will create simple web application using SpringMVC +MyBatis
+ AngularJS to show the data
from database(MYSQL) on UI page.
1.Create
JSP File for Student Application:
Create a folder named “jsp” under WEB-INF (This is where the jsp files will be created as indicated in the dispatcher-servlet.xml for the InternalResourceViewResolver bean).
Create a folder named “jsp” under WEB-INF (This is where the jsp files will be created as indicated in the dispatcher-servlet.xml for the InternalResourceViewResolver bean).
By
using AngularJS we can design below screen:
Related to UI page we can see the code as shown in below:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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">
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<body ng-app="myApp" ng-controller="myclr">
<div
class="generic-container" id="reg"
ng-controller="myclr ">
<div
class="panel panel-default" id="reg">
<div
class="panel-heading" id="reg">
<span
class="lead">Dashboard </span>
</div>
<br>
<div
class="formcontainer">
<table
class="table table">
<thead>
<tr
id="style">
<th>FIRST
NAME:</th>
<th>LAST
NAME:</th>
<th>EMAIL:</th>
</tr>
<tr>
<td>{{userData.Firstname}}</td>
<td>{{userData.Lastname}}</td>
<td>{{email=userData.AppEmail}}</td>
</tr>
</thead>
<tbody>
</table>
</div>
</div>
</div>
<script
type="text/javascript">
function
preventBack() {
window.history.forward();
}
setTimeout("preventBack()",
0);
window.onunload
= function() {
null
};
var
app = angular.module('myApp', []);
app.factory('myService',
function() {
var
savedData = {}
function
set(data) {
savedData
= data;
}
function
get() {
return
savedData;
}
return
{
set
: set,
get
: get
}
});
app.controller('myclr',
myclr);
myclr.$inject
= [ '$scope', 'myService', '$http' ];
function
myclr($scope, myService, $http) {
$scope.userData
= JSON.parse(localStorage.getItem("userData"));
$scope.userData
= $scope.userData[0];
var
data = {};
$http
.post(
"http://localhost:8080/StudentJobApplication/CourseService/coursegetpersonaldetails",
data).success(function(response)
{
response
= JSON.stringify(response);
var
myObj = JSON.parse(response);
getresponse
= JSON.stringify(myObj.getstudentlist);
});
};
</script>
</body>
</html>
Whenever
we run the application first of all it hits the service and then it
pass the call to controller, Where it will perform the required
action and then calls the mapping resource in order to fetch the
details from the database which will turns and displays the data on
UI part.
2.Create
packages for Controller, Mappers and Service :
Create
packages each for the Spring Controller, Model and Service classes
under the src/main/java folder. Also create a package for the MyBatis
Mapper class under the same src/main/java folder.
3.Create classes for Model Tier:
Create a POJO class named Student.java and StudentModel.java inside the package com.mybatis.model to include the details of the Student model entity during login.
Create a POJO class named Student.java and StudentModel.java inside the package com.mybatis.model to include the details of the Student model entity during login.
StudentModel.java:
package
com.mybatis.model;
public
Student
{
//
no need of getters and setters
}
Instead
of this just create an interface for the model
4.StudentMapper.java:
package
com.mybatis.mapper;
import
java.util.List;
import
java.util.Map;
public
interface StudentMapper
{
List<HashMap>
studentgetdetails(Map guiMapMessage);
}
5.MyBatis
Mapper:
A
Mapper in MyBatis framework is similar to the Repository tier in a
Spring environment. Crude SQL queries takes its place here. Create an
interface class named StudentMapper.java inside the package
com.mybatis.mapper to support the database operations.
Studentmapper.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.mybatis.mappers.StudentMapper'>
<select
id="studentgetdetails" parameterType="java.util.Map"
fetchSize="25" resultType="java.util.HashMap" >
select
Email,Firstname,Lastname from student where Email= #{email};
</select>
</mapper>
where
Firstname, Lastname,Email are the field names or column names
in MYSQL DB and where class condition should be mentioned in ng-model
name in view page.
6.Create
classes for Service Tier:
Create
an interface class named StudentService.java inside the package
com.mouri.service to support the service tier operations.
StudentService.java
:
package com.mouri.service ;
import
java.util.List;
import
java.util.Map;
public
interface StudentService
{
void
studentgetdetails(Map guiMapMessage);
}
7.Create
a service tier implementation :
Create
a service tier implementation class (a POJO indeed) named
StudentServiceImpl.java
inside
the package com.mouri.serviceImpl. This is where the application
logic goes –
either
to select the student details into the database.
StudentServiceImpl.java:
package
com.mouri.serviceImpl;
import
java.util.List;
import
java.util.Map;
import
java.util.HashMap;
import
org.mybatis.spring.SqlSessionFactoryBean;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.beans.factory.annotation.Qualifier;
import
org.springframework.stereotype.Service;
import
com.mybatis.mappers.StudentMapper;
import
com.mouri.service.StudentService;
@Service
public
class StudentServiceImpl implements StudentService
{
@Autowired
private
StudentMapper studentMapper;
@Autowired
@Qualifier("studentSessionFactory")
private
SqlSessionFactoryBean studentSessionFactory;
//Retrieving
data
@Override
public
List<HashMap> studentgetdetails(Map guiMapMessage) {
//
TODO Auto-generated method stub
System.out.println("getdetails...");
return studentMapper.studentgetdetails(guiMapMessage);
}
}
8.Create
class for Controller Tier:
Create
a Controller tier POJO class named StudentController.java inside the
package
Controller:
RESTful Web services controller is the way the HTTP response body is
created.
REST
Web service controller simply returns the object and the object data
is written directly to the HTTP response as JSON/XML.
StudentController.java
:
@Controller
@RequestMapping(value
= { "/CourseService" })
public
class StudentController {
@Autowired
private
StudentService studentService;
public
static Map<String, Object> jsonToMap(String jsonStr) throws
JSONException {
Map<String,
Object> retMap = new HashMap<String, Object>();
JSONObject
jsonObject = new JSONObject(jsonStr);
if ( jsonObject != null)
{
retMap
= toMap(jsonObject);
}
return
retMap;
}
//General
method to convert JSON object to Map.
public
static Map<String, Object> toMap(JSONObject object) throws
JSONException {
Map<String,
Object> map = new HashMap<String, Object>();
Iterator<String>
keysItr = object.keys();
while
(keysItr.hasNext()) {
String
key = keysItr.next();
Object
value = object.get(key);
if
(value instanceof JSONArray)
{
value = toList((JSONArray) value);
}
else
if (value instanceof JSONObject)
{
value
= toMap((JSONObject) value);
}
map.put(key,
value);
}
return
map;
}
//General method to convert JSONArray to Map.
//General method to convert JSONArray to Map.
public
static List<Object> toList(JSONArray array) throws
JSONException {
List<Object>
list = new ArrayList<Object>();
for
(int i = 0; i < array.length(); i++) {
Object
value = array.get(i);
if
(value instanceof JSONArray) {
value
= toList((JSONArray) value);
}
else if (value instanceof JSONObject) {
value
= toMap((JSONObject) value);
}
list.add(value);
}
return
list;
}
@RequestMapping(value
= { "/coursegetpersonaldetails" }, method =
RequestMethod.POST, consumes =
"application/json")
public
@ResponseBody Map coursegetpersonaldetailsEntry(@Valid @RequestBody
String requestBody,
HttpSession
session) {
Map
returnMapMessage = new HashMap();
try
{
Map
guiMapMessage = jsonToMap(requestBody);
System.out.println(guiMapMessage);
List<HashMap>
getstudentlist = studentService.studentgetdetails(guiMapMessage);
System.out.println(getstudentlist);
returnMapMessage.put("getstudentlist",
getstudentlist);
}
catch (Exception e) {
e.printStackTrace();
returnMapMessage.put("result",
"error");
returnMapMessage.put("errortext",
"Internal
Application Error. Contact Administrator. Error RefId : " +
e.getMessage());
}
return
returnMapMessage;
}
Here,
If
you want dispatcher-servlet.xml, web.xml, Config.xml, Please click to
refer below link
Getting
the data from the database on UI page:
A
Sample snapshot as shown below.
Thanks & Regards,
Leela Maruthi Borra,
Technical Trainee,
MOURI Tech PVT LTD.
http://www.mouritech.com/
Thanks & Regards,
Leela Maruthi Borra,
Technical Trainee,
MOURI Tech PVT LTD.
http://www.mouritech.com/
Comments
Post a Comment