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.
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.
A. @Autowired ServletContext context;
B. request.getSession().getServletContext();
C. setServletContext(ServletContext context) { this.context = context; }
D. request.getSession().getServletContext();
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
A. XPath validation
B. Annotation validation
C. Programmatic validation
D. Mixed annotation and programmatic validation
A. Constructor-based dependency injection
B. Setter-based dependency injection
C. Prototype-based dependency injection
D. Manual dependency injection
A. InitializingBean
B. IntializeableBean
C. DisposableBean
D. DisposingBean
A. Basic Authentication
B. Digest Access Authentication
C. Remember-me Authentication
D. Multi-factor authentication
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.
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.
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.
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.
A. PageListSorter
B. PageListContext
C. PagedListHolder
D. Spring MVC doesn't include a built-in class for handling pagination.
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.
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.
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
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.
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.
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.
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.
A. Throwing a ResourceNotFoundException declared with the @ResponseStatus annotation.
B. Throwing an HttpRequestMethodNotSupportedException.
C. Configuring
D. Having the method accept HttpServletResponse as a parameter, so that setStatus(404) can be called on it.
A. global session
B. local session
C. prototype
D. singleton
A. True
B. False
A. CustomQualifier
B. CustomAutowireConfigurer
C. CustomQualifierType
D. CustomAutowire
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.
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/>
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.
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.
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); }
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.
A. singleton
B. request
C. global session
D. local session
A. @PostConstruct
B. @PreDestroy
C. @PreConstruct
D. @PostDestroy
A. @Configuration
B. @Definition
C. @Bean
D. @Scope
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.
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
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.
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
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.
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
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
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
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}
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
A. JdbcTemplate
B. SimpleJdbcCall
C. JdbcTemplateCall
D. SPHelper
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
A. Language
B. SDK
C. Class
D. Tool
A. Core, Bean, Context, Web-MVC
B. Bean, Context, Web-MVC, AOP
C. Bean, Context,Web-MVC,SpEL
D. Core, Bean, Context, SpEL
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
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
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);
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