oDesk Spring MVC Test 2015



1. In an annotation-based Spring MVC controller, which of the following are valid ways to set cache headers for a specific path?
Answers:
• Ensuring the instance of "AnnotationMethodHandlerAdapter" does not have the "cacheSeconds" property set, and adding an instance of "WebContentInterceptor".
• Adding "final HttpServletResponse response" as a parameter, then setting the header "Cache-Control" to "all-cache".
• Using a Handler Interceptor and using the "postHandle" method provided by it.
• Cache headers cannot be set for a specific path.

2. Which of the following code samples will get the ServletContext inside an Interceptor?
Answers:
• @Autowired ServletContext context;
• request.getSession().getServletContext();
• setServletContext(ServletContext context) { this.context = context; }
• request.getSession().getServletContext();
3. Which of the following are valid sets of constructor arguments for the ModelAndView class? (Select all correct answers.)
Answers:
• String viewName
• String viewName, Map<String,?> model
• String modelName, Map<String,?> model
• View view, Map<String,?> model, Object modelObject
4. Which of the following are possible validation methods for user input in Spring MVC?
Answers:
• XPath validation
• Annotation validation
• Programmatic validation
• Mixed annotation and programmatic validation
5. Which of the following dependency injection (DI) methodologies are available in Spring MVC?
Answers:
• Constructor-based dependency injection
• Setter-based dependency injection
• Prototype-based dependency injection
• Manual dependency injection
6. Which of the following interfaces can be implemented to interact with a container's management of the bean lifecycle?
Answers:
• InitializingBean
• IntializeableBean
• DisposableBean
• DisposingBean
7. Select all authentication methods that are supported by Spring Security by default:
Answers:
• Basic Authentication
• Digest Access Authentication
• Remember-me Authentication
• Multi-factor authentication
8. Which of the following statements is false?
Answers:
• Spring MVC provides both declarative and programmatic transaction management.
• 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.
• By default, a transaction is only marked for rollback in the case of runtime unchecked exceptions.
• None of these.
9. Which of the following statements is true about the HandlerExceptionResolver class?
Answers:
• Any Spring bean that implements HandlerExceptionResolver will be used to intercept and process any exception raised that was handled by a Controller.
• @ExceptionHandler methods can be injected with the model.
• DefaultHandlerExceptionResolver converts standard Spring exceptions and converts them to HTTP Status Codes.
• None of these.
10. Which of the following  statements is true about method arguments that have an @ModelAttribute annotation?
Answers:
• It indicates that the argument should be retrieved from the model.
• If the argument is not present in the model, it should be added to the model first, and then instantiated.
• If the argument is not present in the model, it should be instantiated first, and then added to the model.
• 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?
Answers:
• It allows access to request and response headers.
• It doesn't allow access to request and response headers.
• It returns a JSON String and sets the mimetype to text/plain.
• 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?
Answers:
• PageListSorter
• PageListContext
• PagedListHolder
• 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?
Answers:
• The attribute appears as string name-value pairs in the URL because the @ModelAttribute annotation is used in the controller.
• Adding "model.asMap().clear();" will prevent the attribute name-value pair from appearing in the URL.
• The attribute name-value pair will be included in the URL, regardless of the use of @ModelAttribute in the controller.
• 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?
Answers:
• <context:annotation-config> activates many different annotations in beans, whether they are defined in XML or through component scanning.
• <context:annotation-config> declares explicit support for annotation-driven MVC controllers.
• <context:annotation-config> adds support for declarative validation via @Valid.
• 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.
Answers:
• default namespace
• c-namespace
• p-namespace
• namespace
16. Which of the following statements is true about the @RequestMapping annotation?
Answers:
• It has a single String parameter.
• It has a String[] paramater.
• It supports ant-style paths.
• 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?
Answers:
• Spring MVC defines 2 different request handler adapters by default: HttpRequestHandlerAdapter and SimpleControllerHandlerAdapter.
• Request handler adapters need to be defined in the context files.
• If at least one request handler adapter is defined the context files, Spring will not create the default adapters.
• 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);
    ...
}
Answers:
• It retrieves the complete path value after the @RequestMapping and @PathVariable values have been parsed.
• It retrieves the complete path value before the @RequestMapping and @PathVariable values have been parsed.
• It retrieves the partial path value (after "**") after the @RequestMapping and @PathVariable values have been parsed.
• 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?
Answers:
• It gets called after the appropriate HandlerAdapter triggers the execution of the handler itself.
• It allows exchanging the request and response objects that are handed down the execution chain.
• It gets configured in the application context.
• 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?
Answers:
• Throwing a ResourceNotFoundException declared with the @ResponseStatus annotation.
• Throwing an HttpRequestMethodNotSupportedException.
• Configuring <context:annotation-config> in the Spring configuration XML document to send a 404 status for a controller via its "returnCode" argument.
• 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?
Answers:
• global session
• local session
• prototype
• singleton
22. True or false: a factory class can hold more than one factory method.
Answers:
• True
• 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?
Answers:
• CustomQualifier
• CustomAutowireConfigurer
• CustomQualifierType
• CustomAutowire
24. Which of the following statements is correct?
Answers:
• Explicitly declared handler mappings or declaring <mvc:annotation-driven> are optional when using <mvc:resources>.
• <mvc:resources> declares BeanNameUrlHandlerMapping by default.
• <mvc:resources> doesn't declare its own handler mapping.
• <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?
Answers:
• <mvc:default-resources/>
• <mvc:resources/>
• <mvc:default-servlet-handler/>
• <mvc:view-controller/>
26. Which of the following statements is true about the @RequestParam annotation?
Answers:
• Providing a "defaultValue" optional element sets the "required" optional element to true.
• It indicates that a method parameter should be bound to a web request parameter.
• It is unsupported for annotated handler methods in Servlet and Portlet environments.
• None of these.
27. What is the difference between the @Repository and the @Controller annotations in Spring?
Answers:
• "@Repository" is used as a stereotype for the persistence layer, while "@Controller" is used as a stereotype for the presentation layer.
• "@Repository" is used as a stereotype for the presentation layer, while "@Controller" is used as a stereotype for the persistence layer.
• "@Repository" is used as a stereotype for the service layer, while "@Controller" is used as a generic stereotype for any Spring-managed component.
• "@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?
Answers:
• @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); }
• @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); }
• @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()); }
• @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?
Answers:
• @PreAuthorize does not work with Spring controller methods.
• @PreAuthorize works with Spring controller methods.
• The "pre-post-annotations" expression should be set to "disabled" in the servlet.xml file.
• 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?
Answers:
• singleton
• request
• global session
• local session
31. Which of the following annotations are supported by classes with the @Bean annotation?
Answers:
• @PostConstruct
• @PreDestroy
• @PreConstruct
• @PostDestroy
32. Fill in the blank: _______ is a class-level annotation indicating that an object is a source of bean definitions.
Answers:
• @Configuration
• @Definition
• @Bean
• @Scope
33. Regarding the @Resource annotation, which of the following statements is false?
Answers:
• It is part of the JSR-250 specification.
• By default, Spring interprets its name attribute as the bean name to be injected.
• If no name attribute is specified, the default name is derived from the field name or setter method.
• 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.
Answers:
• class
• class-name
• factory-class
• factory-method
35. Which of the following statements is true about the @ModelAttribute annotation?
Answers:
• It binds a method parameter or method return value to an anonymous model attribute.
• It can be used to expose reference data to a web view.
• It is not supported for controller classes with @RequestMapping methods.
• 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.
Answers:
• namespace
• name
• class
• value
37. Which of the following statements is/are true about autowiring in Spring?
Answers:
• Multiple constructors a given class may carry the @AutoWired annotation.
• Only one constructor of any given class may carry the @AutoWired annotation.
• Fields are injected before the construction of a bean.
• Fields are injected after the construction of a bean.

38. Regarding dependency resolution, which of the following statements is false?
Answers:
• The ApplicationContext is created and initialized with configuration metadata that describes all the beans.
• Configuration metadata can only be specified via XML or annotations.
• Each property or constructor argument is an actual definition of the value to set, or a reference to another bean in the container.
• For each bean, its dependencies are expressed in the form of properties, constructor arguments, or arguments to the static-factory method.