Friday, 4 March 2016

Difference Between Struts 2 and Spring 3.x

Better Support of UI Tag
You can also leverage from various tags like UI tags, Data tags, control tags and more.

Struts is pull based MVC while spring is PUSH based MVC

Poor documentation.........while  in spring we have good knowledge base

AJAX support in Struts 2

Ajax Support
Ajax has become a good technology for displaying dynamic content or field validation for web-based applications. In my work as a consultant, I have been fortunate to work with Ajax in both SpringMVC and Struts 2 environments. Struts 2 has built-in Ajax support so there is no need to import a third-party library. So if you are keeping score, Struts 2 has its own view language, controller and Ajax support. Again, once your learn Struts 2 you can pretty much develop a web application from beginning to end without the assistance of almost any other framework.

Struts 2 provides built-in support to AJAX using Dojo Toolkit library. If you are new to Dojo, you may want to go through the Introduction of DOJO Toolkit.

Struts 2 comes with powerful set of Dojo AJAX APIs which you can use to add Ajax support. In order to add Ajax support, you need to add following JAR file in your classpath:
struts2-dojo-plugin.jar

Also once we add this JAR file, we need to add following code snippet in whatever JSP file we need to add AJAX support.

<%@ taglib prefix="sx" uri="/struts-dojo-tags"%>

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="sx" uri="/struts-dojo-tags"%>
<html>
<head>
<title>Welcome</title>
<sx:head />
</head>
<body>
<h2>Struts 2 Autocomplete (Drop down) Example!</h2>

Country:
<sx:autocompleter size="1" list="countries" name="country"></sx:autocompleter>
</action>
</body>
</html>

#################################################################################
In Struts 2, I found it a little difficult to set up RESTful webservices when I first learned it.
 We essentially needed 2 separate xml files (one for RESTful URLs and the re-direct and the second for
the struts action mapping).
Another hassle is that in your Java Action you don’t necessarily know that this is a
RESTful webservice or if it is just a plain old Struts Action. This can be confusing to some
 less experienced developers.

In SpringMVC, RESTful webservices take advantage of annotations which not only makes webservices easier to
identify, it also makes them easier to develop and maintain. The majority of your changes all happen in the
Java class and you just have to touch one xml file once as opposed to Struts 2 where you need to edit 3
different places for adding or removing webservice. I really like the RESTful webservice support in
SpringMVC with an assist from annotations because everything is one place and therefore development time is
shorter.


In Conclusion
These are just some of the things you can use when deciding between SpringMVC and Struts 2. Like I said
in the beginning, there isn’t really a definitive answer to which one is better. However, in my opinion,
I would say if you are looking for a stable framework you should choose Struts 2. If you are looking
 for a more robust framework, you should choose SpringMVC.

Exception Handling in Spring MVC

Step-1
Create a pojo to define format of the message 

package com.bas.admin.exception.handler;

public class BASErrorMessage {
private String status;
private String code;
private String message;
private String ex;
private String moreInfo;

public BASErrorMessage(String status, String code, String message, String ex,
String moreInfo) {
this.status = status;
this.code = code;
this.message = message;
this.ex = ex;
this.moreInfo = moreInfo;
}
}


Step-2

/**
 * 
 * @author nagendra
 * This class is for handling global exception
 *
 */
