dineshonjava

What is GitHub and Creating Repository & Branches on Git

Table of Contents

  1. Overview
  2. What is Github?
  3. Creating and Using Repository
  4. Create New Branch and Managing
  5. Pushing changes to a file to GitHub as commits
  6. Open and merge a pull request


Overview
In this git tutorial we are going to discuss about the GitHub and how to create the repository to github and start a new branch and managing the branches.

What is Github?
GitHub is a code hosting platform for version control and collaboration. It lets you and others work together on projects from anywhere. GitHub essentials like repositories, branches, commits, and pull requests to any project. For using it, you just need a GitHub.com account and Internet access.
Creating and Using Repository
A repository is usually used to organize a single project. Repositories can contain folders and files, images, videos, spreadsheets, and data sets – anything your project needs. We recommend including a README, or a file with information about your project. To create a new repository following steps are required.
 Step 1: In the upper right corner, next to your username, click and then click New repository.
 Step 2: Name your repository "Spring-Project".
 Step 3: Write a short description.
 Step 4: Select Initialize this repository with a README.
 Step 5: Click Create repository.

What is GitHub and Creating Repository & Branches on Git

Create New Branch and Managing
Branching is the way to work on different versions of a repository at one time. By default your repository has one branch named master which is considered to be the definitive branch. We use branches to experiment and make edits before committing them to master.

When you create a branch off the master branch, you’re making a copy, or snapshot, of master as it was at that point in time. If someone else made changes to the master branch while you were working on your branch, you could pull in those updates.
branching in github

This diagram shows:

  • The master branch
  • A new branch called feature (because we’re doing ‘feature work’ on this branch)
  • The journey that feature takes before it’s merged into master
For creating a new branch have to use following Steps.

Step 1: Go to your new repository Spring-Project.
Step 2: Click the drop down at the top of the file list that says branch: master.
Step 3: Type a branch name, "UAT", into the new branch text box.
Step 4: Select the blue Create branch box or hit “Enter” on your keyboard.

branching git

Now you have two branches, master and UAT. They look exactly the same, but not for long! Next we’ll add our changes to the new branch.

Pushing changes to a file to GitHub as commits
On GitHub, saved changes are called commits. Each commit has an associated commit message, which is a description explaining why a particular change was made. Commit messages capture the history of your changes, so other contributors can understand what you’ve done and why. Use following steps for Make and commit changes

Step 1: Click the README.md file.
Step 2: Click the pencil icon in the upper right corner of the file view to edit.
Step 3: In the editor, write a bit about yourself.
Step 4: Write a commit message that describes your changes.
Step 5: Click Commit changes button.

git commit

These changes will be made to just the README file on your UAT branch, so now this branch contains content that’s different from master.

Open and merge a pull request
Now that you have changes in a branch off of master, you can open a pull request.

Pull Requests are the heart of collaboration on GitHub. When you open a pull request, you’re proposing your changes and requesting that someone review and pull in your contribution and merge them into their branch. Pull requests show diffs, or differences, of the content from both branches. The changes, additions, and subtractions are shown in green and red.

For Open a Pull Request for changes to the README as following steps

Step 1: Click the Pull Request tab, then from the Pull Request page, click the green New pull request button.
Step 2: Select the branch you made, "UAT", to compare with master (the original).

Step 3: Look over your changes in the diffs on the Compare page, make sure they’re what you want to submit.

Step 4: When you’re satisfied that these are the changes you want to submit, click the big green Create Pull Request button.

Step 5: Give your pull request a title and write a brief description of your changes.

git pull

Merge your Pull Request
In this final step, it’s time to bring your changes together – merging your UAT branch into the master branch.

Step 1: Click the green Merge pull request button to merge the changes into master.
Step 2: Click Confirm merge.
Step 3: Go ahead and delete the branch, since its changes have been incorporated, with the Delete branch button in the purple box.

git merge
git delete branch

Summary

By completing this tutorial, you’ve learned to create a project and make a pull request on GitHub.
Here’s what you accomplished in this article:

  • Created an open source repository
  • Started and managed a new branch
  • Changed a file and committed those changes to GitHub
  • Opened and merged a Pull Request



Exception Handling for REST with Spring using ExceptionHandler and ControllerAdvice Annotation

Exception Handling for REST with Spring using ExceptionHandler and ControllerAdvice Annotation
Table of Contents

  1. Overview
  2. @ExceptionHandler
  3. @ControllerAdvice
  4. ExceptionHandlerResolver
  5. Handle the Access Denied in Spring Security
  6. Summary

