Author Archives: mathanlalsait

Java concurrency and executors framework example

Executors framework

Threads that comes with low level API from Thread class are available from the beginning of Java language, that is not suitable or ready to use directly in large applications that need a huge number of parallel or concurrent process.

Executors APIs are adequate for massively concurrent applications that fully exploit today’s multiprocessor and multi-core systems. And provides you the Highlevel API to manage threads creations and execution.

Executors class

Executors class provides you the factory and utility methods for below interface

  • Executor
  • ExecutorService
  • ScheduledExecutorService
  • ThreadFactory
  • Callable

Some of the utility methods are

  • callable
  • defaultThreadFactory
  • newCachedThreadPool
  • newFixedThreadPool
  • newSingleThreadExecutor
  • newSingleThreadScheduledExecutor
  • newScheduledThreadPool

 

Executor Interface

The Executor interface provides a single method execute() as a drop in replacement of old thread creation methods

Example assume we have a runnable object,

Runnable r=new MyTask();

new Thread(r).start();

We can replace the thread creation with

e.execute(r);

execute method will do the same work as we do with lowlevel API(new Thread(r).start()), but differs in thread creation and managing it based on its implementation.

ExecutorService Interface

ExecutorService interface extends the Executor Interface and provides more methods like

  • execute
  • submit
  • shutdownNow
  • shutdown
  • isTerminated
  • isShutdown
  • invokeAny
  • invokeAll
  • awaitTermination

ScheduledExecutorService interface

ScheduledExecutorService interface extends ExecutorService, An ScheduledExecutorService that can schedule commands to run after a given delay or to execute periodically. ScheduledExecutorService provides you some extra functionality like

  • schedule
  • scheduleAtFixedRate
  • scheduleWithFixedDelay

ThreadFactory Interface

An object that creates new threads on demand. Using thread factories removes hardwiring of calls to new Thread, enabling applications to use special thread subclasses, priorities, etc.

Callable Interface

The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread.

A callable task can return a result and may throw an exception. Implementors define a single method with no arguments called call.

A Runnable, however, does not return a result and cannot throw a checked exception.

Spring MVC Interview Questions | Spring Rest Interview Questions

Here some Frequently asked Spring MVC interview questions and Spring REST interview questions for Java developers applying for web developer roles. While Spring Framework is the most popular and ideal framework in developing web based Java applications and RESTful web services, good knowledge of spring rest and spring MVC is expected from any senior Java developer.

These Spring MVC interview questions for experienced developers also Spring rest interview questions for experienced developers are formed from the updated requirement of  organization’s.

1. What is Spring MVC?

  • Spring Web MVC framework built based on Servlet API Which is merged into Spring Framework
  • “Spring Web MVC,” comes from the name of its source module (spring-web MVC), but it is formally known as “Spring MVC”
  • The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale, and theme resolution as well as support for uploading files.
  • The default handler is based on the @Controller and @RequestMapping annotations, offering a wide range of flexible handling methods

2. Explain the role of DispatcherServlet in spring MVC?

  • DispatcherServlet acts as a front controller for Spring based web applications. It provides a mechanism for request processing where actual work is performed by configurable, delegate components. It is inherited from javax.servlet.http.HttpServlet, it is typically configured in the web.xml file.
  • A web application can define any number of DispatcherServlet instances. Each servlet will operate in its own namespace, loading its own application context with mappings, handlers, etc. Only the root application context as loaded by ContextLoaderListener, if any, will be shared. In most cases, applications have only single DispatcherServlet with the context-root URL(/), that is, all requests coming to that domain will be handled by it.
  • By Spring configuration classes, DispatcherServlet discovers the delegate components it needs for request mapping, view resolution, exception handling etc.

3. What is HandlerMapping?

  • The functionality a basic HandlerMapping provides is the delivering of a HandlerExecutionChain, which must contain the handler that matches the incoming request, and may also contain a list of handler interceptors that are applied to the request.
  • While Request comes in, the DispatcherServlet will hand it over to the handler mapping to let it inspect the request and come up with an appropriate HandlerExecutionChain. Then the DispatcherServlet will execute the handler and interceptors in the chain (if any).
  • Mapping request with handler along the list of interceptors for pre and post processing. Based on varies criteria mapping has enabled where the details of criteria varied by HandlerMapping implementation.

