Spring MVC MCQs

Spring MVC MCQs

These Spring MVC multiple-choice questions and their answers will help you strengthen your grip on the subject of Spring MVC. You can prepare for an upcoming exam or job interview with these 70+ Spring MVC MCQs.
So scroll down and start answering.

1:

In an annotation-based Spring MVC controller, which of the following are valid ways to set cache headers for a specific path?

A.  

Ensuring the instance of "AnnotationMethodHandlerAdapter" does not have the "cacheSeconds" property set, and adding an instance of "WebContentInterceptor".


B.  

Adding "final HttpServletResponse response" as a parameter, then setting the header "Cache-Control" to "all-cache".


C.  

Using a Handler Interceptor and using the "postHandle" method provided by it.


D.  

Cache headers cannot be set for a specific path.


2: Which of the following code samples will get the ServletContext inside an Interceptor?

A.   @Autowired ServletContext context;

B.   request.getSession().getServletContext();

C.   setServletContext(ServletContext context) { this.context = context; }

D.   request.getSession().getServletContext();

3:

Which of the following are valid sets of constructor arguments for the ModelAndView class? (Select all correct answers.)

A.  

String viewName


B.  

String viewName, Map<String,?> model


C.  

String modelName, Map<String,?> model


D.  

View view, Map<String,?> model, Object modelObject


4: Which of the following are possible validation methods for user input in Spring MVC?

A.   XPath validation

B.   Annotation validation

C.   Programmatic validation

D.   Mixed annotation and programmatic validation

5: Which of the following dependency injection (DI) methodologies are available in Spring MVC?

A.   Constructor-based dependency injection

B.   Setter-based dependency injection

C.   Prototype-based dependency injection

D.   Manual dependency injection

6: Which of the following interfaces can be implemented to interact with a container's management of the bean lifecycle?

A.   InitializingBean

B.   IntializeableBean

C.   DisposableBean

D.   DisposingBean

7: Select all authentication methods that are supported by Spring Security by default:

A.   Basic Authentication

B.   Digest Access Authentication

C.   Remember-me Authentication

D.   Multi-factor authentication

8:

Which of the following statements is false?

A.  

Spring MVC provides both declarative and programmatic transaction management.


B.  

The transaction-manager attribute in the transactional advice (<tx:advice/>) is required if the bean name of the PlatformTransactionManager that is being wired is transactionManager.


C.  

By default, a transaction is only marked for rollback in the case of runtime unchecked exceptions.


D.  

None of these.


9: Which of the following statements is true about the HandlerExceptionResolver class?

A.   Any Spring bean that implements HandlerExceptionResolver will be used to intercept and process any exception raised that was handled by a Controller.

B.   @ExceptionHandler methods can be injected with the model.

C.   DefaultHandlerExceptionResolver converts standard Spring exceptions and converts them to HTTP Status Codes.

D.   None of these.

10: Which of the following statements is true about method arguments that have an @ModelAttribute annotation?

A.   It indicates that the argument should be retrieved from the model.

B.   If the argument is not present in the model, it should be added to the model first, and then instantiated.

C.   If the argument is not present in the model, it should be instantiated first, and then added to the model.

D.   Model attributes have to be explicitly added when using @ModelAttribute.

11:

Given the following method:

@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);

    }

Which of the following statements is correct?

A.  

It allows access to request and response headers.


B.  

It doesn't allow access to request and response headers.


C.  

It returns a JSON String and sets the mimetype to text/plain.


D.  

It returns a JSON String and sets the mimetype to text/javascript.


12: Which of the following classes provides built-in pagination functionality in SpringMVC?

A.   PageListSorter

B.   PageListContext

C.   PagedListHolder

D.   Spring MVC doesn't include a built-in class for handling pagination.

13:

Given the method below:

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

public final String foo(HttpServletRequest request, BindingResult bindResult, ModelMap model) {

    model.addAttribute("abc", 123);

    return "foo";

}

When the view is displayed in the browser, it's URL is "http://mydomain/foo?abc=123".

Which of the following statements is true?

A.  

The attribute appears as string name-value pairs in the URL because the @ModelAttribute annotation is used in the controller.


B.  