1. Overview
Here we are going describe how to implement Exception Handling with Spring for a REST API.
Before Spring 3.2
there are two main approaches to handling exceptions in a Spring MVC application were: HandlerExceptionResolver or the @ExceptionHandler annotation. Both of these have some clear downsides.

After Spring 3.2
We now have the new @ControllerAdvice annotation to address the limitations of the previous two solutions.

All of these do have one thing in common – they deal with the separation of concerns very well. The app can throw exception normally to indicate a failure of some kind – exceptions which will then be handled separately.


2. The Controller level using @ExceptionHandler

Here we will define a method to handle exceptions, and annotate that with @ExceptionHandler at controller level. This solution is limited to the controller only for same type of exceptions i.e. this approach has a major drawback – the @ExceptionHandler annotated method is only active for that particular Controller, not globally for the entire application. Of course adding this to every controller makes it not well suited for a general exception handling mechanism.

We can avoid this limitation by making base controller which is extended by every controllers in the application however this can be a problem for applications where, for whatever reasons, the Controllers cannot be made to extend from such a class because this not good approach for reducing loose coupling.

@Controller
public class WebController {
       @ExceptionHandler(StudentNotFoundException.class)
 public ModelAndView handleStudentNotFoundException(StudentNotFoundException ex) {
  Map<String, String> model = new HashMap<String, String>();
  model.put("exception", ex.toString());
  return new ModelAndView("student.error", model);

 }
}

3. The New @ControllerAdvice (Spring 3.2 and Above)

From Spring 3.2 offers to global exception handling @ExceptionHandler with the new @ControllerAdvice annotation, this enables a mechanism that breaks away from the older MVC model and makes use of ResponseEntity along with the type safety and flexibility of @ExceptionHandler:

package com.doj.spring.web.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@ControllerAdvice
public class RestResponseEntityExceptionHandler extends
  ResponseEntityExceptionHandler {
 @ExceptionHandler(value = { IllegalArgumentException.class, IllegalStateException.class })
    protected ResponseEntity<Object> handleConflict(RuntimeException ex, WebRequest request) {
        String bodyOfResponse = "This should be application specific";
        return handleExceptionInternal(ex, bodyOfResponse, 
          new HttpHeaders(), HttpStatus.CONFLICT, request);
    }
}


The new annotation allows the multiple scattered @ExceptionHandler from before to be consolidated into a single, global error handling component.

The actual mechanism is extremely simple but also very flexible:

  • it allows full control over the body of the response as well as the status code
  • it allows mapping of several exceptions to the same method, to be handled together
  • it makes good use of the newer RESTful ResposeEntity response


One thing to keep in mind here is to match the exceptions declared with @ExceptionHandler with the exception used as argument of the method. If these don’t match, the compiler will not complain – no reason it should, and Spring will not complain either.

4. The HandlerExceptionResolver

It will also allow us to implement a uniform exception handling mechanism in our REST API.

ExceptionHandlerExceptionResolver

This resolver was introduced in Spring 3.1 and is enabled by default in the DispatcherServlet. This is actually the core component of how the @ExceptionHandler mechanism presented earlier works.

DefaultHandlerExceptionResolver

This resolver was introduced in Spring 3.0 and is enabled by default in the DispatcherServlet. It is used to resolve standard Spring exceptions to their corresponding HTTP Status Codes.

ResponseStatusExceptionResolver

This resolver was also introduced in Spring 3.0 and is enabled by default in the DispatcherServlet. It’s main responsibility is to use the @ResponseStatus annotation available on custom exceptions and to map these exceptions to HTTP status codes.

package com.doj.spring.web.exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="Student Not Found")
public class StudentNotFoundException extends RuntimeException{

 /**
  * 
  */
 private static final long serialVersionUID = -2581975292273282583L;
 
 String errorMessage;
 
 String errorCode;

 public StudentNotFoundException(String errorMessage, String errorCode) {
  super();
  this.errorMessage = errorMessage;
  this.errorCode = errorCode;
 }

 public String getErrorMessage() {
  return errorMessage;
 }

 public void setErrorMessage(String errorMessage) {
  this.errorMessage = errorMessage;
 }

 public String getErrorCode() {
  return errorCode;
 }

 public void setErrorCode(String errorCode) {
  this.errorCode = errorCode;
 }
 
}


Same as the DefaultHandlerExceptionResolver, this resolver is limited in the way it deals with the body of the response – it does map the Status Code on the response, but the body is still null.

Custom HandlerExceptionResolver
The combination of DefaultHandlerExceptionResolver and ResponseStatusExceptionResolver goes a long way towards providing a good error handling mechanism for a Spring RESTful Service. The downside is – as mentioned before – no control over the body of the response.

