InternalViewResolver in spring boot is unable to find the view - spring

I don't know I have tried multiple times but never really understood how the InternalViewResolver or any view resolver work under the hood. I have configured the view resolution using WebMvcConfigurer. like this one.
#Configuration
public class WebViewConfigurer implements WebMvcConfigurer {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/register").setViewName("registration");
}
}
I have put my html file registration.html in the location: src/main/resources/templates.
Whenever I try to access the page localhost:8080/register I get the whitelabel error page
There was an unexpected error (type=Not Found, status=404).
I have configured view like this many times before and I have always faced problem in the beginning but I always get on top of it after some tweak and this time also I know I would get it. So the problem is not just how I solve my current problem but how can I stop this repetitive mistakes. Has any one faced these problems with ViewResolvers in spring or is it just me.

How logical names are resolved in spring?
Logical names are resolved by DispatcherServelet. And is helped by various view Resolvers . One of which is Internal View Resolver which is a Url based View Resolver.
Follow the stack:
getResource:154, PathResourceResolver (org.springframework.web.servlet.resource)
resolveResourceInternal:137, PathResourceResolver (org.springframework.web.servlet.resource)
resolveResource:46, AbstractResourceResolver (org.springframework.web.servlet.resource)
resolveResource:75, DefaultResourceResolverChain (org.springframework.web.servlet.resource)
getResource:560, ResourceHttpRequestHandler (org.springframework.web.servlet.resource)
handleRequest:485, ResourceHttpRequestHandler (org.springframework.web.servlet.resource)
handle:53, HttpRequestHandlerAdapter (org.springframework.web.servlet.mvc)
doDispatch:1040, DispatcherServlet (org.springframework.web.servlet)
doService:943, DispatcherServlet (org.springframework.web.servlet)
processRequest:1006, FrameworkServlet (org.springframework.web.servlet)
doGet:898, FrameworkServlet (org.springframework.web.servlet)
service:634, HttpServlet (javax.servlet.http)
service:883, FrameworkServlet (org.springframework.web.servlet)
service:741, HttpServlet (javax.servlet.http)
internalDoFilter:231, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
doFilter:53, WsFilter (org.apache.tomcat.websocket.server)
internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
doFilter:113, OncePerRequestFilter (org.springframework.web.filter)
internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
doFilter:113, OncePerRequestFilter (org.springframework.web.filter)
internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
doFilter:113, OncePerRequestFilter (org.springframework.web.filter)
internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
invoke:712, ApplicationDispatcher (org.apache.catalina.core)
processRequest:459, ApplicationDispatcher (org.apache.catalina.core)
doForward:384, ApplicationDispatcher (org.apache.catalina.core)
forward:312, ApplicationDispatcher (org.apache.catalina.core)
renderMergedOutputModel:171, InternalResourceView (org.springframework.web.servlet.view)
render:316, AbstractView (org.springframework.web.servlet.view)
render:1373, DispatcherServlet (org.springframework.web.servlet)
processDispatchResult:1118, DispatcherServlet (org.springframework.web.servlet)
doDispatch:1057, DispatcherServlet (org.springframework.web.servlet)
doService:943, DispatcherServlet (org.springframework.web.servlet)
processRequest:1006, FrameworkServlet (org.springframework.web.servlet)
doGet:898, FrameworkServlet (org.springframework.web.servlet)
service:634, HttpServlet (javax.servlet.http)
service:883, FrameworkServlet (org.springframework.web.servlet)
service:741, HttpServlet (javax.servlet.http)
internalDoFilter:231, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
doFilter:53, WsFilter (org.apache.tomcat.websocket.server)
internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
doFilterInternal:100, RequestContextFilter (org.springframework.web.filter)
doFilter:119, OncePerRequestFilter (org.springframework.web.filter)
internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
doFilterInternal:93, FormContentFilter (org.springframework.web.filter)
doFilter:119, OncePerRequestFilter (org.springframework.web.filter)
internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
doFilterInternal:201, CharacterEncodingFilter (org.springframework.web.filter)
doFilter:119, OncePerRequestFilter (org.springframework.web.filter)
internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core)
doFilter:166, ApplicationFilterChain (org.apache.catalina.core)
invoke:202, StandardWrapperValve (org.apache.catalina.core)
invoke:96, StandardContextValve (org.apache.catalina.core)
invoke:541, AuthenticatorBase (org.apache.catalina.authenticator)
invoke:139, StandardHostValve (org.apache.catalina.core)
invoke:92, ErrorReportValve (org.apache.catalina.valves)
invoke:74, StandardEngineValve (org.apache.catalina.core)
service:343, CoyoteAdapter (org.apache.catalina.connector)
service:373, Http11Processor (org.apache.coyote.http11)
process:65, AbstractProcessorLight (org.apache.coyote)
process:868, AbstractProtocol$ConnectionHandler (org.apache.coyote)
doRun:1590, NioEndpoint$SocketProcessor (org.apache.tomcat.util.net)
run:49, SocketProcessorBase (org.apache.tomcat.util.net)
runWorker:1149, ThreadPoolExecutor (java.util.concurrent)
run:624, ThreadPoolExecutor$Worker (java.util.concurrent)
run:61, TaskThread$WrappingRunnable (org.apache.tomcat.util.threads)
run:748, Thread (java.lang)
PathResourceResolver has a resource variable passed by ResourceHttpRequestHandler which tries to resolve the resource . The resource could be of different types like: ClasspathResource or ServletContextResource.
You can debug the PathResourceResolver.getResource() method to find if in case your resource is not resolved.

