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!!
Related
I implemented a simple Spring Boot application using the following classes:
Application Class:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan(basePackageClasses = CustomerController.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Model Class:
public class Customer {
private Long id;
private String Name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
Controller Class:
#RestController
public class CustomerController {
#RequestMapping(name="/customer", method=RequestMethod.GET)
public Customer getCustomer(#RequestParam Long id) {
Customer cust = new Customer();
cust.setId(id);
cust.setName("George");
return cust;
}
#RequestMapping(name="/customer", method=RequestMethod.POST, consumes = "application/json")
public Customer createCustomer(#RequestBody Customer cust) {
return cust;
}
}
The application was initiated as Spring Boot and produced the following logs:
2022-09-14 13:28:17.448 INFO 13564 --- [ main] Application : Starting Application using Java 18 on DESKTOP with PID 13564
2022-09-14 13:28:17.453 INFO 13564 --- [ main] Application : No active profile set, falling back to 1 default profile: "default"
2022-09-14 13:28:18.757 INFO 13564 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-09-14 13:28:18.773 INFO 13564 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-09-14 13:28:18.773 INFO 13564 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.65]
2022-09-14 13:28:18.904 INFO 13564 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-09-14 13:28:18.904 INFO 13564 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1348 ms
2022-09-14 13:28:19.332 INFO 13564 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-09-14 13:28:19.342 INFO 13564 --- [ main] Application : Started Application in 2.661 seconds (JVM running for 3.766)
2022-09-14 13:28:27.493 INFO 13564 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-09-14 13:28:27.494 INFO 13564 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-09-14 13:28:27.495 INFO 13564 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
When i start postman invoke the following:
GET http://localhost:8080/customer?id=1
and i get the following error:
{
"timestamp": "2022-09-14T10:28:27.548+00:00",
"status": 404,
"error": "Not Found",
"path": "/customer"
}
Your #RequestMapping annotation should use value="customer" instead of name="customer".
Better practice is to annotate the CustomerController with #RestController and #ReqeustMapping("/customer") and mark the getCustomer method with #GetMapping, and the create Customer with #PostMapping
Like example my PostMapping:
#Controller
public class MainController {
#PostMapping("/mainaho")
public String addAho (
#RequestParam String owner,
#RequestParam String text,
#RequestParam String sn,
#RequestParam String invid,
#RequestParam String author, Map<String, Object> model) throws WriterException {
AddTmcAho addTmcAho = new AddTmcAho();
addTmcAho.addTmcAho(ahoRepo, owner, text, sn, invid, author, model);
return "mainaho";
}
}
I work on simple authentication app using spring security & encounter by an access denied error. I must mention that registration works perfectly & I've already created 1 record with bcrypted password but on login I'm failed to understand that what did I miss. Grateful for the help
User.java
public class User implements UserDetails {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
private String username;
private String email;
private String password;
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JsonIgnore
private Set<UserRole> userRoles = new HashSet<>();
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<GrantedAuthority>authorities = new HashSet<>();
userRoles.forEach(ur -> authorities.add(new
Authority(ur.getRole().getName())));
return authorities;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
SecurityConfig
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private UserSecurityService userSecurityService;
public SecurityConfig(UserSecurityService userSecurityService) {
this.userSecurityService = userSecurityService;
}
#Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/api/**").permitAll()
.antMatchers("/api/auth/**").permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws
Exception {
auth.userDetailsService(userSecurityService).passwordEncoder
(passwordEncoder());
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws
Exception {return super.authenticationManagerBean();
}
}
UserSecurityService (loaduser)
#Service
public class UserSecurityService implements UserDetailsService {
private static final Logger LOG =
LoggerFactory.getLogger(UserSecurityService.class);
#Autowired
private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String username) throws
UsernameNotFoundException {
User user = userRepository.findUserByUsername(username);
if (null == user) {
LOG.warn("Username {} not found", username);
throw new UsernameNotFoundException("Username " + username + "
not found");
}
return user;
}
}
AuthController
#RestController
#RequestMapping("/api/auth")
public class AuthController {
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private UserRepository userRepository;
#Autowired
private RoleRepository roleRepository;
#Autowired
private PasswordEncoder passwordEncoder;
#Autowired
private UserService userService;
#PostMapping("/register")
public ResponseEntity<User> register(#RequestBody User user) throws Exception {
return new ResponseEntity<>(userService.register(user), HttpStatus.OK);
}
#PostMapping("/login")
public ResponseEntity<String> login(#RequestBody String username, String password ) throws
Exception {
Authentication authentication = authenticationManager.authenticate(new
UsernamePasswordAuthenticationToken(
username, password
));
SecurityContextHolder.getContext().setAuthentication(authentication);
return new ResponseEntity<>("User signed -in succesfully", HttpStatus.OK);
}
}
Error
2022-01-14 14:49:13.604 INFO 24600 --- [ restartedMain]
c.kash.bankingAPI.BankingApiApplication : Starting
BankingApiApplication using Java 11.0.12 on LAPTOP-BQ48GM36 with PID
24600 (B:\spring\bankingAPI\target\classes started by The Kash in
B:\spring\bankingAPI)
2022-01-14 14:49:13.605 INFO 24600 --- [ restartedMain]
c.kash.bankingAPI.BankingApiApplication : No active profile set,
falling back to default profiles: default
2022-01-14 14:49:13.673 INFO 24600 --- [ restartedMain]
.e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults
active! Set 'spring.devtools.add-properties' to 'false' to disable
2022-01-14 14:49:13.674 INFO 24600 --- [ restartedMain]
.e.DevToolsPropertyDefaultsPostProcessor : For additional web related
logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-01-14 14:49:14.557 INFO 24600 --- [ restartedMain]
.s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data
JPA
repositories in DEFAULT mode.
2022-01-14 14:49:14.646 INFO 24600 --- [ restartedMain]
.s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data
repository scanning in 74 ms. Found 2 JPA repository interfaces.
2022-01-14 14:49:15.876 INFO 24600 --- [ restartedMain]
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with
port(s): 8088 (http)
2022-01-14 14:49:15.890 INFO 24600 --- [ restartedMain]
o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-01-14 14:49:15.890 INFO 24600 --- [ restartedMain]
org.apache.catalina.core.StandardEngine : Starting Servlet engine:
[Apache Tomcat/9.0.56]
2022-01-14 14:49:16.008 INFO 24600 --- [ restartedMain] o.a.c.c.C.
[Tomcat].[localhost].[/] : Initializing Spring embedded
WebApplicationContext
2022-01-14 14:49:16.008 INFO 24600 --- [ restartedMain]
w.s.c.ServletWebServerApplicationContext : Root
WebApplicationContext:
initialization completed in 2334 ms
2022-01-14 14:49:16.264 INFO 24600 --- [ restartedMain]
o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing
PersistenceUnitInfo [name: default]
2022-01-14 14:49:16.332 INFO 24600 --- [ restartedMain]
org.hibernate.Version : HHH000412: Hibernate ORM
core
version 5.6.3.Final
2022-01-14 14:49:16.542 INFO 24600 --- [ restartedMain]
o.hibernate.annotations.common.Version : HCANN000001: Hibernate
Commons Annotations {5.1.2.Final}
2022-01-14 14:49:16.661 INFO 24600 --- [ restartedMain]
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-01-14 14:49:17.128 INFO 24600 --- [ restartedMain]
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start
completed.
2022-01-14 14:49:17.145 INFO 24600 --- [ restartedMain]
org.hibernate.dialect.Dialect : HHH000400: Using dialect:
org.hibernate.dialect.MySQL57Dialect
2022-01-14 14:49:18.469 INFO 24600 --- [ restartedMain]
o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using
JtaPlatform implementation:
[org.hibernate.engine.transaction.jta.platform.internal.
NoJtaPlatform]
2022-01-14 14:49:18.478 INFO 24600 --- [ restartedMain]
j.LocalContainerEntityManagerFactoryBean : Initialized JPA
EntityManagerFactory for persistence unit 'default'
2022-01-14 14:49:19.173 WARN 24600 --- [ restartedMain]
JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is
enabled by default. Therefore, database queries may be performed
during
view rendering. Explicitly configure spring.jpa.open-in-view to
disable
this warning
2022-01-14 14:49:19.453 DEBUG 24600 --- [ restartedMain]
edFilterInvocationSecurityMetadataSource : Adding web access control
expression [permitAll] for Ant [pattern='/api/**', GET]
2022-01-14 14:49:19.455 DEBUG 24600 --- [ restartedMain]
edFilterInvocationSecurityMetadataSource : Adding web access control
expression [permitAll] for Ant [pattern='/api/auth/**']
2022-01-14 14:49:19.456 DEBUG 24600 --- [ restartedMain]
edFilterInvocationSecurityMetadataSource : Adding web access control
expression [authenticated] for any request
2022-01-14 14:49:19.468 INFO 24600 --- [ restartedMain]
o.s.s.web.DefaultSecurityFilterChain : Will secure any request
with
[org.springframework.security.web.context.request.async.
WebAsyncManagerIntegrationFilter#4b607819,
org.springframework.security.web.context.SecurityContextPersistence
Filter#146dcdcf,
org.springframework.security.web.header.HeaderWriterFilter#74f0174b,
org.springframework.security.web.authentication.logout.
LogoutFilter#839ff7f,
org.springframework.security.web.authentication.www.
BasicAuthenticationFilter#4f78b9a2,
org.springframework.security.web.savedrequest.
RequestCacheAwareFilter#7e2b3eef,
org.springframework.security.web.servletapi.SecurityContextHolder
AwareRequestFilter#1996d59a,
org.springframework.security.web.authentication.Anonymous
AuthenticationFilter#d82cd0b,
org.springframework.security.web.session.SessionManagement
Filter#47842f0b,
org.springframework.security.web.access.ExceptionTranslation
Filter#6fdc8d32, org.springframework.security.web.access.intercept.
FilterSecurityInterceptor#3619bc38]
2022-01-14 14:49:19.922 INFO 24600 --- [ restartedMain]
o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is
running
on port 35729
2022-01-14 14:49:19.959 INFO 24600 --- [ restartedMain]
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s):
8088 (http) with context path ''
2022-01-14 14:49:19.970 INFO 24600 --- [ restartedMain]
c.kash.bankingAPI.BankingApiApplication : Started
BankingApiApplication
in 6.835 seconds (JVM running for 7.645)
2022-01-14 14:49:51.914 INFO 24600 --- [nio-8088-exec-2] o.a.c.c.C.
[Tomcat].[localhost].[/] : Initializing Spring
DispatcherServlet
'dispatcherServlet'
2022-01-14 14:49:51.915 INFO 24600 --- [nio-8088-exec-2]
o.s.web.servlet.DispatcherServlet : Initializing Servlet
'dispatcherServlet'
2022-01-14 14:49:51.916 INFO 24600 --- [nio-8088-exec-2]
o.s.web.servlet.DispatcherServlet : Completed initialization
in
1 ms
2022-01-14 14:49:51.931 DEBUG 24600 --- [nio-8088-exec-2]
o.s.security.web.FilterChainProxy : Securing POST /api/auth/login
2022-01-14 14:49:51.936 DEBUG 24600 --- [nio-8088-exec-2]
s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder
to
empty SecurityContext
2022-01-14 14:49:51.939 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder
to
anonymous SecurityContext
2022-01-14 14:49:51.940 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.session.SessionManagementFilter : Request requested invalid
session id 1E5E812360CC1B8291311CA85ACAC55A
2022-01-14 14:49:51.945 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.a.i.FilterSecurityInterceptor : Authorized filter
invocation
[POST /api/auth/login] with attributes [permitAll]
2022-01-14 14:49:51.946 DEBUG 24600 --- [nio-8088-exec-2]
o.s.security.web.FilterChainProxy : Secured POST
/api/auth/login
Hibernate: select user0_.id as id1_7_, user0_.email as email2_7_,
user0_.name as name3_7_, user0_.password as password4_7_,
user0_.primary_account_id as primary_6_7_, user0_.savings_account_id
as
savings_7_7_, user0_.username as username5_7_ from users user0_ where
user0_.username=?
2022-01-14 14:49:52.305 WARN 24600 --- [nio-8088-exec-2]
c.k.b.s.serviceImpl.UserSecurityService : Username {
"username": "seeshee",
"password": "12345"
} not found
2022-01-14 14:49:52.313 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.a.dao.DaoAuthenticationProvider : Failed to find user '{
"username": "seeshee",
"password": "1234"
}'
2022-01-14 14:49:52.698 WARN 24600 --- [nio-8088-exec-2]
o.a.c.util.SessionIdGeneratorBase : Creation of SecureRandom
instance for session ID generation using [SHA1PRNG] took [364]
milliseconds.
2022-01-14 14:49:52.700 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.s.HttpSessionRequestCache : Saved request
http://localhost:8088/api/auth/login to session
2022-01-14 14:49:52.701 DEBUG 24600 --- [nio-8088-exec-2]
s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using
Reque
tHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expec
edHeaderValue=XMLHttpRequest]
2022-1-14 14:49:52.701 DEBUG 24600 --- [nio-8088-exec-2]
s.w.a.DelegatingAuthenticationEntryPoint : No match found. Using
default entry point
org.springframework.security.web.authentication.www.
BasicAuthenticationEntryPoint#691634d7
2022-01-14 14:49:52.702 DEBUG 24600 --- [nio-8088-exec-2]
w.c.HttpSessionSecurityContextRepository : Did not store empty
SecurityContext
2022-01-14 14:49:52.702 DEBUG 24600 --- [nio-8088-exec-2]
w.c.HttpSessionSecurityContextRepository : Did not store empty
SecurityContext
2022-01-14 14:49:52.702 DEBUG 24600 --- [nio-8088-exec-2]
s.s.w.c.SecurityContextPersistenceFilter : Cleared
SecurityContextHolder
to complete request
2022-01-14 14:49:52.705 DEBUG 24600 --- [nio-8088-exec-2]
o.s.security.web.FilterChainProxy : Securing POST /error
2022-01-14 14:49:52.705 DEBUG 24600 --- [nio-8088-exec-2]
s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder
to
empty SecurityContext
2022-01-14 14:49:52.706 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder
to
anonymous SecurityContext
2022-01-14 14:49:52.706 DEBUG 24600 --- [nio-8088-exec-2]
o.s.security.web.FilterChainProxy : Secured POST /error
2022-01-14 14:49:52.721 DEBUG 24600 --- [nio-8088-exec-2]
a.DefaultWebInvocationPrivilegeEvaluator : filter invocation [/error]
denied for AnonymousAuthenticationToken [Principal=anonymousUser,
Credentials=[PROTECTED], Authenticated=true,
Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1,
SessionId=BAFE9322A4A2705325C4B6540915129E], Granted Authorities=
[ROLE_ANONYMOUS]]
org.springframework.security.access.AccessDeniedException: Access is
denied
at
org.springframework.security.access.vote.AffirmativeBased.
decide(AffirmativeBased.java:73)
~[spring-security-core-5.6.1.jar:5.6.1]
at org.springframework.security.web.access.
DefaultWebInvocationPrivilegeEvaluator.isAllowed
(DefaultWe
bInvocationPrivilegeEvaluator.java:100) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.access.
DefaultWebInvocationPrivilegeEvaluator.isAllowed
(DefaultWebInvocationPrivilegeEvaluator.java:67) ~[spring-security-
web-
5.6.1.jar:5.6.1]
at
org.springframework.boot.web.servlet.filter.ErrorPageSecurityFilter.
isAllowed
(ErrorPageSecurityFilter.java:84) ~[spring-boot-2.6.2.jar:2.6.2]
at
org.springframework.boot.web.servlet.filter.ErrorPageSecurityFilter.
doFilter
(ErrorPageSecurityFilter.java:72) ~[spring-boot-2.6.2.jar:2.6.2]
at
org.springframework.boot.web.servlet.filter.ErrorPageSecurityFilter.
doFilter
(ErrorPageSecurityFilter.java:66) ~[spring-boot-2.6.2.jar:2.6.2]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(
ApplicationFilterChain.
java:189) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~
[tomcat-embed-core-9.0.56.jar:9.0.56]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
doFilter
(FilterChainProxy.jav
a:327) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.access.intercept.
FilterSecurityInterceptor.invoke
(FilterSecurityInterceptor.java:106) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.access.intercept.
FilterSecurityInterceptor.doFilter
(FilterSecurityInterceptor.java:81) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.access.
ExceptionTranslationFilter.doFilter
(ExceptionTranslationFilter.java:122) ~[spring-security-web-
5.6.1.jar:5.6.1]
at
org.springframework.security.web.access.ExceptionTranslationFilter.
doFilter
(ExceptionTranslationFilter.java:116) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.session.SessionManagementFilter
.doFilter
(SessionManagementFilter.java:87) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.session.SessionManagementFilter.
doFilter
(SessionManagementFilter.java:81) ~[spring-security-web-
5.6.1.jar:5.6.1]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain
.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.authentication.
AnonymousAuthenticationFilter.doFilter
(AnonymousAuthenticationFilter.java:109) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.servletapi.
SecurityContextHolderAwareRequestFilter.
doFilter(SecurityContextHolderAwareRequestFilter.java:149) ~[spring-
security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.savedrequest.
RequestCacheAwareFilter.doFilter
(RequestCacheAwareFilter.java:63) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:102) ~[spring-web-5.3.14.jar:5.3.14]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.authentication.logout.
LogoutFilter.doFilter
(LogoutFilter.java:103) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.authentication.logout.
LogoutFilter.doFilter
(LogoutFilter.java:89) ~[spring-security-web-5.6.1.jar:5.6.1]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(
OncePerRequestFilter.java:102)
~[spring-web-5.3.14.jar:5.3.14]
at org.springframework.security.web.FilterChainProxy$VirtualFilter
Chain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at
org.springframework.security.web.context.SecurityContextPersistence
Filter.doFilter
(SecurityContextPersistenceFilter.java:110) ~[spring-security-web-
5.6.1.jar:5.6.1]
at
org.springframework.security.web.context.SecurityContextPersistence
Filter.doFilter
(SecurityContextPersistenceFilter.java:80) ~[spring-security-web-
5.6.1.jar:5.6.1]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:102) ~[spring-web-5.3.14.jar:5.3.14]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy.doFilterInternal
(FilterChainProxy.java:211) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy.doFilter
(FilterChainProxy.java:183) ~[spring-security-web-5.6.1.jar:5.6.1]
at
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate
(DelegatingFilterProxy.java:354) ~[spring-web-5.3.14.jar:5.3.14]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter
(DelegatingFilterProxy.java:267) ~
[spring-web-5.3.14.jar:5.3.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:189) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at
org.springframework.web.filter.RequestContextFilter.doFilterInternal
(RequestContextFilter.java:100) ~[spring-web-5.3.14.jar:5.3.14]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:117) ~[spring-web-5.3.14.jar:5.3.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:189) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:102) ~[spring-web-5.3.14.jar:5.3.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:189) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:102) ~[spring-web-5.3.14.jar:5.3.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:189) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationDispatcher.invoke
(ApplicationDispatcher.java:711) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationDispatcher.processRequest
(ApplicationDispatcher.java:461) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationDispatcher.doForward
(ApplicationDispatcher.java:385) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationDispatcher.forward
(ApplicationDispatcher.java:313) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.StandardHostValve.custom
(StandardHostValve.java:403) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.StandardHostValve.status
(StandardHostValve.java:249) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
[tomcat-embed-core-9.0.56.jar:9.0.56]
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run
(TaskThread.java:61) ~
[tomcat-embed-core-9.0.56.jar:9.0.56]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
2022-01-14 00:49:13.289 DEBUG 21332 --- [nio-8088-exec-2]
w.c.HttpSessionSecurityContextRepository : Did not store anonymous
SecurityContext
2022-01-14 00:49:13.289 DEBUG 21332 --- [nio-8088-exec-2]
w.c.HttpSessionSecurityContextRepository : Did not store anonymous
SecurityContext
2022-01-14 00:49:13.289 DEBUG 21332 --- [nio-8088-exec-2]
s.s.w.c.SecurityContextPersistenceFilter : Cleared
SecurityContextHolder to complete request
Your logs say this:
2022-01-14 14:49:52.305 WARN 24600 --- [nio-8088-exec-2] c.k.b.s.serviceImpl.UserSecurityService :
Username { "username": "seeshee", "password": "12345" } not found
If we look in your code we can see the following line:
login(#RequestBody String username, String password )
This is your faulty code line, as it doesn't do what you think it does. You think it will take the json and extract the two parameters username and password and set these. But what it actually does is that the #RequestBody will take the entire body (the json) and set it to the parameter that is defined on, which is username.
So what spring is doing is that it will extract the entire json body and place it into the username string.
Then you try to use that to login, and then you get the error message posted above.
What you need to do is to create a holder class that spring can deserialize into.
public class RequestBody {
public RequestBody(String username, String password) {
this.username = username;
this.password = password;
}
// getters, setters
}
#PostMapping("/login")
public ResponseEntity<String> login(#RequestBody RequestBody requestBody ) throws Exception {
Authentication authentication = authenticationManager.authenticate(new
UsernamePasswordAuthenticationToken(
requestBody.getUsername(), requestBody.getPassword()
));
SecurityContextHolder.getContext().setAuthentication(authentication);
return new ResponseEntity<>("User signed -in succesfully", HttpStatus.OK);
}
You can read about how to use requestbody here:
Spring’s RequestBody and ResponseBody Annotation
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?
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")
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 ()
...