Ideally, we’d like to be able to output either JSON or XML, depending on what format the client has asked for via the Accept header.

5. Handle the Access Denied in Spring Security

MVC – Custom Error Page
XML configuration:
<http>
    <intercept-url pattern="/admin/*" access="hasAnyRole('ROLE_ADMIN')"/>   
    ... 
    <access-denied-handler error-page="/custom-error-page" />
</http>

Java Configuration:
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/admin/*").hasAnyRole("ROLE_ADMIN")
        ...
        .and()
        .exceptionHandling().accessDeniedPage("/custom-error-page");
}

When users tries to access a resource without having enough authorities, they will be redirected to "/custom-error-page".

6. Summary

This tutorial discussed several ways to implement an exception handling mechanism for a REST API in Spring.



Spring @RequestMapping Annotation Example with @RequestParam, @PathVariable

Spring @RequestMapping Annotation Example with @RequestParam, @PathVariable

In this article, we are going discuss about one of the main annotation in Spring MVC @RequestMapping – used to mapping a web request to Spring Controller's handler methods.

All incoming requests are handled by the Dispatcher Servlet and it route them through Spring. When it receives a web request, it determines which controllers should handle the incoming request.

Dispatcher Servlet initially scans all the classes that are annotated with the @Controller annotation. The dispatching process depends on the various @RequestMapping annotations declared in a controller class and its handler methods.
There are three levels of request mapping in Spring MVC
  • @RequestMapping annotations at only method level
  • @RequestMapping annotations at class level
  • Mapping requests by request type

@RequestMapping can be applied to the controller class as well as methods. This annotation for mapping web requests onto specific handler classes and/or handler methods.

Spring MVC RequestMapping Annotation
@ImageSource-SlideShare.net
@RequestMapping annotations at only method level
In this case we are using @RequestMapping annotations is to declare the handler methods directly. The handler method is annotated with @RequestMapping annotation containing a URL pattern. If this pattern of a handler @RequestMapping annotation matches the request URL, DispatcherServlet it dispatches the request to this handler for it to process the request.
1. @RequestMapping Basics

Let’s discuss with a simple example – mapping an HTTP request to a method using some straightforward criteria.

1.1 @RequestMapping – by Path

@RequestMapping(value = "/doj/spring")
 @ResponseBody
 public String getDOJSpringCourse(){
    return "Get DOJ Course for Spring";
 }
Popular Tutorials
Spring Tutorial Spring MVC Web Tutorial Spring Boot Tutorial
Spring Security Tutorial Spring AOP Tutorial Spring JDBC Tutorial
Spring HATEOAS Microservices with Spring Boot REST Webservice
Core Java Hibernate Tutorial Spring Batch
For testing hit following URL on browser:

GET http://localhost:8080/SpringApp/doj/spring

-- response --
200 OK
Server: Apache-Coyote/1.1
Content-Type: text/html
Content-Length: 25
Date: Fri, 18 Mar 2016 10:38:14 GMT

Get DOJ Course for Spring


1.2  @RequestMapping – the HTTP Method

There is no by default HTTP method mapped by a @RequestMapping – so it maps to any type of HTTP request; we sh to add the method :

@RequestMapping(value = "/doj/spring", method = RequestMethod.POST)
 @ResponseBody
 public String postDOJSpringCourse(){
  return "Post DOJ Course for Spring";
 }

POST http://localhost:8080/SpringApp/doj/spring
Content-Type: application/json

-- response --
200 OK
Server: Apache-Coyote/1.1
Content-Type: text/html
Content-Length: 26
Date: Fri, 18 Mar 2016 10:38:22 GMT

Post DOJ Course for Spring

2. RequestMapping with HTTP Headers

2.1. @RequestMapping with the headers attribute

The mapping can be narrowed even further by specifying a header for the request:

@RequestMapping(value = "/doj/spring", headers = "key=val")
 @ResponseBody
 public String getDOJSpringCourseWithHeaders(){
  return "Get DOJ Course for Spring with headers";
 }

And even multiple headers via the header attribute of @RequestMapping:

@RequestMapping(value = "/doj/spring", headers = {"key1=val1", "key2=val2"})
 @ResponseBody
 public String getDOJSpringCourseWithHeaders(){
  return "Get DOJ Course for Spring with headers";
 }

2.2. @RequestMapping Consumes and Produces

Mapping media types produced by a controller method is worth special attention – we can map a request based on its Accept header via the @RequestMapping headers attribute introduced above:

@RequestMapping(value = "/doj/spring", headers = "Accept=application/json")
 @ResponseBody
 public String getDOJSpringCourseJSON(){
  return "Get DOJ Course for Spring as JSON";
 }

GET http://localhost:8080/SpringApp/doj/spring
key: value

-- response --
200 OK
Server: Apache-Coyote/1.1
Content-Type: application/json
Content-Length: 33
Date: Fri, 18 Mar 2016 10:57:03 GMT

Get DOJ Course for Spring as JSON

@RequestMapping annotation now has a produces and a consumes attributes, specifically for this purpose:

@RequestMapping(value = "/doj/spring", method = RequestMethod.GET, produces = "application/json")
 @ResponseBody
 public String getDOJSpringCourseJSONFromREST(){
  return "Get DOJ Course for Spring as JSON from REST";
 }

GET http://localhost:8080/SpringApp/doj/spring
key: value

-- response --
200 OK
Server: Apache-Coyote/1.1
Content-Type: application/json
Content-Length: 43
Date: Fri, 18 Mar 2016 11:00:28 GMT

Get DOJ Course for Spring as JSON from REST

Additionally, produces support multiple values as well:
@RequestMapping(value = "/doj/spring", produces = { "application/json", "application/xml" })

A final note on the new produces and consumes mechanism – these behave differently from most other annotations: when specified at type level, the method level annotations do not complement but override the type level information.

3. RequestMapping with Path Variables

Parts of the mapping URI can be bound to variables via the @PathVariable annotation.

3.1. Single @PathVariable

@RequestMapping(value = "/doj/spring/{id}")
 @ResponseBody
 public String getDOJCourseWithPathVariable(@PathVariable("id") int id) {
    return "Get a DOJ Course with id=" + id;
 }

GET http://localhost:8080/SpringApp/doj/spring/2000

-- response --
200 OK
Server: Apache-Coyote/1.1
Content-Type: text/html
Content-Length: 29
Date: Fri, 18 Mar 2016 11:11:40 GMT

Get a DOJ Course with id=2000

If the name of the method argument matches the name of the path variable exactly, then this can be simplified by using @PathVariable with no value:

@RequestMapping(value = "/doj/spring/{id}")
 @ResponseBody
 public String getDOJCourseWithPathVariable(@PathVariable int id) {
    return "Get a DOJ Course with id=" + id;
 }

3.2. Multiple @PathVariable

More complex URI may need to map multiple parts of the URI to multiple values:

@RequestMapping(value = "/doj/{course}/{id}")
 @ResponseBody
 public String getDOJCourseWithPathVariable(@PathVariable("course") String course ,@PathVariable("id") long id) {
    return "Get a DOJ Course with id=" + id+" course name ="+course;
 }

GET http://localhost:8080/SpringApp/doj/spring/2000

-- response --
200 OK
Server: Apache-Coyote/1.1
Content-Type: text/html
Content-Length: 49
Date: Fri, 18 Mar 2016 11:16:19 GMT

Get a DOJ Course with id=2000 course name =spring

3.3. @PathVariable with RegEx

Regular expressions can also be used when mapping the @PathVariable; for example, we will restrict the mapping to only accept numerical values for the id:

@RequestMapping(value = "/doj/{course}/{numericId:[\\d]+")
 @ResponseBody
 public String getDOJCourseWithPathVariable(@PathVariable("course") String course ,@PathVariable("id") long id) {
    return "Get a DOJ Course with id=" + id+" course name ="+course;
 }

This will mean that the following URIs will match:
http://localhost:8080/SpringApp/doj/spring/2000

But this will not:
http://localhost:8080/SpringApp/doj/spring/xyz

4. RequestMapping with Request Parameters

@RequestMapping allows easy mapping of URL parameters with the @RequestParam annotation.

We are now mapping a request to an URI such as:

@RequestMapping(value = "/doj/spring")
 @ResponseBody
 public String getDOJCourseByRequestParam(@RequestParam("id") long id) {
     return "Get a DOJ Course with id=" + id;
 }

We are then extracting the value of the id parameter using the @RequestParam(“id”) annotation in the controller method signature.

GET http://localhost:8080/SpringApp/doj/spring?id=2000

-- response --
200 OK
Server: Apache-Coyote/1.1
Content-Type: text/html
Content-Length: 29
Date: Fri, 18 Mar 2016 11:29:25 GMT

Get a DOJ Course with id=2000

@RequestMapping can optionally define the parameters – as yet another way of narrowing the request mapping:

@RequestMapping(value = "/doj/spring", params = "id")
 @ResponseBody
 public String getDOJCourseByRequestParam(@RequestParam("id") long id) {
     return "Get a DOJ Course with id=" + id;
 }


Even more flexible mappings are allowed – multiple params values can be defined, and not all of them have to be used:

@RequestMapping(value = "/doj/spring", params = {"id","course"})
 @ResponseBody
 public String getDOJCourseByRequestParam(@RequestParam("id") long id, @RequestParam("course") String course) {
     return "Get a DOJ Course with id=" + id+" Course="+course;
 }

5. RequestMapping Corner Cases

5.1. @RequestMapping – multiple paths mapped to the same controller method

Although a single @RequestMapping path value is usually used for a single controller method, this is just good practice, not a hard and fast rule – there are some cases where mapping multiple requests to the same method may be necessary. For that case, the value attribute of @RequestMapping does accept multiple mappings, not just a single one:

@RequestMapping(value = {"/doj/spring/index", "/doj/spring/home"})
 @ResponseBody
 public String getDOJHome() {
     return "Get a DOJ Home Page";
 }

5.2. @RequestMapping – multiple HTTP request methods to the same controller method

Multiple requests using different HTTP verbs can be mapped to the same controller method:

@RequestMapping(value = {"/doj/spring/home"}, method = {RequestMethod.GET, RequestMethod.POST})
 @ResponseBody
 public String getDOJHome() {
     return "Get a DOJ Home Page";
 }
  

5.3. @RequestMapping – a fallback for all requests

To implement a simple fallback for all requests using a specific HTTP method:

@RequestMapping(value = {"*"})
 @ResponseBody
 public String getDOJDefaultPage() {
     return "Get a DOJ Default Page";
 }
  

@RequestMapping annotations at class level
In this case we are using @RequestMapping annotations at the class level. It is used for filter all incoming request at class level first before forwarding to handler methods. If the incoming request matches the pattern defined in controller class, then it search the controller methods mappings.
@Controller
@RequestMapping("/login/")
public class Login{

 @RequestMapping("doLogin")
 public ModelAndView doLogin(
   @RequestParam(value = "username") String username,
   @RequestParam(value = "password") String password) {
  //....
  //....
  return null;
 }
 
 @RequestMapping(value={"logout","signout"})
 public ModelAndView logout(
   @RequestParam(value = "username") String username) {
  //....
  //....
  
  return null;
 } 
}
  
Conclusion

This article focus on the @RequestMapping annotation in Spring – discussing a simple usecase, the mapping of HTTP headers, binding parts of the URI with @PathVariable and working with URI parameters and the @RequestParam annotation.



Exception Handling in Spring MVC Example and Return Custom 404 Error Pages

Exception Handling in Spring MVC is about handling exceptions in the application by using spring framework. Spring offers we can customized our error page to more friendly error page to user. This example provides the steps to write your own 404 Resource Not Found error page for your application. Here I am writing a custom exception for 404 error using the HttpStatus.NOT_FOUND. This will be annotated as the exception @ExceptionHandler in the controller. Whenever there is any error thrown on this type, it will be redirected to the configured error page.

Lets see the example.

1. Controller in Application

package com.doj.spring.web.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.doj.spring.web.bean.Student;
import com.doj.spring.web.exception.StudentNotFoundException;

@Controller
public class WebController {
 
 static Map<String, Student> map = new HashMap<String, Student>();
 @RequestMapping("/")
 public String home(){
  Student student = new Student();
  student.setFname("Dinesh");
  student.setLname("Rajput");
  student.setAge("29");
  student.setAddress("Noida");
  student.setCourse("MS");
  map.put("1000", student);
  return "home";
 }
 
 @RequestMapping("/doj-student-{rollNumber}")
 public String dojStudentByRollNumber(ModelMap model, @PathVariable(value="rollNumber") String rollNumber){
  Student student = map.get(rollNumber);
  if (student == null) {
   throw new StudentNotFoundException("Student Not Found", "ERROR:404");
  }
  String name = student.getFname()+" "+student.getLname()+" "+student.getAddress()+" "+student.getCourse();
  model.put("name", name);
  return "home";
 }
 
 @ExceptionHandler(StudentNotFoundException.class)
 public ModelAndView handleStudentNotFoundException(StudentNotFoundException ex) {
  Map<String, StudentNotFoundException> model = new HashMap<String, StudentNotFoundException>();
  model.put("exception", ex);
  return new ModelAndView("student.error.400", model);

 }
 
 @ExceptionHandler(Exception.class)
 public ModelAndView handleException(Exception ex) {
  Map<String, Exception> model = new HashMap<String, Exception>();
  model.put("exception", ex);
  return new ModelAndView("student.error.500", model);

 }
}



2. Add Custom Exception

package com.doj.spring.web.exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="Student Not Found")
public class StudentNotFoundException extends RuntimeException{

 /**
  * 
  */
 private static final long serialVersionUID = -2581975292273282583L;
 
 String errorMessage;
 
 String errorCode;

 public StudentNotFoundException(String errorMessage, String errorCode) {
  super();
  this.errorMessage = errorMessage;
  this.errorCode = errorCode;
 }

 public String getErrorMessage() {
  return errorMessage;
 }

 public void setErrorMessage(String errorMessage) {
  this.errorMessage = errorMessage;
 }

 public String getErrorCode() {
  return errorCode;
 }

 public void setErrorCode(String errorCode) {
  this.errorCode = errorCode;
 }
 
}