Adding "model.asMap().clear();" will prevent the attribute name-value pair from appearing in the URL.


C.  

The attribute name-value pair will be included in the URL, regardless of the use of @ModelAttribute in the controller.


D.  

The attribute name-value pair cannot be excluded from being displayed in the URL.


14:

Which of the following is true about the use of <context:annotation-config /> in a servlet?

A.  

<context:annotation-config> activates many different annotations in beans, whether they are defined in XML or through component scanning.


B.  

<context:annotation-config> declares explicit support for annotation-driven MVC controllers.


C.  

<context:annotation-config> adds support for declarative validation via @Valid.


D.  

All statements are false.


15:

Fill in the blank:

The _______ enables the use of the bean element’s attributes, instead of nested <property/> elements, to describe property values and/or collaborating beans.

A.  

default namespace


B.  

c-namespace


C.  

p-namespace


D.  

namespace

16: Which of the following statements is true about the @RequestMapping annotation?

A.   It has a single String parameter.

B.   It has a String[] paramater.

C.   It supports ant-style paths.

D.   It doesn't support wildcard input.

17:

Which of the following statements is true for the configuration of the Spring handler adapter(s) in a Spring MVC application context?

A.  

Spring MVC defines 2 different request handler adapters by default: HttpRequestHandlerAdapter and SimpleControllerHandlerAdapter.


B.  

Request handler adapters need to be defined in the context files.


C.  

If at least one request handler adapter is defined the context files, Spring will not create the default adapters.


D.  

Using <mvc:annotation-driven /> causes the context to define both AnnotationMethodHandlerAdapter and SimpleControllerHandlerAdapter.


18:

What does the following code do?

@RequestMapping("/{id}/**")

public void foo(@PathVariable("id") int id, HttpServletRequest request) {

    String restOfTheUrl = (String) request.getAttribute(

        HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);

    ...

}

A.  

It retrieves the complete path value after the @RequestMapping and @PathVariable values have been parsed.


B.  

It retrieves the complete path value before the @RequestMapping and @PathVariable values have been parsed.


C.  

It retrieves the partial path value (after "**") after the @RequestMapping and @PathVariable values have been parsed.


D.  

It retrieves the partial path value (after "**") before the @RequestMapping and @PathVariable values have been parsed.


19: Which of the following statements is true about the HandlerInterceptor interface?

A.   It gets called after the appropriate HandlerAdapter triggers the execution of the handler itself.

B.   It allows exchanging the request and response objects that are handed down the execution chain.

C.   It gets configured in the application context.

D.   It is well-suited for request content and view content handling, such as multipart forms and GZIP compression.

20: How can an HTTP 404 status code be returned from a Spring MVC Controller?

A.   Throwing a ResourceNotFoundException declared with the @ResponseStatus annotation.

B.   Throwing an HttpRequestMethodNotSupportedException.

C.   Configuring in the Spring configuration XML document to send a 404 status for a controller via its "returnCode" argument.

D.   Having the method accept HttpServletResponse as a parameter, so that setStatus(404) can be called on it.

21: Which of the following is the default bean scope in Spring MVC?

A.   global session

B.   local session

C.   prototype

D.   singleton

22: True or false: a factory class can hold more than one factory method.

A.   True

B.   False

23: Which of the following enables custom qualifier annotation types to be registered even if they are not annotated with Spring’s @Qualifier annotation?

A.   CustomQualifier

B.   CustomAutowireConfigurer

C.   CustomQualifierType

D.   CustomAutowire

24:

Which of the following statements is correct?

A.  

Explicitly declared handler mappings or declaring <mvc:annotation-driven> are optional when using <mvc:resources>.


B.  

<mvc:resources> declares BeanNameUrlHandlerMapping by default.


C.  

<mvc:resources> doesn't declare its own handler mapping.


D.  

<mvc:resources> declares only DefaultAnnotationHandlerMapping by default.


25:

Which of the following can be used to serve static resources while still using DispatchServlet at the site's root?

A.  

<mvc:default-resources/>

B.  

<mvc:resources/>


C.  

<mvc:default-servlet-handler/>


D.  

<mvc:view-controller/>