In case of any one wondering I solved the current problem: I added prefix and suffix in InternalViewResolved and placed the html file in target/class/resources/templates.
My current code after solving:
#Configuration
public class WebViewConfigurer implements WebMvcConfigurer {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/register").setViewName("registration");
}
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.viewResolver(new InternalResourceViewResolver(){{setPrefix("templates/");setSuffix(".html");}});
}
}

Related

how to transfer spring security settings from spring to spring boot

I translate the project from spring to spring boot. the last thing left to do is configure the security.
I tried to do as here but failed XML configuration of Spring Security in Spring Boot
I have
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<http entry-point-ref="restAuthenticationEntryPoint">
<intercept-url pattern="/com/bt**" access="hasAnyRole('ROLE_ADMIN','ROLE_USER')" />
<intercept-url pattern="/com/bt/db/**" access="permitAll()" />
<form-login login-page="/login" login-processing-url="/j_spring_security_check"
authentication-success-handler-ref="successHandler"
authentication-failure-handler-ref="failureHandler" />
<csrf disabled="true" />
<!-- <headers> <frame-options disabled="true"/> <hsts disabled="true"/>
<cache-control disabled="true"/> </headers> -->
<logout />
</http>
<beans:bean id="successHandler" class="com.bt.AjaxAuthSuccessHandler" />
<beans:bean id="failureHandler"
class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler" />
<authentication-manager alias="authenticationManager">
<authentication-provider>
<password-encoder hash="bcrypt" />
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="select username,password, enabled from users where username=?"
authorities-by-username-query="select username, role from user_roles where username =?" />
</authentication-provider>
</authentication-manager>
and this entity
#Entity
#Table(name="users", schema="public")
public class User {
#Id
private String username;
#Column(name="password")
private String password;
#Column(name="enabled")
private boolean enabled;
#OneToMany(mappedBy="user")
private List<UserRole> userRoles;
}
class which is used in app-context-security.xml
public class AjaxAuthSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
public AjaxAuthSuccessHandler() {
super();
setRedirectStrategy(new NoRedirectStrategy());
}
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
super.onAuthenticationSuccess(request, response, authentication);
Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();
response.setContentType("application/json");
response.setCharacterEncoding("UTF8");
response.getWriter().print("{\"role\": \""+authorities.toArray()[0]+"\"}");
}
protected class NoRedirectStrategy implements RedirectStrategy {
#Override
public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url)
throws IOException {
// no redirect
}
}
}
UPDATE:
I was create second entity with roles
#Entity
#Table(name="user_role", schema="public")
public class UserRole {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private Integer id;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name = "username")
private User user;
#Column(name="role")
private String role;
and repository for this entity.
created service
#Service
public class UserService implements UserDetailsService {
#Autowired
private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
User user = userRepository.findById(name)
.orElseThrow( () -> new UsernameNotFoundException("Invalid username or password"));
return new org.springframework.security.core.userdetails.User(user.getUsername(),
user.getPassword(),
mapRolesToAuthorities(user.getQueuesManagers()));
}
private Collection<? extends GrantedAuthority> mapRolesToAuthorities(List<UserQueueManager> roles){
return roles.stream()
.map(role -> new SimpleGrantedAuthority(role.getRole()))
.collect(Collectors.toList());
}
}
based on these classes created a configuration file
#Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserService userService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
#Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
#Bean
public DaoAuthenticationProvider authenticationProvider(){
DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
auth.setUserDetailsService(userService);
auth.setPasswordEncoder(passwordEncoder());
return auth;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
}
but for some reason it doesn't work :(
UPD 2:
20:22:14.564 [http-nio-8080-exec-5] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/ETP.MQ.WEB.CONSOLE/components/select2/select2.min.css", parameters={}
20:22:14.564 [http-nio-8080-exec-10] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/ETP.MQ.WEB.CONSOLE/components/angular-ui-router.min.js", parameters={}
20:22:14.564 [http-nio-8080-exec-6] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/ETP.MQ.WEB.CONSOLE/components/jquery/dist/js/jquery.min.js", parameters={}
20:22:14.564 [http-nio-8080-exec-9] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/ETP.MQ.WEB.CONSOLE/components/angular-cookies/angular-cookies.js", parameters={}
20:22:14.564 [http-nio-8080-exec-7] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/ETP.MQ.WEB.CONSOLE/components/bootstrap/dist/js/bootstrap.min.js", parameters={}
20:22:14.564 [http-nio-8080-exec-8] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/ETP.MQ.WEB.CONSOLE/components/angular-datatables/angular-datatables.min.js", parameters={}
20:22:14.569 [http-nio-8080-exec-9] WARN org.springframework.web.servlet.PageNotFound - No mapping for GET /ETP.MQ.WEB.CONSOLE/components/angular-cookies/angular-cookies.js
20:22:14.569 [http-nio-8080-exec-7] WARN org.springframework.web.servlet.PageNotFound - No mapping for GET /ETP.MQ.WEB.CONSOLE/components/bootstrap/dist/js/bootstrap.min.js
20:22:14.569 [http-nio-8080-exec-8] WARN org.springframework.web.servlet.PageNotFound - No mapping for GET /ETP.MQ.WEB.CONSOLE/components/angular-datatables/angular-datatables.min.js
20:22:14.569 [http-nio-8080-exec-10] WARN org.springframework.web.servlet.PageNotFound - No mapping for GET /ETP.MQ.WEB.CONSOLE/components/angular-ui-router.min.js
20:22:14.569 [http-nio-8080-exec-6] WARN org.springframework.web.servlet.PageNotFound - No mapping for GET /ETP.MQ.WEB.CONSOLE/components/jquery/dist/js/jquery.min.js
20:22:14.569 [http-nio-8080-exec-5] WARN org.springframework.web.servlet.PageNotFound - No mapping for GET /ETP.MQ.WEB.CONSOLE/components/select2/select2.min.css
20:22:14.570 [http-nio-8080-exec-10] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 404 NOT_FOUND
20:22:14.570 [http-nio-8080-exec-6] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 404 NOT_FOUND
20:22:14.570 [http-nio-8080-exec-9] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 404 NOT_FOUND
20:22:14.570 [http-nio-8080-exec-7] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 404 NOT_FOUND
20:22:14.570 [http-nio-8080-exec-8] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 404 NOT_FOUND
20:22:14.570 [http-nio-8080-exec-5] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 404 NOT_FOUND
20:22:14.584 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/ETP.MQ.WEB.CONSOLE/components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff2", parameters={}
20:22:14.585 [http-nio-8080-exec-1] WARN org.springframework.web.servlet.PageNotFound - No mapping for GET /ETP.MQ.WEB.CONSOLE/components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff2
20:22:14.585 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 404 NOT_FOUND
20:22:14.590 [http-nio-8080-exec-2] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/ETP.MQ.WEB.CONSOLE/components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff", parameters={}
20:22:14.590 [http-nio-8080-exec-2] WARN org.springframework.web.servlet.PageNotFound - No mapping for GET /ETP.MQ.WEB.CONSOLE/components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff
20:22:14.591 [http-nio-8080-exec-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 404 NOT_FOUND
20:22:14.595 [http-nio-8080-exec-3] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/ETP.MQ.WEB.CONSOLE/components/bootstrap/dist/fonts/glyphicons-halflings-regular.ttf", parameters={}
20:22:14.596 [http-nio-8080-exec-3] WARN org.springframework.web.servlet.PageNotFound - No mapping for GET /ETP.MQ.WEB.CONSOLE/components/bootstrap/dist/fonts/glyphicons-halflings-regular.ttf
20:22:14.596 [http-nio-8080-exec-3] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 404 NOT_FOUND
20:22:14.601 [http-nio-8080-exec-4] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/ETP.MQ.WEB.CONSOLE/components/bootstrap/dist/fonts/glyphicons-halflings-regular.svg", parameters={}
20:22:14.602 [http-nio-8080-exec-4] WARN org.springframework.web.servlet.PageNotFound - No mapping for GET /ETP.MQ.WEB.CONSOLE/components/bootstrap/dist/fonts/glyphicons-halflings-regular.svg
20:22:14.602 [http-nio-8080-exec-4] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 404 NOT_FOUND
the stricture of my project:
enter image description here
and configuration class
#Configuration
public class WebMvcConfigure implements WebMvcConfigurer {
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver
= new InternalResourceViewResolver();
resolver.setPrefix("/*");
resolver.setSuffix("*.jsp");
return resolver;
}
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/webapp/**")
.addResourceLocations("/webapp/").setCachePeriod(3600)
.resourceChain(true).addResolver(new PathResourceResolver());
}
}
LAST UPDATE
<servlet>
<servlet-name>page-resolver</servlet-name>
<servlet-class>com.bk.ForwardServlet</servlet-class>
<init-param>
<param-name>page</param-name>
<param-value>/index.jsp</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>page-resolver</servlet-name>
<url-pattern>/index.html</url-pattern>
<url-pattern>/login</url-pattern>
<url-pattern>/qmgr/*</url-pattern>
</servlet-mapping>

What is wrong in this Spring Boot Swagger configuration to obtain the documentation of my REST API? Why I can't access to the documentation?

I am working on a Spring Boot application and I am trying to configure Swagger to automatically generate my REST service documentation.
I am following this tutorial: http://www.baeldung.com/swagger-2-documentation-for-spring-rest-api
But I am finding some difficulties to do it.
So basically I have created the following Java configuration class into my Spring Boot project:
#Configuration
#EnableSwagger2
public class Config {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
I think that this is the minimal configuration to generate the Swagger documentation of all my REST service. I have put this configuration class at the same level of the Application class (the class that contains the main() method that start my project). I think that the Config class is ok because I have tryed to put a brack point into the api() method and I can see that it enter in this method at the project startup so I think that this configuration is loaded.
Then in the previous tutorial it say that to verify that the my REST API Swagger documentation is generated I have to perform a GET request to this URL: http://localhost:8080/spring-security-rest/api/v2/api-docs
I think that this URL is related to the example project and not to my project.
So I tried to use: http://localhost:8080/api-docs
But doing in this way I am obtaining this error message:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sat Jan 14 16:05:23 CET 2017
There was an unexpected error (type=Not Found, status=404).
No message available
And in the IDE console I have this message:
[DEBUG] 2017-01-14 16:40:05 [org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:865)] [http-nio-8080-exec-4] DispatcherServlet - DispatcherServlet with name 'dispatcherServlet' processing GET request for [/swagger-ui.html]
[DEBUG] 2017-01-14 16:40:05 [org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:310)] [http-nio-8080-exec-4] RequestMappingHandlerMapping - Looking up handler method for path /swagger-ui.html
[DEBUG] 2017-01-14 16:40:05 [org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:320)] [http-nio-8080-exec-4] RequestMappingHandlerMapping - Did not find handler method for [/swagger-ui.html]
[DEBUG] 2017-01-14 16:40:05 [org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.lookupHandler(AbstractUrlHandlerMapping.java:190)] [http-nio-8080-exec-4] SimpleUrlHandlerMapping - Matching patterns for request [/swagger-ui.html] are [/**]
[DEBUG] 2017-01-14 16:40:05 [org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.lookupHandler(AbstractUrlHandlerMapping.java:219)] [http-nio-8080-exec-4] SimpleUrlHandlerMapping - URI Template variables for request [/swagger-ui.html] are {}
[DEBUG] 2017-01-14 16:40:05 [org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.getHandlerInternal(AbstractUrlHandlerMapping.java:140)] [http-nio-8080-exec-4] SimpleUrlHandlerMapping - Mapping [/swagger-ui.html] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver#4e671ef]]] and 1 interceptor
[DEBUG] 2017-01-14 16:40:05 [org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:951)] [http-nio-8080-exec-4] DispatcherServlet - Last-Modified value for [/swagger-ui.html] is: -1
[DEBUG] 2017-01-14 16:40:05 [org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1044)] [http-nio-8080-exec-4] DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
[DEBUG] 2017-01-14 16:40:05 [org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1000)] [http-nio-8080-exec-4] DispatcherServlet - Successfully completed request
[DEBUG] 2017-01-14 16:40:05 [org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:865)] [http-nio-8080-exec-4] DispatcherServlet - DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error]
[DEBUG] 2017-01-14 16:40:05 [org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:310)] [http-nio-8080-exec-4] RequestMappingHandlerMapping - Looking up handler method for path /error
[DEBUG] 2017-01-14 16:40:05 [org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:317)] [http-nio-8080-exec-4] RequestMappingHandlerMapping - Returning handler method [public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)]
[DEBUG] 2017-01-14 16:40:05 [org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:951)] [http-nio-8080-exec-4] DispatcherServlet - Last-Modified value for [/error] is: -1
[DEBUG] 2017-01-14 16:40:05 [org.springframework.web.servlet.view.ContentNegotiatingViewResolver.getMediaTypes(ContentNegotiatingViewResolver.java:263)] [http-nio-8080-exec-4] ContentNegotiatingViewResolver - Requested media types are [text/html, text/html;q=0.8] based on Accept header types and producible media types [text/html])
[DEBUG] 2017-01-14 16:40:05 [org.springframework.web.servlet.view.BeanNameViewResolver.resolveViewName(BeanNameViewResolver.java:74)] [http-nio-8080-exec-4] BeanNameViewResolver - No matching bean found for view name 'error.html'
[DEBUG] 2017-01-14 16:40:05 [org.springframework.web.servlet.view.ContentNegotiatingViewResolver.getBestView(ContentNegotiatingViewResolver.java:338)] [http-nio-8080-exec-4] ContentNegotiatingViewResolver - Returning [org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$SpelView#50e8ed74] based on requested media type 'text/html'
[DEBUG] 2017-01-14 16:40:05 [org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1251)] [http-nio-8080-exec-4] DispatcherServlet - Rendering view [org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$SpelView#50e8ed74] in DispatcherServlet with name 'dispatcherServlet'
[DEBUG] 2017-01-14 16:40:05 [org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1000)] [http-nio-8080-exec-4] DispatcherServlet - Successfully completed request
The thing that seems me strange is that I have configured nothing related to the URL for my documentation (I don't know if there is a standard URL).
Some further details that maybe could are important to find a solution.
My REST API are implemented in Spring Boot by Controller class that handles request like this:
package com.myapp.controller.room;
#RestController
#RequestMapping("/Room")
public class RoomController {
private static final Logger log = LoggerFactory.getLogger(RoomController.class);
#Autowired
private RoomService roomService;
#Autowired
private RoomMediaService roomMediaService;
public RoomController(){
log.debug("RoomController init");
}
/**
* Ritorna la tipologia di stanza associata ad una stanza
* #param id dellla stanza di cui si intende reperire le informazioni relative alla sua tipologia
* #return RoomTipologyDTO contenente le informazioni relative alla tipologia di stanza
* #throws DataAccessException
*/
#RequestMapping(value = "/{id}/RoomTipology",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<RoomTipologyDTO> getRoomTipologyByRoomId(#PathVariable Long id) throws DataAccessException{
log.debug("getRoomTipologyByRoomId START");
RoomTipologyDTO result = roomService.getRoomTipologyByRoom(id);
log.debug("getRoomTipologyByRoomId END");
return ResponseEntity.ok(result);
}
....................................................................
....................................................................
....................................................................
}
This is the Application class that contains the main() method that start my application:
#SpringBootApplication
#EntityScan("com.betrivius.domain")
#ComponentScan(lazyInit = true)
#EnableAutoConfiguration
public class Application {
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
//context.close();
log.info("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = context.getBeanDefinitionNames();
Arrays.sort(beanNames);
log.info("_______________________________________________________");
for (String beanName : beanNames) {
log.info(beanName);
}
log.info("main() END");
}
}
An example of an URL of one o my service is something like this:
http://localhost:8080/RoomRate/1/RoomRateOptionList
So what is the correct URL to generate my Swagger documentation? Or what am I missing? How can I fix this issue?
Try accessing swagger docs on http://localhost:8080/v2/api-docs. it should work. i think you are using version 2 of swagger documentation.