3. Student Bean Class

package com.doj.spring.web.bean;


public class Student {
 
 String fname;
 
 String lname;
 
 String address;
 
 String course;
 
 String age;
 
 public String getFname() {
  return fname;
 }
 public void setFname(String fname) {
  this.fname = fname;
 }
 public String getLname() {
  return lname;
 }
 public void setLname(String lname) {
  this.lname = lname;
 }
 public String getAddress() {
  return address;
 }
 public void setAddress(String address) {
  this.address = address;
 }
 public String getCourse() {
  return course;
 }
 public void setCourse(String course) {
  this.course = course;
 }
 public String getAge() {
  return age;
 }
 public void setAge(String age) {
  this.age = age;
 }
 
}

4. Views JSP
home.jsp

View for Success Page


<h1>${name} Welcome to DOJ Classes for Spring MVC!!!</h1>

Error Page View
400.jsp

<h1>${exception.errorCode}  -  ${exception.errorMessage} !!!</h1>

mainTemplate.jsp
<!DOCTYPE h1 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
<html>
 <head>
  <title><tiles:insertAttribute name="title"/></title>
  <style>
      .error {
          color: red; font-weight: bold;
      }
  </style>
 </head>
 <body style="text-align: center;">
  <div id="header" style="height: 10%;background-color: gray;"><tiles:insertAttribute name="header"/></div>
  <div id="body" style="height: 70%; background-color: aqua;padding-top: 40px;"><tiles:insertAttribute name="body"/></div>
  <div id="footer" style="height: 10%;background-color: gray;"><tiles:insertAttribute name="footer"/></div>
 </body>
