Spring Boot URL path variable encoding - java

I have a Spring boot (v2.3.5.RELEASE) REST API and cannot seem to fix an encoding problem with path variables. I have tried every solution that found online but nothing helped.
Here is the Main class:
#SpringBootApplication
public class RestApplication {
public static void main(String[] args) {
SpringApplication.run(RestApplication.class, args);
}
}
The RestController (the method is never executed when sending the request to that URL):
#RestController
#RequestMapping("/mvn/packages")
public class ModuleApi {
#Autowired
ModuleApiService service;
#GetMapping(value = "/{pkg}/{pkg_ver}/modules/{namespace}/metadata", produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<String> getModuleMetadata(#PathVariable("pkg") String package_name,
#PathVariable("pkg_ver") String package_version,
#PathVariable("namespace") String module_namespace) {
return service.getModuleMetadata(package_name, package_version, module_namespace);
}
}
The Configuration class:
#Configuration
public class CorsConfiguration
{
#Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setForceEncoding(true);
characterEncodingFilter.setEncoding("UTF-8");
registrationBean.setFilter(characterEncodingFilter);
return registrationBean;
}
}
The application.properties:
logging.level.org.springframework.web=DEBUG
server.port=8080
server.tomcat.uri-encoding=UTF-8
server.servlet.encoding.charset=UTF-8
server.servlet.encoding.enabled=true
server.servlet.encoding.force=true
I even added encoding to the spring-boot-maven-plugin in the pom.xml:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.6.RELEASE</version>
<configuration>
<mainClass>RestApplication</mainClass>
<jvmArguments>-Dfile.encoding=UTF8</jvmArguments>
</configuration>
</plugin>
But the result is still the same.
When sending a request to http://localhost:8080/mvn/packages/junit:junit/4.12/%2Fjunit.framework%2FAssert
i.e. mvn/packages/{pkg}/{pkg_ver}/modules/{namespace}/metadata and namespace is encoded, it returns HTTP 400 - BAD REQUEST.
However, when I try http://localhost:8080/mvn/packages/junit:junit/4.12/foo (does not need encoding/decoding), it works.
I also tried using ALLOW_ENCODED_SLASH property. Main class:
#SpringBootApplication
public class RestApplication {
public static void main(String[] args) {
System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true");
SpringApplication.run(RestApplication.class, args);
}
}
But in this case it cannot resolve the request to that mapping and returns 404 - NOT FOUND:
2020-12-10 17:03:27.044 DEBUG 105120 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : GET "/mvn/packages/junit:junit/4.12/%2Fjunit.framework%2FAssert", parameters={}
2020-12-10 17:03:27.053 DEBUG 105120 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2020-12-10 17:03:27.056 DEBUG 105120 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found
2020-12-10 17:03:27.056 DEBUG 105120 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed 404 NOT_FOUND
2020-12-10 17:03:27.060 DEBUG 105120 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for GET "/error", parameters={}
2020-12-10 17:03:27.062 DEBUG 105120 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
2020-12-10 17:03:27.083 DEBUG 105120 --- [nio-8080-exec-1] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, text/html;q=0.8]
2020-12-10 17:03:27.087 DEBUG 105120 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 404
Can anyone help me please?

Related

Spring Boot permitAll not working in WebSecurityConfigurerAdapter

