Restful Webservice with angular
JAVA-SERVLETS JAVA-JDBC JAVA-JSP HIBERNATE-SHCEMABASED
SPRING-AOP-ANNOTATIONS SPRING -DAO SPRIN-MVC SPRING-SECUTITY
SPRING-DATA-JPA REST-WEB-SERVICE STRUTS2HIBERNATE GWT....Project structure:
-----------------------------------------------
@Path("user")
@Component
public class UserApiResource {
private UserReadPlatformService userReadPlatformService;
private UserWriteplatformService userWriteplatformService;
private final UserRepository userRepository;
@Autowired
public UserApiResource( final UserReadPlatformService userReadPlatformService,final UserRepository userRepository,
final UserWriteplatformService userWriteplatformService){
this.userReadPlatformService=userReadPlatformService;
this.userRepository = userRepository;
this.userWriteplatformService = userWriteplatformService;
}
@GET
@Path("list")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public List<User> getUsersList(){
List<User> users=this.userReadPlatformService.retrieveUserList();
return users;
}
@GET
@Path("{id}")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public User getUserDetails(@PathParam("id") long id) {
User user = null;
try {
user = userReadPlatformService.getUserById(id);
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
@POST
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Status createUser(String json){
System.out.println(json);
Status status = this.userWriteplatformService.createUser(json);
return status;
}
@PUT
@Path("changepassword/{id}")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Status changePassword(@PathParam("id") long id, String jsonData) {
try {
Status status = this.userWriteplatformService.changePassword(jsonData,id);
return status;
} catch (Exception e) {
return new Status(0, e.toString());
}
}
@POST
@Path("login")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Status login(String login) {
try {
JSONObject json = new JSONObject(login);
String username = json.getString("username");
String password = json.getString("password");
String loginType = json.getString("loginType");
System.out.println(login);
Status status = userReadPlatformService.authantication(new Login(username,password,loginType));
System.err.println(status.getLogin().getEmail());
return status;
} catch (Exception e) {
// e.printStackTrace();
return new Status(0, e.toString());
}
}
}
Reposotory class:
-----------------------------
UserRepository .java
public interface UserRepository extends
JpaRepository<User, Long>,
JpaSpecificationExecutor<User>{
}
Entity class:
-------------------------------
User.java
-------------
@Entity
@Table(name = "users")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
@Column(name = "id")
private long id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
}
Service class :
---------------------
UserWriteplatformServiceImpl.java
------------------------------------------------
@Service
public class UserWriteplatformServiceImpl implements UserWriteplatformService{
private final UserRepository userRepository;
@Autowired
public UserWriteplatformServiceImpl(final UserRepository userRepository){
this.userRepository = userRepository;
}
public Status createUser(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
final String firstName = jsonObject.getString("firstName");
final String lastName = jsonObject.getString("lastName");
final String username = jsonObject.getString("username");
final String email = jsonObject.getString("email");
final String phone = jsonObject.getString("phone");
User user = new User(null,firstName, lastName, email, phone,StringConstants.STATUS_PENDING,username,"N");
this.userRepository.save(user);
//this.sendMail(StringConstants.ACTION_REGISTER,user);
return new Status(1,"User Created Successfully..! Need to approve by Admin");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return new Status(0,"User Creation Failed");
}catch (DataIntegrityViolationException e) {
return new Status(0,"User name is already taken....");
}
}
public Status changePassword(String jsonData, long id) {
JSONObject json;
try {
json = new JSONObject(jsonData);
String oldPassword = json.getString("oldpassword");
String newPassword = json.getString("newpassword");
User user = this.userRepository.findOne(id);
if(user != null && oldPassword.equalsIgnoreCase(user.getPassword())){
user.setPassword(newPassword);
user.setIsPwdChanged("Y");
this.userRepository.save(user);
}else{
throw new PasswordWrongException();
}
return new Status(1,"Success");
} catch (JSONException e) {
e.printStackTrace();
return new Status(0,"Fail");
}
}
Rest configutaiotn in web.xml
---------------------------------------------
<web-app>
<display-name>Utility Manager Service</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/service/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.fm.fmrecruit.api</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/service/*</url-pattern>
</servlet-mapping>
--------------------------------------------------------------------------------------
Angular js project structure:
-------------------------------------
Resister.control.js
-----------------------------
(function () {
'use strict';
angular
.module('app')
.controller('RegisterController', RegisterController);
RegisterController.$inject = ['UserService', '$location', '$rootScope', 'FlashService'];
function RegisterController(UserService, $location, $rootScope, FlashService) {
var vm = this;
vm.register = register;
function register() {
vm.dataLoading = true;
if(vm.regType == 'user'){
UserService.Create(vm.user)
.then(function (response) {
console.log(response);
if (response.data.code ==1) {
FlashService.Success(response.data.message, true);
$location.path('/login');
} else {
FlashService.Error(response.data.message);
vm.dataLoading = false;
}
});
}else{
UserService.CreateAdmin(vm.user)
.then(function (response) {
console.log(response);
if (response.data.code ==1) {
FlashService.Success(response.data.message, true);
$location.path('/login');
} else {
FlashService.Error(response.data.message);
vm.dataLoading = false;
}
});
}
}
}
})();
-------------------------------------------------------------
register.view.html
----------------------------
<div class="col-md-6 col-md-offset-3" ng-controller="RegisterController">
<h2>Register</h2>
<div ng-show="vm.error" class="alert alert-danger">{{vm.error}}</div>
<form name="form" ng-submit="vm.register()" role="form">
<div class="form-group" ng-class="{ 'has-error': form.firstName.$dirty && form.firstName.$error.required }">
<label for="username">Registration Type</label>
<div class="controls" style="margin-top:5px;">
<input type="radio" ng-model="vm.regType" value="user" >User
<input type="radio" ng-model="vm.regType" value="admin">Admin
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': form.firstName.$dirty && form.firstName.$error.required }">
<label for="username">First name</label>
<input type="text" name="firstName" id="firstName" class="form-control" ng-model="vm.user.firstName" required />
<span ng-show="form.firstName.$dirty && form.firstName.$error.required" class="help-block">First name is required</span>
</div>
<div class="form-group" ng-class="{ 'has-error': form.lastName.$dirty && form.lastName.$error.required }">
<label for="username">Last name</label>
<input type="text" name="lastName" id="Text1" class="form-control" ng-model="vm.user.lastName" required />
<span ng-show="form.lastName.$dirty && form.lastName.$error.required" class="help-block">Last name is required</span>
</div>
<div class="form-group" ng-class="{ 'has-error': form.username.$dirty && form.username.$error.required }">
<label for="username">Username</label>
<input type="text" name="username" id="username" class="form-control" ng-model="vm.user.username" required />
<span ng-show="form.username.$dirty && form.username.$error.required" class="help-block">Username is required</span>
</div>
<div ng-if="vm.regType == 'admin'" class="form-group" ng-class="{ 'has-error': form.password.$dirty && form.password.$error.required }">
<label for="password">Password</label>
<input type="password" name="password" id="password" class="form-control" ng-model="vm.user.password" required />
<span ng-show="form.password.$dirty && form.password.$error.required" class="help-block">Password is required</span>
</div>
<div class="form-group" ng-class="{ 'has-error': form.email.$dirty && form.email.$error.required }">
<label for="password">Email</label>
<input type="email" name="email" id="email" class="form-control" ng-model="vm.user.email" required />
<span ng-show="form.password.$dirty && form.password.$error.required" class="help-block">email is required</span>
</div>
<div class="form-group" ng-class="{ 'has-error': form.email.$dirty && form.email.$error.required }">
<label for="password">Phone</label>
<input type="phone" name="phone" id="phone" class="form-control" ng-model="vm.user.phone" required />
<span ng-show="form.phone.$dirty && form.phone.$error.required" class="help-block">phone is required</span>
</div>
<div class="form-actions">
<button type="submit" ng-disabled="form.$invalid || vm.dataLoading" class="btn btn-primary">Register</button>
<a href="#/login" class="btn btn-link">Cancel</a>
</div>
</form>
</div>