</html>

5. Spring Configurations based on Java Configuration


package com.doj.spring.web.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.tiles3.TilesConfigurer;
import org.springframework.web.servlet.view.tiles3.TilesViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages={"com.doj.spring.web.controller"})
public class SpringWebConfiguration extends WebMvcConfigurerAdapter{

 @Bean
 public ViewResolver viewResolver() {
  return new TilesViewResolver();
 }
 
 @Bean
 public TilesConfigurer tilesConfigurer() {
  TilesConfigurer tiles = new TilesConfigurer();
  tiles.setDefinitions(new String[] {
    "/WEB-INF/view/tiles/tiles-def.xml"
  });
  tiles.setCheckRefresh(true);
  return tiles;
 }
 
 //Configure for default static content handling
 @Override
 public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
  configurer.enable();
 }
}



6. Deployment Descriptor based on java configuration

package com.doj.spring.web;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import com.doj.spring.web.config.SpringWebConfiguration;

//this file is equivalent to web.xml
public class WebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{

 //Configuration for non web components like services, daos, repos, etc.
 @Override
 protected Class<?>[] getRootConfigClasses() {
  return null;
 }
 
 //Specifying Spring MVC configuration class "SpringWebConfiguration.class" it equivalent to *-servlet.xml file
 @Override
 protected Class<?>[] getServletConfigClasses() {
  return new Class<?>[]{SpringWebConfiguration.class};
 }