26: Which of the following statements is true about the @RequestParam annotation?

A.   Providing a "defaultValue" optional element sets the "required" optional element to true.

B.   It indicates that a method parameter should be bound to a web request parameter.

C.   It is unsupported for annotated handler methods in Servlet and Portlet environments.

D.   None of these.

27:

What is the difference between the @Repository and the @Controller annotations in Spring?

A.  

"@Repository" is used as a stereotype for the persistence layer, while "@Controller" is used as a stereotype for the presentation layer. 

B.  

"@Repository" is used as a stereotype for the presentation layer, while "@Controller" is used as a stereotype for the persistence layer.


C.  

"@Repository" is used as a stereotype for the service layer, while "@Controller" is used as a generic stereotype for any Spring-managed component.


D.  

"@Controller" is used as a stereotype for the service layer, while "@Repository" is used as a generic stereotype for any Spring-managed component.


28:

Which of the following code samples will correctly return an image in @ResponseBody from a byte[] of image data?

A.  

@RequestMapping("/photo") public ResponseEntity<byte[]> testphoto() throws IOException { InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg"); final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.IMAGE_PNG); return new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, HttpStatus.CREATED); }


B.  

@ResponseBody @RequestMapping("/photo", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE) public byte[] testphoto() throws IOException { InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg"); return IOUtils.toByteArray(in); }


C.  

@RequestMapping("/photo") public void photo(HttpServletResponse response) throws IOException { response.setContentType("image/jpeg"); InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg"); IOUtils.copy(in, response.getOutputStream()); }


D.  

@ResponseBody @RequestMapping("/photo2) public byte[] testphoto() throws IOException { InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg"); return IOUtils.toByteArray(in); }


29:

Which of the following statements are correct, with respect to using the @PreAuthorize annotation in Spring controller methods?

A.  

@PreAuthorize does not work with Spring controller methods.


B.  

@PreAuthorize works with Spring controller methods.


C.  

The "pre-post-annotations" expression should be set to "disabled" in the servlet.xml file.


D.  

Using CGLIB proxies are optional when using @PreAuthorize in Spring controller methods.


30: Which of the following is not a built-in Spring MVC bean scope?

A.   singleton

B.   request

C.   global session

D.   local session

31: Which of the following annotations are supported by classes with the @Bean annotation?

A.   @PostConstruct

B.   @PreDestroy

C.   @PreConstruct

D.   @PostDestroy

32: Fill in the blank: _______ is a class-level annotation indicating that an object is a source of bean definitions.

A.   @Configuration

B.   @Definition

C.   @Bean

D.   @Scope

33: Regarding the @Resource annotation, which of the following statements is false?

A.   It is part of the JSR-250 specification.

B.   By default, Spring interprets its name attribute as the bean name to be injected.

C.   If no name attribute is specified, the default name is derived from the field name or setter method.

D.   It supports injection on bean property setter methods only.

34:

Fill in the blank:

When defining a bean that is created with a static factory method, the ______ attribute is used to specify the class containing the static factory method.

A.  

class

B.  

class-name


C.  

factory-class


D.  

factory-method


35: Which of the following statements is true about the @ModelAttribute annotation?

A.   It binds a method parameter or method return value to an anonymous model attribute.

B.   It can be used to expose reference data to a web view.

C.   It is not supported for controller classes with @RequestMapping methods.

D.   It cannot be used to expose command objects to a web view.

36:

Fill in the blank:

In Spring's XML-based configuration, the _______ attribute of the <property/> element specifies a property or constructor argument as a string representation.

A.  

namespace

B.  

name

C.  

class

D.  

value

37: Which of the following statements is/are true about autowiring in Spring?

A.   Multiple constructors a given class may carry the @AutoWired annotation.

B.   Only one constructor of any given class may carry the @AutoWired annotation.

C.   Fields are injected before the construction of a bean.

D.   Fields are injected after the construction of a bean.

38: Which of the following ViewResolver class is widely used?

A.   org.springframework.web.servlet.view.InternalResourceViewResolver

B.   java.springframework.webs.servlet.view.InternalResourceViewResolver

C.   import.springframework.web.servlet.view.InternalResourceViewResolver

D.   com.springframework.class.servlet.view.InternalResourceViewResolver

39: Which of the following is the most efficient way to serialize an Enum to JSON with Jackson 2.1?

A.   Annotate the Enum with @JsonFormat(shape= JsonFormat.Shape.OBJECT)

B.   Use the Jackson ObjectMapper

C.   Use Jackson's @JsonSerialize annotation with a custom serilaizer

D.   Use a custom mapper by extending Jackson's ObjectMapper

40:

Which statement best describes the <context:component-scan> tag for Spring XML configuration?


A.  

<context:component-scan> logically extends <context:annotation-config/>with CLASSPATH component scanning 

B.  

<context:component-scan> does not process annotations


C.  

<context:component-scan> ensures there will be  no duplicates beans in applicationcontext


D.  

<context:component-scan> only add beans annotated as @Component to be added to the  application context


41: Choose the reason why the expression ${user.home} can be null despite the use of @PropertySource annotation?

A.   User.home is an environment variable not a property

B.   User.home is a system variable not a property

C.   Need to use ${sys:user.home}

D.   Need to use ${env:user.home}

42:

Which is the best explanation as to why this Java configuration fails to correctly override / add a resource handler?


A.  

@Configuration 

@ComponentScan("...") 

@EnableTransactionManagement 

public class ApplicationContextConfig { // code}


B.  

public class ApplicationContextConfig needs to extend Spring's WebMvcConfigurerAdapter

C.  

@EnableTransactionManagement is only for JPA configuration


D.  

@EnableTransactionManagement restricts the classpath scan for Spring data annotations only


E.  

You need to remove the @ComponentScan annotation

43: Which class can be used to call Stored Procedures in Spring?

A.   JdbcTemplate

B.   SimpleJdbcCall

C.   JdbcTemplateCall

D.   SPHelper

44: What are the benefits of IOC?

A.   It minimizes the amount of code in your application.

B.   It makes your application easy to test as it doesn't require any singletons or JNDI lookup mechanisms in your unit test cases.

C.   Loose coupling is promoted with minimal effort and least intrusive mechanism.

D.   IOC containers support eager instantiation and lazy loading of services.

E.   All of the above

45: The SpEL module provides a powerful expression ____________ for querying and manipulation of an object.

A.   Language

B.   SDK

C.   Class

D.   Tool

46: What are the modules of the core container?

A.   Core, Bean, Context, Web-MVC

B.   Bean, Context, Web-MVC, AOP

C.   Bean, Context,Web-MVC,SpEL

D.   Core, Bean, Context, SpEL

47: Which statement is correct for @Controller annotation?

A.   The @Controller annotation indicates that a particular class serves the role of a controller. It does not require you to extend any controller base class or reference the Servlet API.

B.   @Controller annotation is used to map a URL to either an entire class or a particular handler method.

C.   @Controller is preferable over programmatic transaction management though it is less flexible than programmatic transaction management, which allows you to control transactions through your code.

D.   All of the above

48: Which of the following is the best way to retrieve the response header for a RestTemplate post request?

A.   Use the RestTemplate exchange method

B.   Use the RestTemplate exchange method and use responses getHeaders() method

C.   Use the RestTemplate exchange method and use responses toString() method

D.   Use the RestTemplate execute method

49:

Choose the correct expression needed to replace the error in the following code fragment for the Spring RestTemplate?


A.  

RestTemplate rt = new RestTemplate();

User returns = rt.postForObject(uri, u, String.class);


B.  

User returns = rt.postForObject(uri, u, User.class);

C.  

String returns = rt.postForObject(uri, u, User.class); 

D.  

User returns = rt.httpEntityCallback(uri, u, String .class);


E.  

User returns = rt.httpEntityCallback(uri, u, User.class);


F.  

String returns = (String ) rt.postForObject(uri, u, User.class);


50: Which of the following best describes the web module?

A.   The web module enables the creation of a web application without XML. The web.xml file needs to be configured for using the web module.

B.   The web module enables the creation of a android application without XML. The web.xml file needs to be configured for using the web module.

C.   The web module enables the creation of a php application without XML. The web.xml file needs to be configured for using the web module.

D.   None of the above