Spring Social Twitter HTTP Status 405 - Request method 'POST' not supported

Friends I am using Spring Mvc 4.2.5, Spring Security 4.0.4 , Spring Social 1.1.2 to integrate with twitter api.everything is fine upto connectcontroller handling get /connect/twitter,/connect . but when i send post request from twitterConnect.jsp its giving 405 error
here is my SocialConfiguration code
#Configuration
#EnableSocial
#PropertySource(value = { "classpath:twitter.properties" })
public class SpringSocialConfig implements SocialConfigurer {
static final Logger logger = Logger.getLogger(SpringSocialConfig.class);
#Autowired
private DataSource dataSource;
//
// SocialConfigurer implementation methods
//
#Override
public void addConnectionFactories(ConnectionFactoryConfigurer cfConfig, Environment env) {
logger.info("at addconnectionFactory adding consumerkey");
System.out.println("at add Connection FActory");
cfConfig.addConnectionFactory(new TwitterConnectionFactory(env.getProperty("twitter.consumerKey"), env.getProperty("twitter.consumerSecret")));
}
#Override
public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
logger.info("crateing jdbcuserconnection repository");
return new JdbcUsersConnectionRepository(dataSource, connectionFactoryLocator, Encryptors.noOpText());
}
// API Binding Beans
//
#Bean
#Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
public Twitter twitter(ConnectionRepository repository) {
Connection<Twitter> connection = repository.findPrimaryConnection(Twitter.class);
logger.info("crateing connection Twitter");
return connection != null ? connection.getApi() : null;
}
//
// Web Controller and Filter Beans
//
#Bean
public ConnectController connectController(ConnectionFactoryLocator connectionFactoryLocator, ConnectionRepository connectionRepository) {
ConnectController connectController = new ConnectController(connectionFactoryLocator, connectionRepository);
logger.info("At connect Controller");
System.out.println("hi iam running");
return connectController;
}
#Bean
public ReconnectFilter apiExceptionHandler(UsersConnectionRepository usersConnectionRepository, UserIdSource userIdSource) {
return new ReconnectFilter(usersConnectionRepository, userIdSource);
}
#Override
public UserIdSource getUserIdSource() {
return new UserIdSource() {
#Override
public String getUserId() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
throw new IllegalStateException("Unable to get a ConnectionRepository: no user signed in");
}
return authentication.getName();
}
};
}
}
This is my SecurityConfiguration
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
#Qualifier("customUserDetailsService")
UserDetailsService userDetailsService;
#Autowired
PersistentTokenRepository tokenRepository;
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
auth.authenticationProvider(authenticationProvider());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.antMatchers("/signup/**").anonymous()
.antMatchers("/dashboard/**","/add_t_accounts/**").access("hasRole('USER')")
.and().formLogin().loginPage("/login").loginProcessingUrl("/login").defaultSuccessUrl("/dashboard")
.usernameParameter("userName").passwordParameter("password").and()
.rememberMe().rememberMeParameter("remember-me").tokenRepository(tokenRepository)
.tokenValiditySeconds(86400).and().csrf()
.and().exceptionHandling().accessDeniedPage("/Access_Denied");
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public TextEncryptor textEncryptor() {
return Encryptors.noOpText();
}
#Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
#Bean
public PersistentTokenBasedRememberMeServices getPersistentTokenBasedRememberMeServices() {
PersistentTokenBasedRememberMeServices tokenBasedservice = new PersistentTokenBasedRememberMeServices(
"remember-me", userDetailsService, tokenRepository);
return tokenBasedservice;
}
#Bean
public AuthenticationTrustResolver getAuthenticationTrustResolver() {
return new AuthenticationTrustResolverImpl();
}
#Bean(name="authenticationManager")
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
Im getting this on console
enter code hereo
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.AnnotationConfigWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Thu Nov 24 05:04:03 IST 2016]; root of context hierarchy
INFO : org.springframework.web.context.support.AnnotationConfigWebApplicationContext - Registering annotated classes: [class org.springframework.social.showcase.config.MainConfig,class org.springframework.social.showcase.config.WebMvcConfig,class org.springframework.social.showcase.config.SecurityConfig,class org.springframework.social.showcase.config.SocialConfig]
WARN : org.springframework.context.annotation.ConfigurationClassEnhancer - #Bean method MainConfig.propertyPlaceHolderConfigurer is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as #Autowired, #Resource and #PostConstruct within the method's declaring #Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see #Bean javadoc for complete details
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO : org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Detected #ExceptionHandler methods in exceptionHandlingControllerAdvice
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - Looking for #ControllerAdvice: Root WebApplicationContext: startup date [Thu Nov 24 05:04:03 IST 2016]; root of context hierarchy
INFO : org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/resources/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.HomeController.home(java.security.Principal,org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signin],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public void org.springframework.social.showcase.signin.SigninController.signin()
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signup],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.social.showcase.signup.SignupForm org.springframework.social.showcase.signup.SignupController.signupForm(org.springframework.web.context.request.WebRequest)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signup],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.signup.SignupController.signup(org.springframework.social.showcase.signup.SignupForm,org.springframework.validation.BindingResult,org.springframework.web.context.request.WebRequest)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/friends],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterFriendsController.friends(org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/followers],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterFriendsController.followers(org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/messages],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterMessageController.sent(org.springframework.social.showcase.twitter.MessageForm)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/messages/sent],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterMessageController.sent(org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/messages],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterMessageController.inbox(org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterProfileController.home(java.security.Principal,org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/revoked],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public void org.springframework.social.showcase.twitter.TwitterRevokedToken.simulateExpiredToken()
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/search],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterSearchController.showTrends(java.lang.String,org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/timeline/{timelineType}],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterTimelineController.showTimeline(java.lang.String,org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/timeline],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterTimelineController.showTimeline(org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/tweet],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterTimelineController.postTweet(java.lang.String)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/trends],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterTrendsController.showTrends(org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signin/{providerId}],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ProviderSignInController.signIn(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signin/{providerId}],methods=[GET],params=[oauth_token],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ProviderSignInController.oauth1Callback(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signin/{providerId}],methods=[GET],params=[error],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ProviderSignInController.oauth2ErrorCallback(java.lang.String,java.lang.String,java.lang.String,java.lang.String,org.springframework.web.context.request.NativeWebRequest)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signin/{providerId}],methods=[GET],params=[code],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ProviderSignInController.oauth2Callback(java.lang.String,java.lang.String,org.springframework.web.context.request.NativeWebRequest)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signin/{providerId}],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ProviderSignInController.canceledAuthorizationCallback()
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.connect(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}],methods=[GET],params=[oauth_token],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.oauth1Callback(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}],methods=[GET],params=[error],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.oauth2ErrorCallback(java.lang.String,java.lang.String,java.lang.String,java.lang.String,org.springframework.web.context.request.NativeWebRequest)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.connect.web.ConnectController.connectionStatus(org.springframework.web.context.request.NativeWebRequest,org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.connect.web.ConnectController.connectionStatus(java.lang.String,org.springframework.web.context.request.NativeWebRequest,org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}],methods=[GET],params=[code],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.oauth2Callback(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}/{providerUserId}],methods=[DELETE],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.removeConnection(java.lang.String,java.lang.String,org.springframework.web.context.request.NativeWebRequest)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}],methods=[DELETE],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.removeConnections(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
INFO : org.springframework.security.web.DefaultSecurityFilterChain - Creating filter chain: Ant [pattern='/resources/**'], []
INFO : org.springframework.security.web.DefaultSecurityFilterChain - Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher#1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#70012279, org.springframework.security.web.context.SecurityContextPersistenceFilter#69061fc0, org.springframework.security.web.header.HeaderWriterFilter#12139505, org.springframework.security.web.csrf.CsrfFilter#5a005b47, org.springframework.security.web.authentication.logout.LogoutFilter#3170938b, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#4946d531, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#5a45ee51, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#27698887, org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter#61a3002, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#5a7e6f61, org.springframework.security.web.session.SessionManagementFilter#58c11f65, org.springframework.security.web.access.ExceptionTranslationFilter#18b43f5, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#4986e68]
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 4999 ms
Nov 24, 2016 5:04:08 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcher'
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'dispatcher': initialization started
INFO : org.springframework.web.context.support.AnnotationConfigWebApplicationContext - Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Thu Nov 24 05:04:08 IST 2016]; parent: Root WebApplicationContext
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'dispatcher': initialization completed in 212 ms
Nov 24, 2016 5:04:08 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8090"]
Nov 24, 2016 5:04:08 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8099"]
Nov 24, 2016 5:04:08 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 23694 ms
I had the same problem like you have. Now, I found the cause. You are including csrf token control in spring security configuration. That's why, you need to add csrf token as input in your connectTwitter view file.

