Part 1.
In this tutorial, we will create a simple CRUD (Create Read Update Delete) User Management Web Application using Jsp, Servlet, angulerjs .
I will see every article in anguler js REST end point using server site REST web service. Rest web service need REST framework to add in your web application.small application we don't want add this. so i will write this article how to use Servlet as a rest end point.
For this tutorial, we will need the following tools: (The older or newer version should also works). Moreover, basic Java knowledge is assumed.
1. Eclipse Kepler j2ee
2. Tomcat 7
3. Angular js
4. Twitter bootstrap
5. JSON
I will follow MVC(Model-View-Controller) pattern for this article.
Go to eclipse
1. Before we create a new project for our application, we need to setup the server. Select File—>New—>Other. From the tree, Select Server.
Choose Apache—>Tomcat v7.0 Server and set the runtime environment.
2. Create a new project. Select File—>New—>Dynamic Web Project.Enter “CRUD” as the project name. Select target runtime to Apache Tomcat v7.0 which we already setup before. Click Finish.Then Create four packages in the src folder.
com.rid.model : contains the POJO (Plain Old Java Object). Each class in this package represents the database table. For this tutorial, however, we only have one table.
com.rid.ctrl : contains the servlets.
com.rid.service :contains the service class that use for perform crud operation .
Complete folder structure.
3 .create new java class in com.rid.model package Name User.java .Write following code
See the User(JSONObject json) constructor this will convert JSON object to POJO using reflection java api. for example:
JSON OBJECT
See toString method in User.java class . its return User object in string .its method i will also use
reflection api. for example its return
4. com.rid.service package create UserServiceI interface . and then create new class UserServiceImpl.java implement UserServiceI.
UserServiceI.java
UserServiceImpl.java
package com.rid.service;
This class i will use memory Map for Crud operation perform. if you want to use jdbc create new class somthing like this
5.In com.rid.ctrl package. Create New servlet UserCtrl.java.
See the following code i will get post data in request and convert in to Json Object.
String path = request.getPathInfo(); get the request URI and see method getUserId(String path) .This get user Id.
doGet method used for get specific User and get Users List.(users/:id and users )
doPost method used for save/update User.(users/:id and users )
doDelete method used for delete User .(users/:id )
Source Code: coming soon(Wait for github link)
All method return user in json form.That's all done in server site. First part is done.
In this tutorial, we will create a simple CRUD (Create Read Update Delete) User Management Web Application using Jsp, Servlet, angulerjs .
I will see every article in anguler js REST end point using server site REST web service. Rest web service need REST framework to add in your web application.small application we don't want add this. so i will write this article how to use Servlet as a rest end point.
For this tutorial, we will need the following tools: (The older or newer version should also works). Moreover, basic Java knowledge is assumed.
1. Eclipse Kepler j2ee
2. Tomcat 7
3. Angular js
4. Twitter bootstrap
5. JSON
I will follow MVC(Model-View-Controller) pattern for this article.
Go to eclipse
1. Before we create a new project for our application, we need to setup the server. Select File—>New—>Other. From the tree, Select Server.
Choose Apache—>Tomcat v7.0 Server and set the runtime environment.
2. Create a new project. Select File—>New—>Dynamic Web Project.Enter “CRUD” as the project name. Select target runtime to Apache Tomcat v7.0 which we already setup before. Click Finish.Then Create four packages in the src folder.
com.rid.model : contains the POJO (Plain Old Java Object). Each class in this package represents the database table. For this tutorial, however, we only have one table.
com.rid.ctrl : contains the servlets.
com.rid.service :contains the service class that use for perform crud operation .
Complete folder structure.
3 .create new java class in com.rid.model package Name User.java .Write following code
package com.rid.model;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import org.json.JSONObject;
public class User {
private int id;
private String firstName;
private String lastName;
private String emailId;
private String password;
private String userName;
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public User() {
super();
}
public User(JSONObject json) {
try {
BeanInfo info = Introspector.getBeanInfo(this.getClass());
PropertyDescriptor[] props = info.getPropertyDescriptors();
for (int i = 0; i < props.length; i++) {
PropertyDescriptor prop = props[i];
Method getter = prop.getReadMethod();
Method setter = prop.getWriteMethod();
Class param = getter.getReturnType();
try {
Object setVal = null;
if (!json.isNull(prop.getName())) {
if (param == int.class)
setVal = json.getInt(prop.getName());
else if (param == long.class)
setVal = json.getLong(prop.getName());
else if (param == String.class)
setVal = json.getString(prop.getName());
else if (param == boolean.class)
setVal = json.getBoolean(prop.getName());
else if (param == Double.class)
setVal = json.getDouble(prop.getName());
else
continue;
setter.invoke(this, new Object[] { setVal });
System.out
.println(getter.invoke(this, (Object[]) null));
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer(this.getClass().getSimpleName()+"[");
Method[] ms = this.getClass().getMethods();
String mName = null;
for (int i = 0; i < ms.length; i++) {
mName = ms[i].getName();
if (mName.startsWith("get")) {
try {
buffer.append("\n\t" + mName + " = "
+ ms[i].invoke(this, (Object[]) null));
} catch (Exception e) {
}
}
}
buffer.append("]");
return buffer.toString();
}
}This Project use json object .Copy json.jar in WebContent\WEB-INF\lib folder.
See the User(JSONObject json) constructor this will convert JSON object to POJO using reflection java api. for example:
JSON OBJECT
{
"id":1, // store in id field in User.java
"firstName":"joe", // store in firstName field in User.java
"lastName":"smith" , // store in lastName field in User.java
"emailId" :"joe@example.com", // store in emailId field in User.java
"password":"zxre45vg", // store in password field in User.java
"userName":"joe_smith" // store in userName field in User.java
}
See toString method in User.java class . its return User object in string .its method i will also use
reflection api. for example its return
user[more detailed for reflection api see http://docs.oracle.com/javase/tutorial/reflect/
id =1,
firstName =joe
lastName =smith
emailId =joe@example.com
password =zxre45vg
userName =joe_smith
]
4. com.rid.service package create UserServiceI interface . and then create new class UserServiceImpl.java implement UserServiceI.
UserServiceI.java
package com.rid.service;
import java.util.List;
import com.rid.model.User;
public interface UserServiceI {
public User add(User base);
public User get(Integer id);
public User update(User user);
public User delete(User user);
public List<User> search();
public List<User> list();
}
UserServiceImpl.java
package com.rid.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.rid.model.User;
public class UserServiceImpl implements UserServiceI {
static Map<Integer, User> map=new HashMap<Integer, User>();
@Override
public User add(User user) {
System.out.println("add call");
Integer id=this.map.size()+1;
user.setId(id);
this.map.put(id,user);
return user;
}
@Override
public User get(Integer id) {
System.out.println("get call");
return this.map.get(id);
}
@Override
public User update(User user) {
System.out.println("update call");
this.map.put(user.getId(),user);
return user;
}
@Override
public User delete(User user) {
System.out.println("delete call");
this.map.remove(user.getId());
return user;
}
@Override
public List<User> search() {
// TODO Auto-generated method stub
return null;
}
@Override
public List<User> list() {
System.out.println(this.map.values());
List l =new ArrayList<User>(this.map.values());
return l;
}
}
This class i will use memory Map for Crud operation perform. if you want to use jdbc create new class somthing like this
package com.rid.service;you will write code yourself for jdbc operation .
import java.util.List;
import com.rid.model.User;
public class UserServiceJDBCImpl implements UserServiceI {
@Override
public User add(User base) {
// TODO Auto-generated method stub
return null;
}
@Override
public User get(Integer id) {
// TODO Auto-generated method stub
return null;
}
@Override
public User update(User user) {
// TODO Auto-generated method stub
return null;
}
@Override
public User delete(User user) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<User> search() {
// TODO Auto-generated method stub
return null;
}
@Override
public List<User> list() {
// TODO Auto-generated method stub
return null;
}
}
5.In com.rid.ctrl package. Create New servlet UserCtrl.java.
package com.rid.ctrl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import com.rid.model.User;
import com.rid.service.UserServiceI;
import com.rid.service.UserServiceImpl;
/**
* Servlet implementation class UserCtrl
*/
@WebServlet("/users/*")
public class UserCtrl extends HttpServlet {
private UserServiceI service = null;
@Override
public void init() throws ServletException {
this.service = new UserServiceImpl();
}
// path {users/:id or users} method {Get}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String pathInfo = httpRequest.getPathInfo();
String path = request.getPathInfo();
Object data = null;
//path users/:id
if (path != null) {
Integer id = getUserId(path);
data = new JSONObject(service.get(id));
}
//path users
if (path == null) {
List list = service.list();
data = new JSONArray(list);
}
PrintWriter writer = response.getWriter();
response.setContentType("application/json");
writer.write(data.toString());
writer.close();
}
// path {users/:id or users} method {Post}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String pathInfo = httpRequest.getPathInfo();
String path = request.getPathInfo();
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
JSONObject jsonObject = new JSONObject(jb.toString());
User user = new User(jsonObject);
if (path != null) {
Integer id = getUserId(path);
service.update(user);
}
if (path == null) {
if (user.getId() > 0)
user = service.update(user);
else
user = service.add(user);
}
} catch (Exception e) { /* report an error */
}
}
// path {users/:id} method {Delete}
@Override
protected void doDelete(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String path = request.getPathInfo();
Object data = null;
if (path != null) {
Integer id = getUserId(path);
User user = new User();
user.setId(id);
data = new JSONObject(service.delete(user));
}
PrintWriter writer = response.getWriter();
response.setContentType("application/json");
writer.write(data.toString());
writer.close();
}
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
super.doPut(req, resp);
}
public Integer getUserId(String path) {
try {
String[] urldata = path.split("/");
return Integer.parseInt(urldata[1]);
} catch (Exception e) {
}
return 0;
}
}
See the following code i will get post data in request and convert in to Json Object.
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
JSONObject jsonObject = new JSONObject(jb.toString());
String path = request.getPathInfo(); get the request URI and see method getUserId(String path) .This get user Id.
doGet method used for get specific User and get Users List.(users/:id and users )
doPost method used for save/update User.(users/:id and users )
doDelete method used for delete User .(users/:id )
Source Code: coming soon(Wait for github link)
All method return user in json form.That's all done in server site. First part is done.
No comments:
Post a Comment