When I POST to /api/v1/auth/register, I get a 403 response generated by the configured accessDeniedHandler. However, I'm expecting this request to be permitted as it's covered by permitAll() and precedes anyRequest().authenticated().
Requests such as GET /api/v1/reference/countries work just fine. Also, my integration tests that hit these /api/v1/auth/** endpoints also work, which suggests something to do with CORS, although the preflight request is 200.
Any idea what's wrong with this security configuration?
#Configuration
#EnableGlobalMethodSecurity(
prePostEnabled = true,
securedEnabled = true,
jsr250Enabled = true
)
#Order(1)
#RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final UserDetailsServiceImpl userDetailsService;
private final Config config;
private final ObjectMapper objectMapper;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.authorizeRequests()
.antMatchers(
"/api/v1/auth/register",
"/api/v1/auth/register/check",
"/api/v1/auth/register/activate",
"/api/v1/auth/password/update",
"/api/v1/auth/recover",
"/api/v1/auth/recover/check",
"/api/v1/auth/recover/reset",
"/api/v1/csrf-token",
"/api/v1/reference/**"
)
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.successHandler((request, response, authentication) -> {
response.getWriter().append("OK");
response.setStatus(HttpServletResponse.SC_OK);
})
.failureHandler((request, response, exception) -> {
response.getWriter().append("Invalid credentials or inactive account");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
})
.loginProcessingUrl("/api/v1/auth/login")
.permitAll()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/api/v1/auth/logout", "POST"))
.permitAll()
.and()
.exceptionHandling()
.accessDeniedHandler((request, response, accessDeniedException) -> {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
objectMapper.writeValue(
response.getWriter(),
ErrorResponseBody
.builder()
.code(ErrorType.ACCESS_DENIED)
.status(HttpServletResponse.SC_FORBIDDEN)
.message("Access denied")
.build()
);
})
.authenticationEntryPoint((request, response, authException) -> {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
objectMapper.writeValue(
response.getWriter(),
ErrorResponseBody
.builder()
.code(ErrorType.LOGIN_REQUIRED)
.status(HttpServletResponse.SC_UNAUTHORIZED)
.message("You are not authorized to access this resource")
.build()
);
})
.and()
.userDetailsService(userDetailsService);
if (config.isCsrfDisabled()) {
http
.csrf()
.disable();
}
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public CorsConfigurationSource corsConfigurationSource() {
final var configuration = new CorsConfiguration();
configuration.setAllowCredentials(true);
configuration.setAllowedOrigins(config.getAllowedOrigins());
configuration.setAllowedMethods(asList("GET", "POST", "PUT", "PATCH", "DELETE"));
configuration.setAllowedHeaders(Arrays.asList(HttpHeaders.AUTHORIZATION, HttpHeaders.CACHE_CONTROL, HttpHeaders.CONTENT_TYPE, HttpHeaders.ACCEPT));
final var source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/api/**", configuration);
return source;
}
}
Here's my CORS config:
#Configuration
#RequiredArgsConstructor(onConstructor = #__(#Autowired))
public class WebConfig {
private final Config config;
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
#Override
public void addCorsMappings(CorsRegistry registry) {
final var allowedOrigins = Optional
.ofNullable(config.getAllowedOrigins())
.map(origins -> origins.toArray(new String[]{}))
.orElse(new String[]{});
System.out.println("Enabling CORS for the following origins:" + Arrays.asList(allowedOrigins).toString());
registry
.addMapping("/api/**")
.allowedOrigins(allowedOrigins)
.allowCredentials(true)
.allowedMethods("*")
.allowedHeaders("*");
}
};
}
}
I'm invoking these endpoints from http://localhost:3000, which is one of the items returned by config.getAllowedOrigins().
Here's the Spring Security debug logging from the request:
2020-11-24 06:51:16.110 INFO 1 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-11-24 06:51:16.112 INFO 1 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-11-24 06:51:16.158 INFO 1 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 44 ms
2020-11-24 06:51:16.193 DEBUG 1 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : /api/v1/auth/register at position 1 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2020-11-24 06:51:16.200 DEBUG 1 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : /api/v1/auth/register at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2020-11-24 06:51:16.205 DEBUG 1 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
2020-11-24 06:51:16.206 DEBUG 1 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created.
2020-11-24 06:51:16.214 DEBUG 1 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : /api/v1/auth/register at position 3 of 13 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2020-11-24 06:51:16.217 DEBUG 1 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : /api/v1/auth/register at position 4 of 13 in additional filter chain; firing Filter: 'CorsFilter'
2020-11-24 06:51:16.286 DEBUG 1 --- [nio-8080-exec-1] o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#461bbc94
2020-11-24 06:51:16.290 DEBUG 1 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2020-11-24 06:51:16.299 DEBUG 1 --- [nio-8080-exec-1] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
2020-11-24 06:51:16.483 DEBUG 1 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /api/v1/auth/register at position 1 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2020-11-24 06:51:16.485 DEBUG 1 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /api/v1/auth/register at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2020-11-24 06:51:16.486 DEBUG 1 --- [nio-8080-exec-2] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
2020-11-24 06:51:16.487 DEBUG 1 --- [nio-8080-exec-2] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created.
2020-11-24 06:51:16.488 DEBUG 1 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /api/v1/auth/register at position 3 of 13 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2020-11-24 06:51:16.489 DEBUG 1 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /api/v1/auth/register at position 4 of 13 in additional filter chain; firing Filter: 'CorsFilter'
2020-11-24 06:51:16.494 DEBUG 1 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /api/v1/auth/register at position 5 of 13 in additional filter chain; firing Filter: 'CsrfFilter'
2020-11-24 06:51:16.525 DEBUG 1 --- [nio-8080-exec-2] o.s.security.web.csrf.CsrfFilter : Invalid CSRF token found for http://dev.api.example.com/api/v1/auth/register
2020-11-24 06:51:16.609 DEBUG 1 --- [nio-8080-exec-2] o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#461bbc94
2020-11-24 06:51:16.610 DEBUG 1 --- [nio-8080-exec-2] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2020-11-24 06:51:16.615 DEBUG 1 --- [nio-8080-exec-2] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
Disable CSRF using .csrf().disable() in configure(HttpSecurity http) More deatils are explained here
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
... // other configurations
}

'Consumes' defaults to 'application/octet-stream' on Spring Boot RequestMapping, null when set

I'm attempting to create a simple Post request handler in Spring Boot that consumes JSON.
#RestController
#EnableWebMvc
public class WebFormController
{
#RequestMapping(path="/process-contact-form", method = RequestMethod.POST)
public ResponseEntity<String> processContact(#RequestBody Form form) throws Exception
{
System.out.println("TEST TEST: Ran");
return new ResponseEntity<String>("Thank you for contacting us, we'll respond soon.", HttpStatus.OK);
}
}
By default, my understanding is this will consume application/json.
However, when I make a request using curl or Postman, I get this response from Spring...
DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream' not supported
And in Postman I get '415 Unsupported Media Type'.
If I explicitly define the 'consumes' property...
#RequestMapping(path="/process-contact-form", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
Spring Boot returns this...
DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type '' not supported
I've tried setting consumes to "application/json", x-www-form-urlencoded, and plain text and sending those types of requests from Postman, but I get the same results.
I built this off aws-serverless-java-container https://github.com/awslabs/aws-serverless-java-container/wiki/Quick-start---Spring-Boot and I'm running it from the SAM local CLI.
EDIT
I switched logging to DEBUG to get more details...
2020-05-08 17:53:40.692 DEBUG 1 --- [ main] s.b.w.s.f.OrderedCharacterEncodingFilter : Filter 'characterEncodingFilter' configured for use
2020-05-08 17:53:40.692 DEBUG 1 --- [ main] c.a.s.p.i.servlet.FilterChainHolder : Starting REQUEST: filter 0-characterEncodingFilter
2020-05-08 17:53:40.698 DEBUG 1 --- [ main] c.a.s.p.i.s.AwsProxyHttpServletRequest : Called set character encoding to UTF-8 on a request without a content type. Character encoding will not be set
2020-05-08 17:53:40.698 DEBUG 1 --- [ main] c.a.s.p.i.servlet.FilterChainHolder : Starting REQUEST: filter 2-com.amazonaws.serverless.proxy.internal.servlet.FilterChainManager$ServletExecutionFilter
2020-05-08 17:53:40.729 DEBUG 1 --- [ main] o.s.web.servlet.DispatcherServlet : POST "/process-contact-form", parameters={}
2020-05-08 17:53:40.732 DEBUG 1 --- [ main] c.a.s.p.i.servlet.AwsHttpServletRequest : Trying to access session. Lambda functions are stateless and should not rely on the session
2020-05-08 17:53:40.758 DEBUG 1 --- [ main] c.a.s.p.i.s.AwsHttpServletResponse : Response buffer flushed with 0 bytes, latch=1
2020-05-08 17:53:40.761 WARN 1 --- [ main] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type '' not supported]
2020-05-08 17:53:40.761 DEBUG 1 --- [ main] o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 415
2020-05-08 17:53:40.763 DEBUG 1 --- [ main] c.a.s.p.i.servlet.AwsHttpServletRequest : Trying to access session. Lambda functions are stateless and should not rely on the session
2020-05-08 17:53:40.768 DEBUG 1 --- [ main] c.a.s.p.i.servlet.FilterChainHolder : Executed ERROR: filter 3-com.amazonaws.serverless.proxy.internal.servlet.FilterChainManager$ServletExecutionFilter
2020-05-08 17:53:40.769 DEBUG 1 --- [ main] c.a.s.p.i.servlet.FilterChainHolder : Executed ERROR: filter 3-characterEncodingFilter
2020-05-08 17:53:40.779 INFO 1 --- [ main] c.a.s.p.internal.LambdaContainerHandler : 127.0.0.1:56893 null- null [08/05/2020:17:53:40Z] "POST /process-contact-form null" 415 - "-" "-" combined
2020-05-08 17:53:40.818 DEBUG 1 --- [ main] s.n.www.protocol.http.HttpURLConnection : sun.net.www.MessageHeader#c9d82f99 pairs: {POST /2018-06-01/runtime/invocation/807c7e06-86f6-1bd3-1055-78b464604573/response HTTP/1.1: null}{Docker-Lambda-Invoke-Wait: 1588960412475}{Docker-Lambda-Init-End: 1588960420587}{User-Agent: Java/1.8.0_201}{Host: 127.0.0.1:9001}{Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2}{Connection: keep-alive}{Content-type: application/x-www-form-urlencoded}{Content-Length: 104}
2020-05-08 17:53:40.822 DEBUG 1 --- [ main] s.n.www.protocol.http.HttpURLConnection : sun.net.www.MessageHeader#6f0129144 pairs: {null: HTTP/1.1 202 Accepted}{Content-Type: application/json}{Date: Fri, 08 May 2020 17:53:40 GMT}{Transfer-Encoding: chunked}
2020-05-08 17:53:40.825 DEBUG 1 --- [ main] s.n.www.protocol.http.HttpURLConnection : sun.net.www.MessageHeader#18fdb6cf5 pairs: {GET /2018-06-01/runtime/invocation/next HTTP/1.1: null}{User-Agent: Java/1.8.0_201}{Host: 127.0.0.1:9001}{Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2}{Connection: keep-alive}
EDIT
StreamLambdaHandler
public class StreamLambdaHandler implements RequestStreamHandler {
private static SpringBootLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> handler;
static {
try {
handler = SpringBootLambdaContainerHandler.getAwsProxyHandler(Application.class);
} catch (ContainerInitializationException e) {
// if we fail here. We re-throw the exception to force another cold start
e.printStackTrace();
throw new RuntimeException("Could not initialize Spring Boot application", e);
}
}
#Override
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context)
throws IOException {
System.out.println("TEST TEST " + inputStream.toString() + " " + outputStream.toString());
handler.proxyStream(inputStream, outputStream, context);
}
}
I had some assistance starting the app from scratch, and using different libraries. The annotation looks like this now..
#Path("/submit")
#Component
#Slf4j
public class SubmitController {
private JiraService jira;
private ConfigurationRepository configurations;
#Autowired
public SubmitController(JiraService jira, ConfigurationRepository configurations) {
this.jira = jira;
this.configurations = configurations;
}
#POST
#Path("/{id}")
#AnonymousAllowed
#Produces({APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response submitForm(#PathParam("id") String id, String body) {
// Stuff
}

Demo Spring Boot application for REST apis for CRUD operation throws 404 not found error

I'm trying to write a basic application with rest api's connecting with a postgres database to perform couple of crud operations. When I run the application it starts successfully. But when I go to the url "http://localhost:8080/employees" or http://localhost:8080", it shows "This localhost page can’t be found. No webpage was found for the web address: http://localhost:8080/employees. HTTP ERROR 404".
Here is my TestApplication.java
package com.ranjana.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.http.HttpStatus;
#SpringBootApplication
#EntityScan(basePackages = {"com.ranjana.test.model"})
#ComponentScan(basePackageClasses = EmployeeController.class)
public class TestApplication implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
#Override
public void customize(ConfigurableServletWebServerFactory factory) {
factory.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN, "/errors/403.html"));
factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/errors/404.html"));
factory.addErrorPages(new ErrorPage("/errors/500.html"));
}
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
The controller class - EmployeeController.java :
package com.ranjana.test.controller;
import com.ranjana.test.repositoy.EmployeeRepo;
import com.ranjana.test.exception.ResourceNotFoundException;
import com.ranjana.test.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
#RestController
#RequestMapping("/api/v1")
public class EmployeeController {
#Autowired
private EmployeeRepo empRepo;
#GetMapping("/employees")
public List<Employee> getAllEmployees(){
System.out.printf(empRepo.findAll().toString());
return empRepo.findAll();
}
#GetMapping("/employee/{id}")
public ResponseEntity<Employee> getUsersById(#PathVariable(value = "id") Long emplId)
throws ResourceNotFoundException {
Employee employee = empRepo.findById(emplId).orElseThrow(() -> new ResourceNotFoundException("Employee not found for id: " + emplId));
return ResponseEntity.ok().body(employee);
}
#PostMapping("/employees")
public Employee createEmployee(#Valid #RequestBody Employee employee){
System.out.println(employee.toString());
return empRepo.save(employee);
}
#PutMapping("/employee/{id}")
public ResponseEntity<Employee> updateEmployee(#PathVariable(value = "id") Long emplId, #Valid #RequestBody Employee empDetails)
throws ResourceNotFoundException{
Employee employee = empRepo.findById(emplId).orElseThrow(() -> new ResourceNotFoundException("Employee not found for id: " + emplId ));
employee.setFirstName(empDetails.getFirstName());
employee.setLastName(empDetails.getLastName());
employee.setEmailId(empDetails.getEmailId());
employee.setContactNumber(empDetails.getContactNumber());
employee.setUpdateDateTime(new Date());
final Employee updatedEmployee = empRepo.save(employee);
return ResponseEntity.ok(updatedEmployee);
}
#DeleteMapping("/employee/{id}")
public Map<String, Boolean> deleteEmployee(#PathVariable(value = "id") Long emplId)
throws Exception{
Employee employee = empRepo.findById(emplId).orElseThrow(() -> new ResourceNotFoundException("Employee not found for id: " + emplId));
empRepo.delete(employee);
Map <String, Boolean> response= new HashMap<>();
response.put("Deleted", Boolean.TRUE);
return response;
}
}
The model - Employee.java:
package com.ranjana.test.model;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import javax.persistence.*;
import java.util.Date;
#Entity
#Table(name = "employee")
public class Employee {
//Employee Id
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
//Employee First Name
#Column(name = "first_name", nullable = false)
private String firstName;
//Employee Last Name
#Column(name = "last_name", nullable = false)
private String lastName;
//Employee Email Address
#Column(name = "email", nullable = true)
private String emailId;
//Employee Contact Number
#Column(name = "contact_number", nullable = true)
private String contactNumber;
//Creation Timestamp
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "create_date_time", nullable = false)
private Date createDateTime;
//Update Timestamp
#UpdateTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "update_date_time", nullable = true)
private Date updateDateTime;
//Getters and Setters
#Override
public String toString(){
return "Employee{"
+ "id = " + id + '\''
+ "firstName" + firstName + '\''
+ "lastName" + lastName + '\''
+ "email" + emailId + '\''
+ "phone" + contactNumber + '\''
+ "createDateTime" + createDateTime + '\''
+ "updateDateTime" + updateDateTime + '\''
+ "}";
}
}
The console looks like following:
2019-08-05 13:27:18.327 INFO 9943 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2019-08-05 13:27:18.332 INFO 9943 --- [ restartedMain] com.ranjana.test.TestApplication : Started TestApplication in 3.678 seconds (JVM running for 9.357)
2019-08-05 13:27:18.340 DEBUG 9943 --- [ restartedMain] o.s.boot.devtools.restart.Restarter : Creating new Restarter for thread Thread[main,5,main]
2019-08-05 13:27:18.340 DEBUG 9943 --- [ restartedMain] o.s.boot.devtools.restart.Restarter : Immediately restarting application
2019-08-05 13:27:18.340 DEBUG 9943 --- [ restartedMain] o.s.boot.devtools.restart.Restarter : Created RestartClassLoader org.springframework.boot.devtools.restart.classloader.RestartClassLoader#51171eea
2019-08-05 13:27:18.340 DEBUG 9943 --- [ restartedMain] o.s.boot.devtools.restart.Restarter : Starting application com.ranjana.test.TestApplication with URLs [file:/Users/ranjanasinha/ransinha/test/target/classes/]
2019-08-05 13:27:18.714 DEBUG 9943 --- [2)-10.36.30.147] o.s.jdbc.core.JdbcTemplate : Executing SQL query [SELECT 1]
2019-08-05 13:27:18.714 INFO 9943 --- [3)-10.36.30.147] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-08-05 13:27:18.714 INFO 9943 --- [3)-10.36.30.147] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2019-08-05 13:27:18.715 DEBUG 9943 --- [3)-10.36.30.147] o.s.web.servlet.DispatcherServlet : Detected StandardServletMultipartResolver
2019-08-05 13:27:18.724 DEBUG 9943 --- [3)-10.36.30.147] o.s.web.servlet.DispatcherServlet : enableLoggingRequestDetails='false': request parameters and headers will be masked to prevent unsafe logging of potentially sensitive data
2019-08-05 13:27:18.724 INFO 9943 --- [3)-10.36.30.147] o.s.web.servlet.DispatcherServlet : Completed initialization in 9 ms
2019-08-05 13:27:31.581 DEBUG 9943 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : GET "/employees", parameters={}
2019-08-05 13:27:31.587 DEBUG 9943 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2019-08-05 13:27:31.591 DEBUG 9943 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found
2019-08-05 13:27:31.591 DEBUG 9943 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed 404 NOT_FOUND
2019-08-05 13:27:31.599 DEBUG 9943 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for GET "/errors/404.html", parameters={}
2019-08-05 13:27:31.601 DEBUG 9943 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2019-08-05 13:27:31.602 DEBUG 9943 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found
2019-08-05 13:27:31.602 DEBUG 9943 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 404
2019-08-05 13:27:35.827 DEBUG 9943 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : GET "/", parameters={}
2019-08-05 13:27:35.830 DEBUG 9943 --- [nio-8080-exec-2] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2019-08-05 13:27:35.830 DEBUG 9943 --- [nio-8080-exec-2] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found
2019-08-05 13:27:35.830 DEBUG 9943 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed 404 NOT_FOUND
2019-08-05 13:27:35.831 DEBUG 9943 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for GET "/errors/404.html", parameters={}
2019-08-05 13:27:35.833 DEBUG 9943 --- [nio-8080-exec-2] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2019-08-05 13:27:35.834 DEBUG 9943 --- [nio-8080-exec-2] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found
2019-08-05 13:27:35.834 DEBUG 9943 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 404
2019-08-05 13:27:38.056 DEBUG 9943 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : GET "/", parameters={}
2019-08-05 13:27:38.058 DEBUG 9943 --- [nio-8080-exec-3] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2019-08-05 13:27:38.058 DEBUG 9943 --- [nio-8080-exec-3] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found
2019-08-05 13:27:38.058 DEBUG 9943 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : Completed 404 NOT_FOUND
2019-08-05 13:27:38.059 DEBUG 9943 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for GET "/errors/404.html", parameters={}
2019-08-05 13:27:38.060 DEBUG 9943 --- [nio-8080-exec-3] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2019-08-05 13:27:38.062 DEBUG 9943 --- [nio-8080-exec-3] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found
2019-08-05 13:27:38.062 DEBUG 9943 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 404
I'm new to spring boot. Please help me figure out what I'm missing.
Also the table got created. And I checked with manually putting data in the table, still the 404 not found error is showing. Thanks in advance.
You should call like http://localhost:8080/api/v1/employees
Because you have created requestmapping("API/v1")

Spring Security custom login page with multiple Thymleaf ViewResolvers

I have searched and searched and can not find anything. I working on a PoC for a corp project using spring boot, thyme leaf, spring security.
If I set login page in spring security config like
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasAnyRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage ("/login")
.permitAll().defaultSuccessUrl ("/home")
.and()
.logout()
.permitAll();
}
and in my login page (HTML) I pass:
....
<link rel="stylesheet" type="text/css" href="/styles.css" />
....
simple css file:
#test {
font-family: Arial, sans-serif;
padding-left: 1em;
background-color: /*[[${backgroundColor}]]*/ pink !important;
}
I get log:
2017-06-28 21:50:29.436 INFO 24430 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 12 ms
2017-06-28 21:50:29.436 DEBUG 24430 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Servlet 'dispatcherServlet' configured successfully
2017-06-28 21:50:29.476 DEBUG 24430 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/login]
2017-06-28 21:50:29.477 DEBUG 24430 --- [nio-8080-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /login
2017-06-28 21:50:29.492 DEBUG 24430 --- [nio-8080-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public java.lang.String sample.multimodule.generic.web.login.login(org.springframework.ui.Model)]
2017-06-28 21:50:29.492 DEBUG 24430 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/login] is: -1
2017-06-28 21:50:29.505 DEBUG 24430 --- [nio-8080-exec-2] o.s.w.s.v.ContentNegotiatingViewResolver : Requested media types are [text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8] based on Accept header types and producible media types [*/*])
2017-06-28 21:50:29.509 DEBUG 24430 --- [nio-8080-exec-2] o.s.w.servlet.view.BeanNameViewResolver : Found matching bean for view name 'login' - to be ignored since it does not implement View
2017-06-28 21:50:29.510 DEBUG 24430 --- [nio-8080-exec-2] o.s.w.s.v.ContentNegotiatingViewResolver : Returning [org.thymeleaf.spring4.view.ThymeleafView#5d886361] based on requested media type 'text/html'
2017-06-28 21:50:29.511 DEBUG 24430 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Rendering view [org.thymeleaf.spring4.view.ThymeleafView#5d886361] in DispatcherServlet with name 'dispatcherServlet'
2017-06-28 21:50:29.776 DEBUG 24430 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Successfully completed request
2017-06-28 21:50:29.798 DEBUG 24430 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/login]
2017-06-28 21:50:29.798 DEBUG 24430 --- [nio-8080-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /login
2017-06-28 21:50:29.799 DEBUG 24430 --- [nio-8080-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public java.lang.String sample.multimodule.generic.web.login.login(org.springframework.ui.Model)]
2017-06-28 21:50:29.799 DEBUG 24430 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/login] is: -1
2017-06-28 21:50:29.799 DEBUG 24430 --- [nio-8080-exec-4] o.s.w.s.v.ContentNegotiatingViewResolver : Requested media types are [text/css, */*;q=0.1] based on Accept header types and producible media types [*/*])
2017-06-28 21:50:29.800 DEBUG 24430 --- [nio-8080-exec-4] o.s.w.servlet.view.BeanNameViewResolver : Found matching bean for view name 'login' - to be ignored since it does not implement View
2017-06-28 21:50:29.800 DEBUG 24430 --- [nio-8080-exec-4] o.s.w.servlet.view.BeanNameViewResolver : No matching bean found for view name 'login.css'
2017-06-28 21:50:29.800 DEBUG 24430 --- [nio-8080-exec-4] o.s.w.s.v.ContentNegotiatingViewResolver : Returning [org.thymeleaf.spring4.view.ThymeleafView#34f7b639] based on requested media type 'text/css'
2017-06-28 21:50:29.800 DEBUG 24430 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : Rendering view [org.thymeleaf.spring4.view.ThymeleafView#34f7b639] in DispatcherServlet with name 'dispatcherServlet'
2017-06-28 21:50:29.819 ERROR 24430 --- [nio-8080-exec-4] org.thymeleaf.TemplateEngine : [THYMELEAF][http-nio-8080-exec-4] Exception processing template "login [text/html]": An error happened during template parsing (template: "class path resource [templates/css/login]")
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/css/login]")
at org.thymeleaf.templateparser.text.AbstractTextTemplateParser.parse(AbstractTextTemplateParser.java:174) ~[thymeleaf-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.thymeleaf.templateparser.text.AbstractTextTemplateParser.parseStandalone(AbstractTextTemplateParser.java:92) ~[thymeleaf-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:666) ~[thymeleaf-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098) [thymeleaf-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1072) [thymeleaf-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.thymeleaf.spring4.view.ThymeleafView.renderFragment(ThymeleafView.java:335) [thymeleaf-spring4-3.0.5.RELEASE.jar:3.0.5.RELEASE]
...
...
I have ThymeleafConfig:
#Configuration
#ConditionalOnClass({SpringTemplateEngine.class})
public class ThymeleafConfig extends WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter implements ApplicationContextAware {
private ApplicationContext applicationContext;
private static final String UTF8 = "UTF-8";
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
private TemplateEngine templateEngine(ITemplateResolver templateResolver) {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setTemplateResolver(templateResolver);
return engine;
}
#Bean
public ViewResolver htmlViewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setOrder (0);
resolver.setTemplateEngine(templateEngine(htmlTemplateResolver ()));
resolver.setCharacterEncoding(UTF8);
resolver.setContentType("text/html");
return resolver;
}
private ITemplateResolver htmlTemplateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setOrder (0);
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("classpath:/templates/");
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
resolver.setCacheable(false);
return resolver;
}
#Bean
public ViewResolver cssViewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setOrder (10);
resolver.setTemplateEngine(templateEngine(cssTemplateResolver ()));
resolver.setCharacterEncoding(UTF8);
resolver.setContentType("text/css");
return resolver;
}
private ITemplateResolver cssTemplateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setOrder (10);
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("classpath:/templates/css/");
resolver.setSuffix("");
resolver.setTemplateMode(TemplateMode.CSS);
resolver.setCacheable(false);
return resolver;
}
#Bean
public ViewResolver jsViewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setOrder (20);
resolver.setTemplateEngine(templateEngine(jsTemplateResolver ()));
resolver.setCharacterEncoding(UTF8);
resolver.setContentType("application/javascript");
return resolver;
}
private ITemplateResolver jsTemplateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setOrder (20);
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("classpath:/templates/js/");
resolver.setSuffix("");
resolver.setTemplateMode(TemplateMode.JAVASCRIPT);
resolver.setCacheable(false);
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
And a Css Controller:
#Controller
public class CssController {
#RequestMapping (value = "/styles.css")
public String mainStyles(Model model, HttpServletResponse response) {
model.addAttribute("backgroundColor", "blue");
return "styles.css";
}
}
If I remove
....formLogin().loginPage ("/home")
from Security config and get it in controller as normal, it works, and the variables are added into the css file as I expect.
Any ideas of why I get this problem when directing to /login from within Spring Security?
*note first time posting, so apologize if in proper format.
Found where the issue was, wasn't permitting access to the file when using security.
Needed to add following to security config:
...
.antMatchers ("/styles.css").permitAll ()
...

Spring boot UrlFilenameViewController not working

I am trying to route a view when I request a specific URL without any Model, so i am using the URLFileNameController to do that, below is my main class and bean declaration for the same.
#SpringBootApplication
public class WebMvcApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(CpiWebMvcApplication.class);
}
public static void main(String[] args)
{
ApplicationContext ctx =SpringApplication.run(CpiWebMvcApplication.class, args);
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames)
{
System.out.println(beanName);
}
}
}
//Bean Declaration -- declared in a separate class
#Configuration
//#ImportResource("*/**/Controller-Beans.xml")
public class BeanConfig {
#Bean
public InternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
return viewResolver;
}
#Bean(name = "urlViewController")
public UrlFilenameViewController getUrlViewController() {
UrlFilenameViewController urlViewController = new UrlFilenameViewController();
urlViewController.setSuffix(".jsp");
urlViewController.setPrefix("/WEB-INF/");
urlViewController.setAlwaysUseFullPath(true);
return urlViewController;
}
#Bean
public SimpleUrlHandlerMapping getUrlHandlerMapping() {
SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
Properties mappings = new Properties();
mappings.put("*.do", getUrlViewController());
handlerMapping.setMappings(mappings);
return handlerMapping;
}
#Bean
public DispatcherServlet dispatcherServlet() {
return new DispatcherServlet();
}
/**
* Register dispatcherServlet programmatically
*
* #return ServletRegistrationBean
*/
#Bean
public ServletRegistrationBean dispatcherServletRegistration() {
ServletRegistrationBean registration = new ServletRegistrationBean(
dispatcherServlet());
registration.addUrlMappings("*.do");
registration
.setName(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
registration.setLoadOnStartup(-1);
return registration;
}
When I run my spring boot app, I get the following:
2017-01-04 10:43:04.806 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing servlet 'dispatcherServletRegistration'
2017-01-04 10:43:04.807 INFO 24728 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServletRegistration'
2017-01-04 10:43:04.807 INFO 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServletRegistration': initialization started
2017-01-04 10:43:04.807 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Using MultipartResolver [org.springframework.web.multipart.support.StandardServletMultipartResolver#7f1abac0]
2017-01-04 10:43:04.817 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Unable to locate LocaleResolver with name 'localeResolver': using default [org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver#621cf3e7]
2017-01-04 10:43:04.830 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Unable to locate ThemeResolver with name 'themeResolver': using default [org.springframework.web.servlet.theme.FixedThemeResolver#41e31325]
2017-01-04 10:43:04.837 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Unable to locate RequestToViewNameTranslator with name 'viewNameTranslator': using default [org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator#46a1a74]
2017-01-04 10:43:04.852 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Unable to locate FlashMapManager with name 'flashMapManager': using default [org.springframework.web.servlet.support.SessionFlashMapManager#56cd7abe]
2017-01-04 10:43:04.852 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Published WebApplicationContext of servlet 'dispatcherServletRegistration' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcherServletRegistration]
2017-01-04 10:43:04.852 INFO 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServletRegistration': initialization completed in 45 ms
2017-01-04 10:43:04.852 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Servlet 'dispatcherServletRegistration' configured successfully
2017-01-04 10:43:04.879 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServletRegistration' processing GET request for [/logout.do]
2017-01-04 10:43:04.894 DEBUG 24728 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /logout.do
2017-01-04 10:43:04.909 DEBUG 24728 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/logout.do]
2017-01-04 10:43:04.909 DEBUG 24728 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Matching patterns for request [/logout.do] are [/**]
2017-01-04 10:43:04.912 DEBUG 24728 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : URI Template variables for request [/logout.do] are {}
2017-01-04 10:43:04.912 DEBUG 24728 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapping [/logout.do] 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#720653c2]]] and 1 interceptor
2017-01-04 10:43:04.912 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/logout.do] is: -1
2017-01-04 10:43:04.917 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServletRegistration': assuming HandlerAdapter completed request handling
2017-01-04 10:43:04.917 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Successfully completed request
The logs clearly states that my app is not able to find the view, but I am not able to understand where i am doing wrong, as when i declared a controller with a mapping, i am able to get the view.
#Controller
public class LoginPageController {
#RequestMapping("/secure/main")
//#ResponseBody
public String getLoginpage(Model model, #RequestParam(value="name", required=false, defaultValue="Uttik") String name)
{
model.addAttribute("name", name);
return "unauth";
}
}
I tried even declaring the beans in xml, still it didnt worked. Any idea where i am doing wrong?
Thanks in advance!!

Categories