Spring MVC Rest API not working when implementing InitializingBean

I have a basic API setup with Spring MVC Rest as following.
public abstract class AbstractApi implements InitializingBean {
#Autowired
protected ValidatorFactory validatorFactory;
/* ... */
#Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(validatorFactory);
}
}
#Controller
#RequestMapping("books")
public class BookApi extends AbstractApi {
private final BookRepository bookRepository;
#Autowired
public BookApi(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
#RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Book> getBooks() {
return new ResponseEntity<>(bookRepository.findAll(), HttpStatus.OK);
}
}
The server returns 404 - Not Found if I send GET /books request with above configuration.
But, if I make AbstractApi un-implement InitializingBean, it works fine. Also, annotating #PostConstruct to afterPropertiesSet() instead of implementing InitializingBean works.
Why is Spring #Controller API not working when implementing InitializingBean?
Your code looks correct. I tested in on my own and everything works as expected. What I'm suggesting is to remove #Autowired ValidatorFactory in AbstractApi class just for testing purpose. Implementing InitializingBean is not related to the request mapping handler mapping. My working code is:
public abstract class AbstractApi implements InitializingBean {
#Override
public void afterPropertiesSet() throws Exception {
System.out.println("after properties set");
}
}
and my controller
#Controller
#RequestMapping("books")
public class BooksController extends AbstractApi {
#RequestMapping(method = RequestMethod.GET)
public ResponseEntity<String> getBooks() {
return new ResponseEntity<>("", HttpStatus.OK);
}
}
and starting log from tomcat:
2016-01-28 16:48:03.141 INFO 2238 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-01-28 16:48:03.317 INFO 2238 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2016-01-28 16:48:03.329 INFO 2238 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.0.23
2016-01-28 16:48:03.405 INFO 2238 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2016-01-28 16:48:03.405 INFO 2238 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1815 ms
2016-01-28 16:48:03.512 INFO 2238 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2016-01-28 16:48:03.515 INFO 2238 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
after properties set
Your current #RequestMapping("books") path is incorrectly specified. When running locally on port 8080 looks like http://localhost:8080books
and should be #RequestMapping("/books") - http://localhost:8080/books
give that a try.