4. What is ViewResolver?

  • For Resolve, logical String-based view names, which is returned from a handler to an actual View, for rendering the response. Interface to be implemented by objects that can resolve views by name.
  • Views in Spring are addressed by a view name and are resolved by a view resolver.

5. What is WebApplicationInitializer?

  • Interface to be implemented in Servlet 3.0+ environments in order to configure the ServletContext programmatically — as opposed to (or possibly in conjunction with) the traditional web.xml-based approach.
  • Implementations of this SPI will be detected automatically by SpringServletContainerInitializer, which itself is bootstrapped automatically by any Servlet 3.0 container

6. What is the use of AbstractAnnotationConfigDispatcherServletInitializer?

WebApplicationInitializer to register a DispatcherServlet and use Java-based Spring configuration.

Here some Implementations are required to implement:

  • getRootConfigClasses() — for “root” application context (non-web infrastructure) configuration.
  • getServletConfigClasses() — for DispatcherServlet application context (Spring MVC infrastructure) configuration.
  • If an application context hierarchy is not required, applications may return all configuration via getRootConfigClasses() and return null from getServletConfigClasses().

7. What is the use of AbstractDispatcherServletInitializer?

Base class for WebApplicationInitializer implementations that register a DispatcherServlet in the servlet context. Most applications should consider extending the Spring Java config subclass Abstract Annotation Config Dispatcher Servlet Initializer.

8.Use of @Controller annotation?

This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning. It is typically used in combination with annotated handler methods based on the RequestMapping annotation.