 //Mapping dispatcher server to "/" i.e. Servlet Mapping in the web.xml 
 @Override
 protected String[] getServletMappings() {
  return new String[]{"/"};
 }
}


All files related this example is not mention here for whole application you can download the zip of working application.

SpringMVCExceptionHandlingExample



7. Lets see demo this application

1. Welcome Page

http://localhost:8080/SpringMVCExceptionHandlingExample/


Exception Handling in Spring MVC


2. Error Page

http://localhost:8080/SpringMVCExceptionHandlingExample/doj-student-10001


Exception Handling in Spring MVC Example and Return Custom 404 Error Pages




Difference between "git add -A" and "git add ." & "git add -u"

Millions of developers use GitHub to build personal projects, support their businesses, and work together on open source technologies. Git is very popular repository server. There are lots of command for git lets see difference between git add -A, git add . and git add -u .

According to git version 1.x

"git add -A" is equivalent to "git add ." and "git add -u"

  • git add -A stages All
  • git add . stages new and modified, without deleted
  • git add -u stages modified and deleted, without new

The important point about git add . is that it looks at the working tree and adds all those paths to the staged changes if they are either changed or are new and not ignored, it does not stage any 'rm' actions.

git add -u looks at all the already tracked files and stages the changes to those files if they are different or if they have been removed. It does not add any new files, it only stages changes to already tracked files.