HttpRequestMethodNotSupportedException: Request method 'POST' not supported

Creating a unit test with MockMvc I am running into:
HttpRequestMethodNotSupportedException: Request method 'POST' not supported
Which causes the test case to fail expecting a '200' but getting a '405'. Some of the additional things you may see in the Junit are for Spring Rest Docs and can be ignored. Such as the #Rule or the .andDo() on the mockMvc Call. I have followed the following documentation Spring Rest Docs - Path Parameter and cannot seem to get it working.
Here is the Controller:
#RestController("/transferObjects")
public class TransferObjectController {
#RequestMapping(method=RequestMethod.GET, produces="application/json")
public List<TransferObject> getTransferObjects(){
// do some magic
return null;
}
#RequestMapping(value = "/{name}", method=RequestMethod.POST)
#ResponseStatus(HttpStatus.OK)
public void addTransferObject(#PathVariable("name")String name){
// do magic
}
#RequestMapping(value = "/{name}", method=RequestMethod.DELETE)
#ResponseStatus(HttpStatus.OK)
public void deleteTransferObject(#PathVariable("name")String name){
// do magic
}
Here is the Junit Class:
public class TransferObjectControllerTest {
#Rule
public RestDocumentation restDocumentation = new RestDocumentation("target/generated-snippets");
private MockMvc mockMvc;
#Before
public void setUp() throws Exception {
this.mockMvc = MockMvcBuilders.standaloneSetup(new TransferObjectController())
.apply(documentationConfiguration(this.restDocumentation))
.build();
}
#Test
public void testAddTransferObject() throws Exception {
this.mockMvc.perform(post("/transferObjects/{name}", "hi"))
.andExpect(status().isOk()).andDo(document("transferObject",
pathParameters(
parameterWithName("name").description("The name of the new Transfer Object to be created."))));
}
And here is the console while running the test:
11:20:48.148 [main] INFO o.s.w.s.m.m.a.RequestMappingHandlerAdapter - Looking for #ControllerAdvice: org.springframework.test.web.servlet.setup.StubWebApplicationContext#5ab785fe
11:20:48.205 [main] DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Looking for exception mappings: org.springframework.test.web.servlet.setup.StubWebApplicationContext#5ab785fe
11:20:48.283 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Initializing servlet ''
11:20:48.307 [main] DEBUG o.s.w.c.s.StandardServletEnvironment - Adding [servletConfigInitParams] PropertySource with lowest search precedence
11:20:48.307 [main] DEBUG o.s.w.c.s.StandardServletEnvironment - Adding [servletContextInitParams] PropertySource with lowest search precedence
11:20:48.312 [main] DEBUG o.s.w.c.s.StandardServletEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
11:20:48.312 [main] DEBUG o.s.w.c.s.StandardServletEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
11:20:48.313 [main] DEBUG o.s.w.c.s.StandardServletEnvironment - Initialized StandardServletEnvironment with PropertySources [servletConfigInitParams,servletContextInitParams,systemProperties,systemEnvironment]
11:20:48.313 [main] INFO o.s.mock.web.MockServletContext - Initializing Spring FrameworkServlet ''
11:20:48.313 [main] INFO o.s.t.w.s.TestDispatcherServlet - FrameworkServlet '': initialization started
11:20:48.318 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Unable to locate MultipartResolver with name 'multipartResolver': no multipart request handling provided
11:20:48.318 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Using LocaleResolver [org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver#63238bf4]
11:20:48.318 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Using ThemeResolver [org.springframework.web.servlet.theme.FixedThemeResolver#32b97305]
11:20:48.319 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Using RequestToViewNameTranslator [org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator#2d2e6747]
11:20:48.319 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Using FlashMapManager [org.springframework.web.servlet.support.SessionFlashMapManager#417e7d7d]
11:20:48.319 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Published WebApplicationContext of servlet '' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.]
11:20:48.319 [main] INFO o.s.t.w.s.TestDispatcherServlet - FrameworkServlet '': initialization completed in 6 ms
11:20:48.319 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Servlet '' configured successfully
11:20:48.361 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - DispatcherServlet with name '' processing POST request for [/transferObjects/hi]
11:20:48.364 [main] DEBUG o.s.t.w.s.s.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Looking up handler method for path /transferObjects/hi
11:20:48.368 [main] DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported
11:20:48.369 [main] DEBUG o.s.w.s.m.a.ResponseStatusExceptionResolver - Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported
11:20:48.369 [main] DEBUG o.s.w.s.m.s.DefaultHandlerExceptionResolver - Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported
11:20:48.369 [main] WARN o.s.web.servlet.PageNotFound - Request method 'POST' not supported
11:20:48.370 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Null ModelAndView returned to DispatcherServlet with name '': assuming HandlerAdapter completed request handling
11:20:48.370 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Successfully completed request
It appears I was able to fix this problem.
Taking a closer look at the console while running the test I noticed:
Mapped "{[],methods=[GET],produces=[application/json]}" onto public java.util.List<common.to.TransferObject> sf.common.controller.TransferObjectController.getTransferObjects()
Mapped "{[/{name}],methods=[POST]}" onto public void sf.common.controller.TransferObjectController.addTransferObject(java.lang.String)
Mapped "{[/{name}],methods=[DELETE]}" onto public void sf.common.controller.TransferObjectController.deleteTransferObject(java.lang.String)
this shows that it is mapping the controller request mappings to the specific RequestMapping the method holds. #RestController("/transferObjects") is not actually defining the mapping as a parent. For me to do that I must include #RequestMapping("/transferObjects") underneath the #RestController.
So by changing the parent mapping I can now use the following test case:
#Test
public void testAddTransferObject() throws Exception {
this.mockMvc.perform(post("/transferObjects/{name}", "hi"))
.andExpect(status().isOk()).andDo(document("transferObject",
pathParameters(
parameterWithName("name").description("The name of the new Transfer Object to be created."))));
}

Resources