@ControllerAdvice
public class BASGlobalExceptionHandler {


@ExceptionHandler(SQLException.class)
String handlerDbException(HttpServletRequest req, Exception ex,Model model) {
BASErrorMessage basErrorMessage=new BASErrorMessage(HttpStatus.INTERNAL_SERVER_ERROR.toString(),"5000" , ex.getMessage(), ex.getClass().toString(), req.getRequestURL().toString());
errorLoggerAsString(ex);
model.addAttribute("basErrorMessage", basErrorMessage);
return NavigationConstant.COMMON_PREFIX_PAGE+NavigationConstant.COMMON_ERROR_PAGE;

    
  @ExceptionHandler(Exception.class)
  String handlerGlobalException(HttpServletRequest req, Exception ex,Model model) {
  BASErrorMessage basErrorMessage=new BASErrorMessage(HttpStatus.OK.toString(),"5000" , ex.getMessage(), ex.getClass().toString(), req.getRequestURL().toString());
  errorLoggerAsString(ex);
  model.addAttribute("basErrorMessage", basErrorMessage);
  return NavigationConstant.COMMON_PREFIX_PAGE+NavigationConstant.COMMON_ERROR_PAGE;
 



Step-3
Scan the package for Global Exception Handler


/WEB-INF/bas-context.xml (Spring Web Application Context )

<!-- Scanning controller for annotation for spring mvc --> 
<context:component-scan base-package="com.bas.hr.web.controller"/>
<context:component-scan base-package="com.bas.common.web.controller"/>
<context:component-scan base-package="com.bas.employee.web.controller"/>
<context:component-scan base-package="com.bas.admin.web.controller"/>
<context:component-scan base-package="com.bas.admin.web.report.controller"/>

<context:component-scan base-package="com.bas.admin.exception.handler"/>

Exception Handling in Rest web service!

Step-1

Define some custom exception :-

public class LanguageNotFoundException extends RuntimeException {

public LanguageNotFoundException(String message){
super(message);
}

public LanguageNotFoundException(String message,Exception exe){
super(message,exe);
}
}


public class UserTokenNotValidException extends RuntimeException {

private String userToken;

public String getUserToken() {
return userToken;
}

public void setUserToken(String userToken) {
this.userToken = userToken;
}
}


Step-2

@ControllerAdvice ->>>Spring 3.2

@ControllerAdvice
public class GPSGlobalExceptionHandler {

@Autowired
@Qualifier("UserService")
private UserService userService;

/**
     * Initiate Logger for this class
     */

    private static final Log logger = LogFactory.getLog(GPSGlobalExceptionHandler.class);

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(LanguageNotFoundException.class)
@ResponseBody QuizErrorInfo handleLanguageException(HttpServletRequest req, Exception ex) {
QuizErrorInfo errorInfo=new QuizErrorInfo(HttpStatus.BAD_REQUEST.toString(),"4000" , ex.getMessage(), ex.getClass().toString(), req.getRequestURL().toString());
errorDBLogger(ex, req.getRequestURL().toString());
ex.printStackTrace();
if(logger.isErrorEnabled()){
logger.error(errorInfo);
logger.error(ex.getStackTrace());
}
return errorInfo;
}

@ExceptionHandler(MethodArgumentNotValidException.class)
 @ResponseStatus(HttpStatus.BAD_REQUEST)
 @ResponseBody
 public QuizErrorInfo processValidationError(HttpServletRequest req,MethodArgumentNotValidException ex) {
errorDBLogger(ex, req.getRequestURL().toString());
   BindingResult result = ex.getBindingResult();
   List<FieldError> fieldErrors = result.getFieldErrors();
   String errors= processFieldErrors(fieldErrors);
   QuizErrorInfo errorInfo=new QuizErrorInfo(HttpStatus.BAD_REQUEST.toString(),"3000" , errors, ex.getClass().toString(), req.getRequestURL().toString());
   return errorInfo;
 }

}


Step-3
public class QuizErrorInfo {
private String status;
private String code;
private String message;
private String ex;
private String moreInfo;


public QuizErrorInfo(String status, String code, String message, String ex,
String moreInfo) {
this.status = status;
this.code = code;
this.message = message;
this.ex = ex;
this.moreInfo = moreInfo;
}

}

How to remove and rename attributes from JSON Response in Restful Web Service


@JsonInclude(Include.NON_DEFAULT)
public class TopicVO {

@JsonProperty("topic_id")
private String tid;
@JsonProperty("name")
private String topic;
private int language;
private String languageName;
private Timestamp lastUpdate;
private String adminid;
@JsonIgnore
private Timestamp doe;
@JsonIgnore
private String description;
private String status;

public String getStatus() {
return status;
}

}

What is role of proxy-target-class attribute in AOP, Spring Caching and Transaction


Spring @Transactional annotation different Attributes


Wednesday, 2 March 2016

What is the difference between dependency injection and dependency look up?


  • Dependency lookup:
    • If resource of the application spends time to search and get dependent values from other resources of application, then it is called dependency lookup
    • Example :
      • If the student get his dependent value material from instruction by asking for it then is called dependency lookup.
      • The way servlet / ejb component gets jdbc data source object form registry through jndi lookup operation is called dependency lookup.
    • In dependency lookup, resource perform “pull” operation on other resource or on underlying s/w to get the dependent values.


  • <jee:jndi-lookup id="sdatasource" jndi-name="jdbc/synergy-emp-ds"/>

//@Repository ,@Component,@Controller
@Repository("LoginDaoImpl")
@Transactional
public class LoginDaoImpl implements LoginDao {
@Autowired
@Qualifier("sdatasource")
private DataSource dataSource;

}


  • Dependency injection:
When we create any application there are many classes in it which depend on each other to execute some  business logic. In that case any object which needs other objects to do its work, is responsible for getting  those dependencies itself (by using new keyword) by that way those classes are tightly coupled. 

In case of dependency injection objects  won't be creating their dependencies themselves but the dependencies will be injected into the objects. How Spring helps with dependency injection is you can define your beans in a XML file (there are other ways too) and spring will initialize the classes and create the associations.