git add -A is a handy shortcut for doing both.

  • git add -A is equivalent to git add --all
  • git add -u is equivalent to git add --update

According to git version 2.x
  • git add -A stages All
  • git add . stages All in same path
  • git add -u stages modified and deleted, without new

There is no more difference in 2.0. git add . equals to git add -A for the same path, the only difference is if there are new files in other paths of the tree.

With Git 2.0, git add -A is default: git add . equals git add -A .





Exception Handling in Spring MVC with Example

Whenever we work with spring mvc then we assume that everything will always work in the our web application. But what if something goes wrong? What if, while handling a request, an exception is thrown? What response will be sent to the client when thing go awry? 

No matter what happens, good or bad, the outcome of a servlet request is a servlet response. If an exception occurs during request processing, the outcome is still a servlet response. Somehow, the exception must be translated into a response.


Spring Offers multiple default exception handling status codes and ways to translate exceptions to responses.

  • Certain Spring exceptions are automatically mapped to specific HTTP status codes.
  • An exception can be annotated with @ResponseStatus to map it to an HTTP status code.
  • A method can be annotated with @ExceptionHandler to handle the exception.
Default Http Status Code Mapping with Exceptions

404--->Not Found-->NoSuchRequestHandlingMethodException etc.
400--->Bad Request-->BindException, HttpMessageNotReadableException etc.
406--->Not Acceptable-->HttpMediaTypeNotAcceptableException
415--->Unsuppported Media Type-->HttpMediaTypeNotSupportedException
405--->Method Not Allowed-->HttpRequestMethodNotSupportedException
500--->Internal Server Error-->HttpMessageNotWritableException

These above are usually thrown by Spring framework itself as the result of something went wrong in DispatcherServlet and failed any validations. For Example you want access any method in the controller which not mapped with any request then DispatcherServet through NoSuchRequestHandlingMethodException means 404 so resulting in a response with a status code of 404 (Not Found).

In Case of Custom Exception and Error Pages

1.  Mapping Exception to HTTP Status Code

So above handling provided by spring is helpful but not more useful whenever we are taking about Custom Exception  or Custom Error Pages so in this case we have to do something more better but don't worry Spring offers a way to map exceptions to HTTP status codes via the @ResponseStatus annotation.

Suppose we are working with an application about Student Management for that we have an student controller with mapping to find student record from StudentRepository as follows
.
@Controller
public class StudentController {
  @RequestMapping("/doj-student-{rollNumber}")
  public String dojStudentByRollNumber(ModelMap model, @PathVariable(value="rollNumber") String rollNumber){
   Student student = StudentRepository.findStudentByRollNumber(rollNumber);
   String name = student.getFname()+" "+student.getLname()+" "+student.getAddress()+" "+student.getCourse();
   model.put("name", name);
   return "home";
  }

}
As see in the above code when we are passing rollNumber to find a student from StudentRepository if for any rollNumber we got student then everything is fine in the application user get student detail as response. What happens when StudentRepository return null value for any rollNumber in this case user may got Internal Server Error i.e. 500 status code error.


For handling this scenario we have our custom exception StudentNotFoundException as follows.

package com.doj.spring.web.exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="Student Not Found")
public class StudentNotFoundException extends RuntimeException{

 /**
  * 
  */
 private static final long serialVersionUID = -2581975292273282583L;

}

Here, a Student is retrieved by its rollNumber from the StudentRepository. If findStudentByRollNumber() returns a Student object, that Student is put into the model, and the view whose name is student is tasked with rendering it in the response. But if findStudentByRollNumber() returns null, then a StudentNotFoundException is thrown. For now, StudentController with StudentNotFoundException looks like this:

@Controller
public class StudentController {
  @RequestMapping("/doj-student-{rollNumber}")
  public String dojStudentByRollNumber(ModelMap model, @PathVariable(value="rollNumber") String rollNumber){
   Student student = StudentRepository.findStudentByRollNumber(rollNumber);
    if (student == null) {
 throw new StudentNotFoundException();
   } 
   String name = student.getFname()+" "+student.getLname()+" "+student.getAddress()+" "+student.getCourse();
   model.put("name", name);
   return "home";
  }

}

After introducing this @ResponseStatus annotation, if a StudentNotFoundException were to be thrown from a controller method, the response would have a status code of 404 and a reason of Student Not Found.

2.  ExceptionHandling methods