9.Use of @RequestMapping annotation?

  • Annotation for mapping web requests onto methods in request handling classes with flexible method signatures.
  • Both Spring MVC and Spring WebFlux support this annotation through a RequestMappingHandlerMapping and RequestMappingHandlerAdapter in their respective modules and package structure. For the exact list of supported handler method arguments and return types in each, please use the reference documentation links below:
  • Spring MVC Method Arguments and Return Values, Spring WebFlux Method Arguments and Return Values
  • @RequestMapping(value = “/something”, headers = “content-type=text/*”)

10.Difference between @RequestMapping vs @GetMapping?

  • RequestMapping can be used at class level:

This annotation can be used both at the class and at the method level. In most cases, at the method level applications will prefer to use one of the HTTP method specific variants @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, or @PatchMapping.

  • while GetMapping only applies to the method:

Annotation for mapping HTTP GET requests onto specific handler methods.

11.Use of @ComponentScan(“”) annotation?

  • Configures component scanning directives for use with @Configuration classes.
  • Provides support parallel with Spring XML’s <context:component-scan> element.
  • Either basePackageClasses() or basePackages() (or its alias value()) may be specified to define specific packages to scan.
  • If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.

12.Use of @RestController?

@RestController annotation, which marks the class as a controller where every method returns a domain object instead of a view. It’s shorthand for @Controller and @ResponseBody rolled together.

13. How do you declare request and response Media Types in spring MVC

@RequestMapping(method=RequestMethod.GET, value="/fooBar")

public ResponseEntity<String> fooBar2() {

    String json = "jsonResponse";

    HttpHeaders responseHeaders = new HttpHeaders();

    responseHeaders.setContentType(MediaType.APPLICATION_JSON);

    return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);

}

14. What is CORS?

Cross-Origin Resource Sharing (CORS) is a specification that enables truly open access across domain-boundaries. If you serve public content, please consider using CORS to open it up for universal JavaScript/browser access.

15. What is RestTemplate?

  • Synchronous client to perform HTTP requests, exposing a simple, template method API over underlying HTTP client libraries such as the JDK HttpURLConnection, Apache HttpComponents, and others.
  • The RestTemplate offers templates for common scenarios by HTTP method, in addition to the generalized exchange and execute methods that support of less frequent cases.

16. How do you handle the exception in Spring MVC?

  • In Spring MVC, unexpected exceptions might be thrown during execution of its controllers. Spring provides two approaches for handling these exceptions:
  • Using XML configuration: this is similar to exception handling in Servlet/JSP, by declaring a SimpleMappingExceptionResolverbean in Spring’s application context file and map exception types with view names. This approach applies to all controllers in the application.
  • Using the exception handler method: Spring provides the @ExceptionHandler annotation type which is used to annotate a method to handle exceptions raised by the controller’s methods. This approach applies to only the controller in which the handler method is declared.

17. How do you handle container errors in spring MVC?

For access to errors from validation and data binding for a command object (@ModelAttribute argument) or errors from the validation of a @RequestBody else @RequestPart arguments, You must declare an Errors or BindingResult argument immediately after the validated method argument.

18. What is @ResponseBody annotation?

  • Annotation that indicates a method return value should be bound to the web response body. Supported for annotated handler methods.
  • As of version 4.0, this annotation can also be added on the type level in which case it is inherited and does not need to be added on the method level.

19.Use of @RequestParam, @RequestHeader, @PathVariable, @MatrixVariable, and @CookieValue?

@RequestParam

  • Annotation which indicates that a method parameter should be bound to a web request parameter.Supported for annotated handler methods in Spring MVC and Spring WebFlux as follows:
  • In Spring MVC, “request parameters” map to query parameters, form data, and parts in multipart requests. This is because the Servlet API combines query parameters and form data into a single map called “parameters”, and that includes automatic parsing of the request body.
  • In Spring WebFlux, “request parameters” map to query parameters only. To work with all 3, query, form data, and multipart data, you can use data binding to a command object annotated with ModelAttribute.
  • If the method parameter type is Map and a request parameter name is specified, then the request parameter value is converted to a Map assuming an appropriate conversion strategy is available.
  • If the method parameter is Map<String, String> or MultiValueMap<String, String> and a parameter name is not specified, then the map parameter is populated with all request parameter names and values.

@PathVariable

  • Annotation which indicates that a method parameter should be bound to a URI template variable. Supported for RequestMapping annotated handler methods.
  • If the method parameter is Map<String, String> then the map is populated with all path variable names and values.

@MatrixVariable

  • Annotation which indicates that a method parameter should be bound to a name-value pair within a path segment. Supported for RequestMapping annotated handler methods.
  • If the method parameter type is Map and a matrix variable name is specified, then the matrix variable value is converted to a Map assuming an appropriate conversion strategy is available.
  • If the method parameter is Map<String, String> or MultiValueMap<String, String> and a variable name is not specified, then the map is populated with all matrix variable names and values.

@CookieValue

  • Annotation which indicates that a method parameter should be bound to an HTTP cookie.
  • The method parameter may be declared as type Cookie or as a cookie value type (String, int, etc.).

20.Use of @RequestBody?

Annotation that indicates a method return value should be bound to the web response body. Supported for annotated handler methods.

21.Use of @InitBinder?

The value in @InitBinder is the names of command/form attributes and/or request parameters that this init-binder method is supposed to apply to. The default is to apply to all command/form attributes and all request parameters processed by the annotated handler class. Specifying model attribute names or request parameter names here restricts the init-binder method to those specific attributes/parameters, with different init-binder methods typically applying to different groups of attributes or parameters.

22. What is DataBinder?

Binder that allows for setting property values onto a target object, including support for validation and binding result analysis. The binding process can be customized through specifying allowed fields, required fields, custom editors, etc.

23. What is ResponseBodyEmitter?

  • A controller method return value type for asynchronous request processing where one or more objects are written to the response.
  • While DeferredResult is used to produce a single result, a ResponseBodyEmitter can be used to send multiple objects where each object is written with a compatible HttpMessageConverter.
  • Supported as a return type on its own as well as within a ResponseEntity.

24. What is DeferredResult and Callable?

  • DeferredResult provides an alternative to using a Callable for asynchronous request processing. While a Callable is executed concurrently on behalf of the application, with a DeferredResult the application can produce the result from a thread of its choice.
  • Subclasses can extend this class to easily associate additional data or behavior with the DeferredResult. For example, one might want to associate the user used to create the DeferredResult by extending the class and adding an additional property for the user.
  • In this way, the user could easily be accessed later without the need to use a data structure to do the mapping

25. What is WebClient?

Non-blocking, reactive client to perform HTTP requests, exposing a fluent, reactive API over underlying HTTP client libraries such as Reactor Netty.

26. How do you redirect a page using Spring MVC?

  • Prefix in a view name lets you perform a redirect. The UrlBasedViewResolver and its subclasses recognize this as an instruction that a redirect is needed. The rest of the view name is the redirect URL.
  • The net effect is the same as if the controller had returned a RedirectView, but now the controller itself can operate in terms of logical view names.
  • A logical view name such as redirect:/myapp/some/resource, redirects relative to the current Servlet context, while a name such as a redirect: http://myhost.com/some/arbitrary/ path redirects to an absolute URL.
  @RequestMapping(value = "/redirect", method = RequestMethod.GET)

        public String redirect() {

            return "redirect:finalPage";

        }

    @RequestMapping(value = "/finalPage", method = RequestMethod.GET)

        public String finalPage() {

            return "final";

        }

 

27. How do you forward a request to another page using Spring MVC?

@RequestMapping("/myController/test")

public String myMethod(@RequestParam("reqParam") String reqParamValue) {

 return "forward:/someOtherUrl?reqParam="+reqParamValue; 

 //forward request to another controller with the param and value

}

or

@RequestMapping("/myController/test")

public String myMethod(@RequestParam("reqParam") String reqParamValue,

HttpServletRequest request) {

request.setAttribute("reqParam", reqParamValue);

return "forward:/someOtherUrl"; 

}

28. How do you handle FileUpload using Spring MVC?

 @RequestMapping(method = RequestMethod.POST)

     public String fileUploaded(Model model, @Validated File file,

             BindingResult result) {
  String returnVal = "successFile";

  if (result.hasErrors()) {

   returnVal = "file";

  } else {           

   MultipartFile multipartFile = file.getFile();

  }

  return returnVal;

 }

Java servlet tutorial and example

Introduction to Java Servlet tutorial

For providing a dynamic response to the user’s request. Java servlet code (server-side code) running on the web server to make a response to more dynamics. Users passing request message via the server, and the server returns a response message as illustrated.

What is Servlet and difference between JSP and Servlet?

Servlet hello world example

Servlet form data example

Servlet life cycle example

doGet vs doPost – Soon

Servlet Redirect example

Request dispatcher forward and include

Servlet Session management – Soon

Servlet Cookies

Url Rewriting

Hidden form fields

Servlet HttpSession

Servlet Filter

Servlet Listener

load-on-startup in Servlet

More Examples:

Cookie login and logout session

Servlet File download

Servlet File Upload

HttpSession Login and logout

Login page with MySQL database

Simple registration form example

Registration form in JSP with database connectivity

Simple login example using Servlet and JSP

Java pogram to Swapping of two numbers using third variable

Following swapping example program in java for swapping two unique number values with temporary variables. Here is a java program for how swapping happened.

base3.java


public class Base3
{
public static void main(String[] args)
   {
	int a=10;
	int b=20;
	int temp;
	temp=a;
	a=b;
	b=temp;
	System.out.println("After Swapping the value of a is : "+a);
	System.out.println("After Swapping the value of b is : "+b);
	
   }
}

Output:

After Swapping value of a is : 20

After Swapping value of b is : 10

Java program to check the given number is binary or not

Binary number system relied on base number 2 in the number system. In general, the base-2  system is a positional notation with a radix of 2. Consists of 0 and 1 both digit is referred to as a bit. Based on boolean output values here is a Java program for checking binary numbers.

base13.java

public class Base13 
{
	public boolean isBinaryNumber(int binary)
	{
		boolean status = true;
		while(true) 
		{
			if(binary == 0) 
			{
				break;
			}
			else 
			{
				int tmp = binary%10;
				if(tmp > 1) 
				{
					status = false;
					break;
				}
				binary = binary/10;
			}
		}
		return status;
	}
	public static void main(String a[]) 
	{
		Base13 mbc = new Base13();
		System.out.println("Is 1000 binary? :"+mbc.isBinaryNumber(1000));
		System.out.println("Is 1030 binary? :"+mbc.isBinaryNumber(1030));
	}
}

Output:


Is 1000 binary? :true
Is 1030 binary? :false

Java Program to Convert Binary number to Decimal number

In general, Number systems can be convertible. Following Simple java program will demonstrate how to convert the Binary number system into a Decimal number system.

base12.java

public class Base12 
{
	public static int getDecimal(int binary)
	{  
	    int decimal = 0;  
	    int n = 0;  
	    while(true){  
	      if(binary == 0)
	      {  
	        break;  
	      }
	      else 
	      {  
	          int temp = binary%10;  
	          decimal += temp*Math.pow(2, n);  
	          binary = binary/10;  
	          n++;  
	       }  
	    }  
	    return decimal;  
	}  
	
	public static void main(String args[])
	{    
	System.out.println("Decimal of 111 is: "+getDecimal(111));  
	 
	}
}

Output:

Decimal of 111 is: 7