Mapping exceptions to status codes is simple and sufficient for many cases. But what if you want the response to carry more than just a status code that represents the error that occurred? Rather than treat the exception generically as some HTTP error, maybe you’d like to handle the exception the same way you might handle the request itself.
@Controller
public class StudentController {
  @RequestMapping("/doj-student-{rollNumber}")
  public String dojStudentByRollNumber(ModelMap model, @PathVariable(value="rollNumber") String rollNumber){
   Student student = StudentRepository.findStudentByRollNumber(rollNumber);
    if (student == null) {
 throw new StudentNotFoundException();
   } 
   String name = student.getFname()+" "+student.getLname()+" "+student.getAddress()+" "+student.getCourse();
   model.put("name", name);
   return "home";
  }


    @ExceptionHandler(StudentNotFoundException.class)
    public ModelAndView handleStudentNotFoundException(StudentNotFoundException ex) {
  Map<String, String> model = new HashMap<String, String>();
  model.put("exception", ex.toString());
  return new ModelAndView("student.error", model);

 }
}

The @ExceptionHandler annotation has been applied to the handleStudentNotFoundException() method, designating it as the go-to method when a StudentNotFoundException is thrown. It returns a ModelAndView object, which, just as with the request-handling method, specifies with the logical name of the view to render, telling the user that student not found for this rollNumber.

If @ExceptionHandler methods can handle exceptions thrown from any handler method in the same controller class, you might be wondering if there’s a way they can handle exceptions thrown from handler methods in any controller.




java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

When we deploy a Spring MVC application into Tomcat and Servlet container not able to found this class org.springframework.web.servlet.DispatcherServlet then an Exception java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet error comes which usually found in the spring-webmvc.jar file.
The DispatcherServlet is the core of Spring MVC framework, In Spring’s web MVC framework the mechanism of dispatching the request to the appropriate controllers is achieved by configuring the DispatcherServlet class. DispatcherServlet is the class which manages the entire request handling process.Like a normal servlet DispatcherServlet also needs to be configured in the web deployement Descriptor(web.xml) and specify the URL pattern such that Servlet container like Tomcat should send all HTTP request to DispatcherServlet. We also set load-on-startup tag as 1 for this Servlet, so that it should be loaded at deployment time. This Servlet is the link between Servlet Container and Spring MVC framework.
DispatcherServlet in the deployment descriptor (web.xml)

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>   
</web-app>

Reason of java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

When we deploy a Java web application which uses Spring MVC into a web server like Tomcat, it reads the deployment descriptor (web.xml file) and starts looking for org.springframework.web.servlet.DispatcherServlet in its classpath. As per Java EE specification, all application dependency JARs must be in WEB-INF/lib directory, so if doesn't find the JAR there it will throw the java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet.

Error stacktrace of this issue like:

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:532)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:514)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:142)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1144)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5176)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5460)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:663)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1642)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)

Solution for java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

Solution 1- You did not include spring-beans and spring-context jars in your lib. If you are using maven (which will help a lot) those two lines will be enough

<dependency>
 <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
   <version>4.1.0.RELEASE</version>
</dependency>
<dependency>
 <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
   <version>4.1.0.RELEASE</version>
</dependency>

Solution 2- The necessary jars are in your classpath but are not deployed on tomcat.

  • spring-beans - 4.1.0.RELEASE
  • spring-webmvc - 4.1.0.RELEASE
  • spring - 4.1.0.RELEASE



java.lang.ClassNotFoundException : javax.servlet.jsp.jstl.core.Config

While deploying a web application of spring mvc with maven and jsp on tomcat 7.0. If you got a following problem.

Problem-
java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
at org.apache.myfaces.view.jsp.JspViewDeclarationLanguage.buildView(JspViewDeclarationLanguage.java:91)
at org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:78)
at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:241)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:199)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)


Solution-

Solution for this problem is following-

The error is telling you it cannot find the class because it is not available in your application.
By default, Tomcat container doesn’t contain any jstl library. To fix it, declares jstl.jar in your Maven pom.xml file.

1. If you are using Maven, make sure you have the dependency for jstl artifact:


<dependency>
 <groupId>javax.servlet</groupId>
 <artifactId>jstl</artifactId>
 <version>1.2</version>
  </dependency>

2. If you were using Gradle, you could write in a build.gradle:

dependencies {
    compile 'javax.servlet:jstl:1.2'
}


3. And if you are not using maven or gradle, just make sure you include the JAR in your classpath.
You need to add at least the following jar files in your WEB-INF/lib directory:

  • jsf-impl.jar
  • jsf-api.jar
  • jstl.jar
You can download JSTL 1.1 here and JSTL 1.2 here.