问:
loadUserByUsername() method not getting invoked by spring security
I'm new to Spring security and just started learning it. I want to use a custom User class, So I'm trying to implement UserDetailsService interface and override loadUserByUsername()  method to return the custom User object.
 but spring security is not invoking loadUserByUsername(),
So user is not getting authenticated, Instead gets redirected to login page.

I can't figure out what's going wrong

Code:

```<code>@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/login","/css/**","/images/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll();
    }
    @Autowired
    @Qualifier("userDetailsService")
    UserDetailsService userDetailsService;
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        System.out.println("configureglobal called");

        auth.userDetailsService(userDetailsService);
    }
}
</code>```

```<code>@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(final String username)
        throws UsernameNotFoundException {
        System.out.println("loadUserByUsername called");
        User user = userRepository.findByUsername(username);

return user;

    }
}
</code>```

```<code>public interface UserRepository extends JpaRepository<User, Long>{
    User findByUsername(String username);
    List<User> findByName(String name);

}
</code>```

Here is my controller class. Even when a valid username and password is provided, login method is getting called 3 times and loadUserByUsername() is not invoked

```<code> @Controller
    public class MainController {
        @RequestMapping(value= {"/login"})
        public String login() {
            System.out.println("login called");
            return "login";
        }

            @RequestMapping(value={"/",/home"})
            public String homeReturner(HttpServletRequest request,Model model) {
                System.out.println("home returner called");
                model.addAttribute("name", request.getAttribute("name"));
                return "home";
            }
    }
</code>```

User class

```<code>@Entity
public class User implements UserDetails {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

    private String name;

    private String username;

    private String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String userName) {
        this.username = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean isAccountNonExpired() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public boolean isEnabled() {
        // TODO Auto-generated method stub
        return true;
    }

}
</code>```

Html form in the login page

```<code><form action="/signin">
    <input type="text" name="username" placeholder="Email"> <input type="password" name="password" placeholder="Password"> <button type="submit">Sign in</button><br>
    <input type="checkbox" name=""> <label>Remember me.</label>   <input type="checkbox" name=""><label>Forgot password?</label>
</form>
</code>```

Sign in controller

```<code>@Controller
public class LoginController {
    @Autowired
    private UserRepository userRepository;
    @GetMapping(path="/signin")
    public String signin() {

            System.out.print("signin called");
        return "home";
    }
}
</code>```

What's going wrong here? Why loadUserByUsername() isn't invoked?

Debug Log

```2018-07-04 21:59:19.249 DEBUG 7128 --- [nio-8080-exec-4] o.s.s.w.util.matcher.AndRequestMatcher   : Trying to match using NegatedRequestMatcher [requestMatcher=Ant [pattern='/**/favicon.ico']]
2018-07-04 21:59:19.250 DEBUG 7128 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/favicon.ico'; against '/**/favicon.ico'
2018-07-04 21:59:19.251 DEBUG 7128 --- [nio-8080-exec-4] o.s.s.w.u.matcher.NegatedRequestMatcher  : matches = false
2018-07-04 21:59:19.252 DEBUG 7128 --- [nio-8080-exec-4] o.s.s.w.util.matcher.AndRequestMatcher   : Did not match
2018-07-04 21:59:19.252 DEBUG 7128 --- [nio-8080-exec-4] o.s.s.w.s.HttpSessionRequestCache        : Request not saved as configured RequestMatcher did not match
2018-07-04 21:59:19.252 DEBUG 7128 --- [nio-8080-exec-4] o.s.s.w.a.ExceptionTranslationFilter     : Calling Authentication entry point.
2018-07-04 21:59:19.253 DEBUG 7128 --- [nio-8080-exec-4] o.s.s.web.DefaultRedirectStrategy        : Redirecting to 'http://localhost:8080/login'
2018-07-04 21:59:19.254 DEBUG 7128 --- [nio-8080-exec-4] 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@7a1d6f3f
2018-07-04 21:59:19.254 DEBUG 7128 --- [nio-8080-exec-4] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2018-07-04 21:59:19.257 DEBUG 7128 --- [nio-8080-exec-4] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
2018-07-04 21:59:19.298 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2018-07-04 21:59:19.298 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2018-07-04 21:59:19.298 DEBUG 7128 --- [nio-8080-exec-3] w.c.HttpSessionSecurityContextRepository : HttpSession returned null object for SPRING_SECURITY_CONTEXT
2018-07-04 21:59:19.298 DEBUG 7128 --- [nio-8080-exec-3] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@22d63ce1. A new one will be created.
2018-07-04 21:59:19.299 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2018-07-04 21:59:19.300 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
2018-07-04 21:59:19.300 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/logout'
2018-07-04 21:59:19.301 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 5 of 11 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2018-07-04 21:59:19.301 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'GET /login' doesn't match 'POST /login
2018-07-04 21:59:19.302 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2018-07-04 21:59:19.302 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.s.DefaultSavedRequest            : pathInfo: both null (property equals)
2018-07-04 21:59:19.302 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.s.DefaultSavedRequest            : queryString: both null (property equals)
2018-07-04 21:59:19.303 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.s.DefaultSavedRequest            : requestURI: arg1=/home; arg2=/login (property not equals)
2018-07-04 21:59:19.303 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.s.HttpSessionRequestCache        : saved request doesn't match
2018-07-04 21:59:19.303 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2018-07-04 21:59:19.304 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2018-07-04 21:59:19.304 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.a.AnonymousAuthenticationFilter  : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@3793fe54: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffde5d4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: FB5BC6CF44B2064132ADF5A75EE463DD; Granted Authorities: ROLE_ANONYMOUS'
2018-07-04 21:59:19.306 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
2018-07-04 21:59:19.306 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2018-07-04 21:59:19.307 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2018-07-04 21:59:19.307 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/'
2018-07-04 21:59:19.308 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/login'
2018-07-04 21:59:19.308 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /login; Attributes: [permitAll]
2018-07-04 21:59:19.308 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@3793fe54: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffde5d4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: FB5BC6CF44B2064132ADF5A75EE463DD; Granted Authorities: ROLE_ANONYMOUS
2018-07-04 21:59:19.309 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@7cbce1e2, returned: 1
2018-07-04 21:59:19.310 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor    : Authorization successful
2018-07-04 21:59:19.310 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor    : RunAsManager did not change Authentication object
2018-07-04 21:59:19.310 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login reached end of additional filter chain; proceeding with original chain
login called2018-07-04 21:59:19.320 DEBUG 7128 --- [nio-8080-exec-3] 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@7a1d6f3f
2018-07-04 21:59:19.321 DEBUG 7128 --- [nio-8080-exec-3] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2018-07-04 21:59:19.326 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.a.ExceptionTranslationFilter     : Chain processed normally
2018-07-04 21:59:19.326 DEBUG 7128 --- [nio-8080-exec-3] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
2018-07-04 21:59:26.605 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2018-07-04 21:59:26.606 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2018-07-04 21:59:26.607 DEBUG 7128 --- [nio-8080-exec-7] w.c.HttpSessionSecurityContextRepository : HttpSession returned null object for SPRING_SECURITY_CONTEXT
2018-07-04 21:59:26.607 DEBUG 7128 --- [nio-8080-exec-7] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@22d63ce1. A new one will be created.
2018-07-04 21:59:26.607 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2018-07-04 21:59:26.607 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
2018-07-04 21:59:26.607 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/signin'; against '/logout'
2018-07-04 21:59:26.608 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 5 of 11 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2018-07-04 21:59:26.608 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/signin'; against '/login'
2018-07-04 21:59:26.608 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2018-07-04 21:59:26.609 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.s.DefaultSavedRequest            : pathInfo: both null (property equals)
2018-07-04 21:59:26.609 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.s.DefaultSavedRequest            : queryString: both null (property equals)
2018-07-04 21:59:26.610 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.s.DefaultSavedRequest            : requestURI: arg1=/home; arg2=/signin (property not equals)
2018-07-04 21:59:26.610 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.s.HttpSessionRequestCache        : saved request doesn't match
2018-07-04 21:59:26.610 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2018-07-04 21:59:26.610 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2018-07-04 21:59:26.611 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.a.AnonymousAuthenticationFilter  : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@3793fe54: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffde5d4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: FB5BC6CF44B2064132ADF5A75EE463DD; Granted Authorities: ROLE_ANONYMOUS'
2018-07-04 21:59:26.611 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
2018-07-04 21:59:26.612 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2018-07-04 21:59:26.612 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2018-07-04 21:59:26.612 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/signin'; against '/'
2018-07-04 21:59:26.613 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/signin'; against '/login'
2018-07-04 21:59:26.613 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/signin'; against '/css/**'
2018-07-04 21:59:26.613 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/signin'; against '/images/**'
2018-07-04 21:59:26.614 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /signin; Attributes: [authenticated]
2018-07-04 21:59:26.614 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@3793fe54: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffde5d4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: FB5BC6CF44B2064132ADF5A75EE463DD; Granted Authorities: ROLE_ANONYMOUS
2018-07-04 21:59:26.615 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@7cbce1e2, returned: -1
2018-07-04 21:59:26.618 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.a.ExceptionTranslationFilter     : Access is denied (user is anonymous); redirecting to authentication entry point

org.springframework.security.access.AccessDeniedException: Access is denied
    at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) ~[spring-security-core-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233) ~[spring-security-core-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:124) ~[spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) ~[spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) ~[spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_162]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_162]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_162]
```

答:
I had the same problem, I solved it by changing the method="get" to method="post" in form.</p>
```<code>        <form th:action="@{/users/login}" th:method="post" class="login">
            //inputs
            <input type="submit" value="Enter!"/>
        </form>
</code>```

Body:
I'm new to Spring security and just started learning it. I want to use a custom User class, So I'm trying to implement UserDetailsService interface and override loadUserByUsername()  method to return the custom User object.
 but spring security is not invoking loadUserByUsername(),
So user is not getting authenticated, Instead gets redirected to login page.

I can't figure out what's going wrong

Code:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/login","/css/**","/images/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll();
    }
    @Autowired
    @Qualifier("userDetailsService")
    UserDetailsService userDetailsService;
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        System.out.println("configureglobal called");

        auth.userDetailsService(userDetailsService);
    }
}

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(final String username)
        throws UsernameNotFoundException {
        System.out.println("loadUserByUsername called");
        User user = userRepository.findByUsername(username);

return user;

    }
}

public interface UserRepository extends JpaRepository<User, Long>{
    User findByUsername(String username);
    List<User> findByName(String name);

}

Here is my controller class. Even when a valid username and password is provided, login method is getting called 3 times and loadUserByUsername() is not invoked

 @Controller
    public class MainController {
        @RequestMapping(value= {"/login"})
        public String login() {
            System.out.println("login called");
            return "login";
        }

            @RequestMapping(value={"/",/home"})
            public String homeReturner(HttpServletRequest request,Model model) {
                System.out.println("home returner called");
                model.addAttribute("name", request.getAttribute("name"));
                return "home";
            }
    }

User class

@Entity
public class User implements UserDetails {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

    private String name;

    private String username;

    private String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String userName) {
        this.username = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean isAccountNonExpired() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public boolean isEnabled() {
        // TODO Auto-generated method stub
        return true;
    }

}

Html form in the login page

<form action="/signin">
    <input type="text" name="username" placeholder="Email"> <input type="password" name="password" placeholder="Password"> <button type="submit">Sign in</button>

    <input type="checkbox" name=""> Remember me.   <input type="checkbox" name="">Forgot password?
</form>

Sign in controller

@Controller
public class LoginController {
    @Autowired
    private UserRepository userRepository;
    @GetMapping(path="/signin")
    public String signin() {

            System.out.print("signin called");
        return "home";
    }
}

What's going wrong here? Why loadUserByUsername() isn't invoked?

Debug Log

2018-07-04 21:59:19.249 DEBUG 7128 --- [nio-8080-exec-4] o.s.s.w.util.matcher.AndRequestMatcher   : Trying to match using NegatedRequestMatcher [requestMatcher=Ant [pattern='/**/favicon.ico']]
2018-07-04 21:59:19.250 DEBUG 7128 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/favicon.ico'; against '/**/favicon.ico'
2018-07-04 21:59:19.251 DEBUG 7128 --- [nio-8080-exec-4] o.s.s.w.u.matcher.NegatedRequestMatcher  : matches = false
2018-07-04 21:59:19.252 DEBUG 7128 --- [nio-8080-exec-4] o.s.s.w.util.matcher.AndRequestMatcher   : Did not match
2018-07-04 21:59:19.252 DEBUG 7128 --- [nio-8080-exec-4] o.s.s.w.s.HttpSessionRequestCache        : Request not saved as configured RequestMatcher did not match
2018-07-04 21:59:19.252 DEBUG 7128 --- [nio-8080-exec-4] o.s.s.w.a.ExceptionTranslationFilter     : Calling Authentication entry point.
2018-07-04 21:59:19.253 DEBUG 7128 --- [nio-8080-exec-4] o.s.s.web.DefaultRedirectStrategy        : Redirecting to 'http://localhost:8080/login'
2018-07-04 21:59:19.254 DEBUG 7128 --- [nio-8080-exec-4] 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@7a1d6f3f
2018-07-04 21:59:19.254 DEBUG 7128 --- [nio-8080-exec-4] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2018-07-04 21:59:19.257 DEBUG 7128 --- [nio-8080-exec-4] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
2018-07-04 21:59:19.298 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2018-07-04 21:59:19.298 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2018-07-04 21:59:19.298 DEBUG 7128 --- [nio-8080-exec-3] w.c.HttpSessionSecurityContextRepository : HttpSession returned null object for SPRING_SECURITY_CONTEXT
2018-07-04 21:59:19.298 DEBUG 7128 --- [nio-8080-exec-3] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@22d63ce1. A new one will be created.
2018-07-04 21:59:19.299 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2018-07-04 21:59:19.300 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
2018-07-04 21:59:19.300 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/logout'
2018-07-04 21:59:19.301 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 5 of 11 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2018-07-04 21:59:19.301 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'GET /login' doesn't match 'POST /login
2018-07-04 21:59:19.302 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2018-07-04 21:59:19.302 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.s.DefaultSavedRequest            : pathInfo: both null (property equals)
2018-07-04 21:59:19.302 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.s.DefaultSavedRequest            : queryString: both null (property equals)
2018-07-04 21:59:19.303 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.s.DefaultSavedRequest            : requestURI: arg1=/home; arg2=/login (property not equals)
2018-07-04 21:59:19.303 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.s.HttpSessionRequestCache        : saved request doesn't match
2018-07-04 21:59:19.303 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2018-07-04 21:59:19.304 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2018-07-04 21:59:19.304 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.a.AnonymousAuthenticationFilter  : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@3793fe54: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffde5d4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: FB5BC6CF44B2064132ADF5A75EE463DD; Granted Authorities: ROLE_ANONYMOUS'
2018-07-04 21:59:19.306 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
2018-07-04 21:59:19.306 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2018-07-04 21:59:19.307 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2018-07-04 21:59:19.307 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/'
2018-07-04 21:59:19.308 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/login'
2018-07-04 21:59:19.308 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /login; Attributes: [permitAll]
2018-07-04 21:59:19.308 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@3793fe54: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffde5d4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: FB5BC6CF44B2064132ADF5A75EE463DD; Granted Authorities: ROLE_ANONYMOUS
2018-07-04 21:59:19.309 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@7cbce1e2, returned: 1
2018-07-04 21:59:19.310 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor    : Authorization successful
2018-07-04 21:59:19.310 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor    : RunAsManager did not change Authentication object
2018-07-04 21:59:19.310 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login reached end of additional filter chain; proceeding with original chain
login called2018-07-04 21:59:19.320 DEBUG 7128 --- [nio-8080-exec-3] 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@7a1d6f3f
2018-07-04 21:59:19.321 DEBUG 7128 --- [nio-8080-exec-3] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2018-07-04 21:59:19.326 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.a.ExceptionTranslationFilter     : Chain processed normally
2018-07-04 21:59:19.326 DEBUG 7128 --- [nio-8080-exec-3] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
2018-07-04 21:59:26.605 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2018-07-04 21:59:26.606 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2018-07-04 21:59:26.607 DEBUG 7128 --- [nio-8080-exec-7] w.c.HttpSessionSecurityContextRepository : HttpSession returned null object for SPRING_SECURITY_CONTEXT
2018-07-04 21:59:26.607 DEBUG 7128 --- [nio-8080-exec-7] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@22d63ce1. A new one will be created.
2018-07-04 21:59:26.607 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2018-07-04 21:59:26.607 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
2018-07-04 21:59:26.607 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/signin'; against '/logout'
2018-07-04 21:59:26.608 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 5 of 11 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2018-07-04 21:59:26.608 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/signin'; against '/login'
2018-07-04 21:59:26.608 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2018-07-04 21:59:26.609 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.s.DefaultSavedRequest            : pathInfo: both null (property equals)
2018-07-04 21:59:26.609 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.s.DefaultSavedRequest            : queryString: both null (property equals)
2018-07-04 21:59:26.610 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.s.DefaultSavedRequest            : requestURI: arg1=/home; arg2=/signin (property not equals)
2018-07-04 21:59:26.610 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.s.HttpSessionRequestCache        : saved request doesn't match
2018-07-04 21:59:26.610 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2018-07-04 21:59:26.610 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2018-07-04 21:59:26.611 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.a.AnonymousAuthenticationFilter  : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@3793fe54: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffde5d4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: FB5BC6CF44B2064132ADF5A75EE463DD; Granted Authorities: ROLE_ANONYMOUS'
2018-07-04 21:59:26.611 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
2018-07-04 21:59:26.612 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2018-07-04 21:59:26.612 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2018-07-04 21:59:26.612 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/signin'; against '/'
2018-07-04 21:59:26.613 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/signin'; against '/login'
2018-07-04 21:59:26.613 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/signin'; against '/css/**'
2018-07-04 21:59:26.613 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/signin'; against '/images/**'
2018-07-04 21:59:26.614 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /signin; Attributes: [authenticated]
2018-07-04 21:59:26.614 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@3793fe54: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffde5d4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: FB5BC6CF44B2064132ADF5A75EE463DD; Granted Authorities: ROLE_ANONYMOUS
2018-07-04 21:59:26.615 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@7cbce1e2, returned: -1
2018-07-04 21:59:26.618 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.a.ExceptionTranslationFilter     : Access is denied (user is anonymous); redirecting to authentication entry point

org.springframework.security.access.AccessDeniedException: Access is denied
    at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) ~[spring-security-core-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233) ~[spring-security-core-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:124) ~[spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) ~[spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) ~[spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_162]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_162]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_162]

Body:
I had the same problem, I solved it by changing the method="get" to method="post" in form.

        <form th:action="@{/users/login}" th:method="post" class="login">
            //inputs
            <input type="submit" value="Enter!"/>
        </form>


来源: stackexchange

问:
Focus language grammar
I need to extract some info from a list of mainframe scripts written in focus language.
I'm trying to write a java program for parsing source code. Due to the name of the language it is difficult to find any useful information on the internet. Maybe someone know if exist a grammar for this language on internet(for example for antlr4) or maybe an implemented lexer.
Thanks in advance for any response!</p>

答:
Follow this link to the Focus Developer Manuals, then click on the left side to open the list of manuals available.

Note: The link to "FOCUS Developer Manuals" at the bottom of the the WikiPedia page was http://... instead of https://..., and resulted in a connection refused error. I have corrected the Wiki page.

ContentLicense: CC BY-SA 4.0

Title: Focus language grammar


问:
Detect if user is using mobile iOS
I have written a function to copy text from a textarea but I need to have a particular code block executed if the user is using an apple mobile device.

I tried the following statement

```<code>if (navigator.userAgent.match(/iphone|ipod|ipad/)) {
 // code
}
</code>```

but it doesn't seem to work very well.

Do you have any suggestions?

/* Full code */

```<code>function copy(copyText) {
  if (navigator.userAgent.match(/iphone|ipod|ipad/)) {
    // handle iOS devices
    copyText.contenteditable = true;
    copyText.readonly = false;

    var range = document.createRange();
    range.selectNodeContents(input);

    var selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
    input.setSelectionRange(0, 999999);
  } else {
    // other devices are easy
    copyText.select();
  }
  document.execCommand("copy");
}
</code>```

答:
Detecting a mobile browser

Not sure if this is what youre looking for but it looks like might have the answer to your question?

Using navigator.userAgentData
You may also use navigator.userAgentData.mobile, but userAgentData is still experimental, so it is not recommended for use in production.

```<code>const isMobile = navigator.userAgentData.mobile;
</code>```

That part might be of use

Title: Detect if user is using mobile iOS

Body:
I have written a function to copy text from a textarea but I need to have a particular code block executed if the user is using an apple mobile device.

I tried the following statement

if (navigator.userAgent.match(/iphone|ipod|ipad/)) {
 // code
}

but it doesn't seem to work very well.

Do you have any suggestions?

/* Full code */

function copy(copyText) {
  if (navigator.userAgent.match(/iphone|ipod|ipad/)) {
    // handle iOS devices
    copyText.contenteditable = true;
    copyText.readonly = false;

    var range = document.createRange();
    range.selectNodeContents(input);

    var selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
    input.setSelectionRange(0, 999999);
  } else {
    // other devices are easy
    copyText.select();
  }
  document.execCommand("copy");
}

Body:
Detecting a mobile browser

Not sure if this is what youre looking for but it looks like might have the answer to your question?

Using navigator.userAgentData
You may also use navigator.userAgentData.mobile, but userAgentData is still experimental, so it is not recommended for use in production.

const isMobile = navigator.userAgentData.mobile;

That part might be of use


问:
'ME' not valid within a module in vb.net
I am trying to update a chart from within a module in vb.net;

Me.Chart1.Series.Add("Profile")

Me.Chart1.Series("Profile").Color = Color.LightGray

......

But I keep getting an error message: 'ME' not valid within a module.
Any workaround would be much appreciated please. Kind regards.

答:
Me means the current Object or Instance of a Class. Me works from within a Form because a Form is a Class AND the Chart is presumably contained by the Form so it is then found and acted upon. The Chart is NOT contained by the Module so Me makes no sense here. Additionally, a Module is a special kind of class where everything (including the Module) is SHARED, which is why you also can't use Me within it.

The solution is to PASS the Chart into the Module, either storing a reference to it in a Module member, or simply using it via a Parameter in a Method:

```<code>' ... in the Module ...
Public Sub UpdateChart(ByVal c As Chart)
    c.Series.Add("Profile")
    c.Series("Profile").Color = Color.LightGray
    ' ... other code that use "c" ...
End Sub
</code>```

In the Form, you'd call it with:

```<code>UpdateChart(Me.Chart1)
</code>```

Body:
Me means the current Object or Instance of a Class. Me works from within a Form because a Form is a Class AND the Chart is presumably contained by the Form so it is then found and acted upon. The Chart is NOT contained by the Module so Me makes no sense here. Additionally, a Module is a special kind of class where everything (including the Module) is SHARED, which is why you also can't use Me within it.

The solution is to PASS the Chart into the Module, either storing a reference to it in a Module member, or simply using it via a Parameter in a Method:

' ... in the Module ...
Public Sub UpdateChart(ByVal c As Chart)
    c.Series.Add("Profile")
    c.Series("Profile").Color = Color.LightGray
    ' ... other code that use "c" ...
End Sub

In the Form, you'd call it with:

UpdateChart(Me.Chart1)


问:
Class to Instance Registry Typing in TypeScript
I'm trying to use classes as input values to a registry method where the return value is a cached instance of that instance.  However I do not find a way to make this type safe.

What I want is something like this:

```<code>class MyRegistry {
  getInstance<T, C extends Class<T>>(cls: C): T;
}

let x: MyThing = registry.getInstance(MyThing);
</code>```

Is there a way to make this work? I'm aware there are ways to type out newables but I cannot find a way to make the return value concrete.

答:
You might consider something like this:</p>
```<code>class Class {}
class ClassY extends Class {}

class MyRegistry<T extends typeof Class> {
  #reg = new Map<T, InstanceType<T>>()
  getInstance<U extends T>(cls: U) { return this.#reg.get(cls) as InstanceType<U> }
  setInstance(u: InstanceType<T>) { this.#reg.set(u.constructor as T, u) }
}

const r = new MyRegistry()
const x = r.getInstance(Class) // x: Class
const y = r.getInstance(ClassY) // y: ClassY
</code>```

Body:
I'm trying to use classes as input values to a registry method where the return value is a cached instance of that instance.  However I do not find a way to make this type safe.

What I want is something like this:

class MyRegistry {
  getInstance<T, C extends Class<T>>(cls: C): T;
}

let x: MyThing = registry.getInstance(MyThing);

Is there a way to make this work? I'm aware there are ways to type out newables but I cannot find a way to make the return value concrete.

Body:
You might consider something like this:

class Class {}
class ClassY extends Class {}

class MyRegistry<T extends typeof Class> {
  #reg = new Map<T, InstanceType<T>>()
  getInstance<U extends T>(cls: U) { return this.#reg.get(cls) as InstanceType<U> }
  setInstance(u: InstanceType<T>) { this.#reg.set(u.constructor as T, u) }
}

const r = new MyRegistry()
const x = r.getInstance(Class) // x: Class
const y = r.getInstance(ClassY) // y: ClassY


问:
Template function for max_element on maps needs to know both types
I'm trying to write a custom cmp function for a map, a simple one that does the comparison over the second element of the map. I'd like to have the function as a template, but I can't figure out how to pass the map's .first and .second types along to my cmp function. My non-working code is below, which will clearly fail since the type of T1 and T2 are not passed along:

```<code>#include <map>
#include <vector>
#include <algorithm>

template<class T1, class T2>
bool pairCompare(const std::pair<T1,T2> & x,
                 const std::pair<T1,T2> & y) {
  return x.second < y.second;
}

template<class T1>
typename T1::iterator map_max_element(const T1 & A) {

  // How do I pass the type to pairCompare?
  return std::max_element(A.begin(), A.end(), pairCompare<?????>);
}

int main() {
  std::map<std::vector<double>, int> A;
  map_max_element(A);

  return 0;
}
</code>```

答:
std::map has a nested type called value_type which is actually a typedef of std::pair<const K, V>. And std::pair has two nested types first_type and second_type.  Use this info as:

```<code>template<class T>
typename T::const_iterator map_max_element(const T & A)
{
   typedef typename T::value_type pair_type;
   typedef typename pair_type::first_type K;
   typedef typename pair_type::second_type V;
   return std::max_element(A.begin(), A.end(), pairCompare<K,V>);
}
</code>```

Note that in your code the return type is wrong. It should be const_iterator, rather than iterator, because in the function A is const map. Hence what you can get from it is const_iterator. :-)

Or you could simply write the compare function as:

```<code>template<class T>
bool pairCompare(const T & x, const T & y) {
  return x.second < y.second;
}
</code>```

And use it as:

```<code>return std::max_element(A.begin(), A.end(), pairCompare<typename T::value_type>);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to write a custom cmp function for a map, a simple one that does the comparison over the second element of the map. I'd like to have the function as a template, but I can't figure out how to pass the map's .first and .second types along to my cmp function. My non-working code is below, which will clearly fail since the type of T1 and T2 are not passed along:

#include <map>
#include <vector>
#include <algorithm>

template<class T1, class T2>
bool pairCompare(const std::pair<T1,T2> & x,
                 const std::pair<T1,T2> & y) {
  return x.second < y.second;
}

template<class T1>
typename T1::iterator map_max_element(const T1 & A) {

  // How do I pass the type to pairCompare?
  return std::max_element(A.begin(), A.end(), pairCompare<?????>);
}

int main() {
  std::map<std::vector<double>, int> A;
  map_max_element(A);

  return 0;
}

Body:
std::map has a nested type called value_type which is actually a typedef of std::pair<const K, V>. And std::pair has two nested types first_type and second_type.  Use this info as:

template<class T>
typename T::const_iterator map_max_element(const T & A)
{
   typedef typename T::value_type pair_type;
   typedef typename pair_type::first_type K;
   typedef typename pair_type::second_type V;
   return std::max_element(A.begin(), A.end(), pairCompare<K,V>);
}

Note that in your code the return type is wrong. It should be const_iterator, rather than iterator, because in the function A is const map. Hence what you can get from it is const_iterator. :-)

Or you could simply write the compare function as:

template<class T>
bool pairCompare(const T & x, const T & y) {
  return x.second < y.second;
}

And use it as:

return std::max_element(A.begin(), A.end(), pairCompare<typename T::value_type>);


问:
Calculate difference between min and max for each Pandas group
I want to calculate difference between max and min value for each group in pandas dataframe.
For example, I wrote a code that calculates standard deviation for each group.

```<code>import pandas as pd
import statistics

months = ["Jan", "Jan", "Jan", "Jan","Feb","Feb","Feb", "Feb", "Mar", "Mar", "Mar", "Mar"]
values_1 = [1,2,7,1,3,8,9,4,7,4,11,1]
values_2 = [8,6,6,5,6,6,8,4,9,9,10,9]
df = pd.DataFrame({"Month": months,
                   "values_1": values_1,
                   "values_2": values_2})

print(df)

df = df.groupby('Month')[['values_1', 'values_2']].std().round(2)
df = df.reset_index(drop = False)
print(df)
</code>```

Result looks like this:

```<code>    Month  values_1  values_2
0   Feb      2.94      1.63
1   Jan      2.87      1.26
2   Mar      4.27      0.50
</code>```

Now I want to modify the code so that I get the same type/looks of the result, but with max-min values instead of standard deviation.

答:
Update: added numpy.ptp
IIUC, you can try  using agg with a list of aggregating functions like this:

```<code>df = df.groupby('Month')[['values_1', 'values_2']].agg(['min', 'max', 'std', np.ptp]).round(2)
</code>```

Output:

```<code>  Month values_1               values_2
             min max   std ptp      min max   std ptp
0   Feb        3   9  2.94   6        4   8  1.63   4
1   Jan        1   7  2.87   6        5   8  1.26   3
2   Mar        1  11  4.27  10        9  10  0.50   1
</code>```

Body:
I want to calculate difference between max and min value for each group in pandas dataframe.
For example, I wrote a code that calculates standard deviation for each group.

import pandas as pd
import statistics

months = ["Jan", "Jan", "Jan", "Jan","Feb","Feb","Feb", "Feb", "Mar", "Mar", "Mar", "Mar"]
values_1 = [1,2,7,1,3,8,9,4,7,4,11,1]
values_2 = [8,6,6,5,6,6,8,4,9,9,10,9]
df = pd.DataFrame({"Month": months,
                   "values_1": values_1,
                   "values_2": values_2})

print(df)

df = df.groupby('Month')[['values_1', 'values_2']].std().round(2)
df = df.reset_index(drop = False)
print(df)

Result looks like this:

    Month  values_1  values_2
0   Feb      2.94      1.63
1   Jan      2.87      1.26
2   Mar      4.27      0.50

Now I want to modify the code so that I get the same type/looks of the result, but with max-min values instead of standard deviation.

Body:
Update: added numpy.ptp
IIUC, you can try  using agg with a list of aggregating functions like this:

df = df.groupby('Month')[['values_1', 'values_2']].agg(['min', 'max', 'std', np.ptp]).round(2)

Output:

  Month values_1               values_2
             min max   std ptp      min max   std ptp
0   Feb        3   9  2.94   6        4   8  1.63   4
1   Jan        1   7  2.87   6        5   8  1.26   3
2   Mar        1  11  4.27  10        9  10  0.50   1


问:
Database schema for storing the inventory item slot
I am working on a small web project where I would like to have an user inventory like in the RPG games or shooting games. I want to keep it as simple as possible. What I want to achieve is to store the slots of the items so that next time when the page is loaded, items would stay on the correct position.Items will have fixed positions such as, one slot for rifle, one slot for headgear.

What kind of relation and db schema should I create for that? I am using MySQL

I have the following schema so far:

答:
I assume some items can occupy one of several slots. I'd create a couple of new tables:

```<code>create table slots (
  id int primary key,
  name varchar(20) -- 'headgear', 'rifle', 'coin pocket'
);

create table inventory_slot (
  item_id int not null,
  slot_id int not null,
  primary key (item_id, slot_id),
  foreign key (item_id) references inventory_item(id),
  foreign key (slot_id) references slots(id)
);
</code>```

There's at least one row in inventory_slot for each possible inventory item, and there may be multiple rows in inventory_slot for the same item, if it is allowed to be held in multiple places on a given user's inventory.

Then modify the user inventory table:

```<code>create table user_inventory (
  id int primary key,
  user_id int not null,
  item_id int not null,
  slot_id int not null,
  unique key (user_id, slot_id),
  foreign key (user_id) references user(id),
  foreign key (item_id, slot_id) references inventory_slot(item_id, slot_id)
);
</code>```

This allows only one item per slot per user because of the unique key. The items must reference a row in inventory_slot so you know they can only be held in slots that have been designated as ok for a given item.

Body:
I assume some items can occupy one of several slots. I'd create a couple of new tables:

create table slots (
  id int primary key,
  name varchar(20) -- 'headgear', 'rifle', 'coin pocket'
);

create table inventory_slot (
  item_id int not null,
  slot_id int not null,
  primary key (item_id, slot_id),
  foreign key (item_id) references inventory_item(id),
  foreign key (slot_id) references slots(id)
);

There's at least one row in inventory_slot for each possible inventory item, and there may be multiple rows in inventory_slot for the same item, if it is allowed to be held in multiple places on a given user's inventory.

Then modify the user inventory table:

create table user_inventory (
  id int primary key,
  user_id int not null,
  item_id int not null,
  slot_id int not null,
  unique key (user_id, slot_id),
  foreign key (user_id) references user(id),
  foreign key (item_id, slot_id) references inventory_slot(item_id, slot_id)
);

This allows only one item per slot per user because of the unique key. The items must reference a row in inventory_slot so you know they can only be held in slots that have been designated as ok for a given item.


问:
Dynamic Buttons in React Form Are Behaving Differently When Conditionally Rendered with && vs Ternary
I'm modifying some existing code in React, and I'm running into unexpected behavior with dynamic buttons within a form.

There is a button that is rendered dynamically based on the state, isEditing.

When isEditing is false, the button will render "Edit", and it has an onClick callback that will update the state to true.

When isEditing is true, the button will render "Done" and instead of an onClick callback, it will have the property type=submit. In this case, clicking the button will trigger the onSubmit callback of the form that contains it. The form's onSubmit callback will update the isEditing state back to false.

The existing code has these different versions of the button set up with the conditional && operator, and it works as expected in toggling the state with each click.

However, when I tried to recreate the same setup with a ternary instead of the &&, the behavior is broken. When isEditing is false, clicking the button will trigger the onClick callback as expected, but then it immediately triggers the onSubmit callback of the form as well.

The compiled output of both of these appear like they should be identical, but for whatever reason they are behaving differently. I'm wondering what is causing this difference in behavior. Why is the ternary version submitting the form while the && version isn't?

Here is a code snippet with the relevant parts along with a link to a codepen where I recreated the issue. State updates are handled with React Hooks. Thanks

```<code>const App = () => {
    const [isEditing, setIsEditing] = useState(false)
    const handleSubmit = event => {
        event.preventDefault()
        setIsEditing(false)
    }
    const handleClick = () => {
        setIsEditing(true)
    }

    return (
        <>
            <form onSubmit={handleSubmit}>
                {/* WORKING */}
                {isEditing && (
                    <button type="submit">Working Done</button>
                )}
                {!isEditing && (
                    <button onClick={handleClick}>Working Edit</button>
                )}

                {/* NOT WORKING */}
                {isEditing ? (
                    <button type="submit">Broken Done</button>
                ) : (
                    <button onClick={handleClick}>Broken Edit</button>
                )}
            </form>
        </>
    )
}
</code>```

https://codepen.io/HoonKing123/pen/NWwgMar?editors=1010

答:
Thanks for asking such an interesting question as it's very confusing as well but let me try to explain what I think is happening here.

Reason

This is not happening because of && vs Ternary, but because of using a single interpolation (curly braces in JSX) for the ternary operator.

As React tries to re-use DOM elements [wherever it needs] (especially for some particular elements like buttons, especially in the same/single interpolation) to couple DOM elements with react elements.

 So, React uses the same button element for each condition with the default behaviour of submitting the form when clicked.

 Note that the default type for a button inside the form is submit (ref1, ref2).

Using separate interpolation with && in your example above enforces React to use distinct elements for each button. [see Possible Solutions below to understand this better]

Check out this discussion here, specifically this comment.

This issue will persist with && as well [not only for ternary] if we use a single interpolation for it; something like this

```<code>{ isEditing && (
    <button type="submit">Working (But Now Broken) Done</button>
  ) || (
    <button onClick={handleClick}>Working (But Now Broken) Edit</button>
) }
</code>```

See working example here

Possible Solutions

There are a couple of ways to fix this, let's discuss them one by one.

It can also work with the ternary operator just use a different interpolation statement for each case [like we did for &&] (ref). Showing this solution just to strengthen our understanding of this concept.

```<code>{ isEditing ? (
    <button type="submit">Broken (But Now Working) Done</button>
  ) : null }
{ !isEditing ? (
    <button onClick={handleClick}>Broken (But Now Working) Edit</button>
) : null }
</code>```

Use a unique key for each button as it will force React not to reuse the existing element (ref).

Use event.preventDefault() in handleClick function to explicitly prevent the default behavior of the button which is form submission (ref1 ,ref2).

Use <input type="submit"> instead of <button type="submit"> as input is a different element, it will force React not reuse the existing element (ref).

Working Code Example

All the possible solutions and explanations with reference for each one are inside this code example - https://codepen.io/MominBinShahid/pen/vYWJYXW?editors=1010

P.S. In JSX, using ternary over && is recommended, check this for in-depth understanding https://kentcdodds.com/blog/use-ternaries-rather-than-and-and-in-jsx

Body:
I'm modifying some existing code in React, and I'm running into unexpected behavior with dynamic buttons within a form.

There is a button that is rendered dynamically based on the state, isEditing.

When isEditing is false, the button will render "Edit", and it has an onClick callback that will update the state to true.

When isEditing is true, the button will render "Done" and instead of an onClick callback, it will have the property type=submit. In this case, clicking the button will trigger the onSubmit callback of the form that contains it. The form's onSubmit callback will update the isEditing state back to false.

The existing code has these different versions of the button set up with the conditional && operator, and it works as expected in toggling the state with each click.

However, when I tried to recreate the same setup with a ternary instead of the &&, the behavior is broken. When isEditing is false, clicking the button will trigger the onClick callback as expected, but then it immediately triggers the onSubmit callback of the form as well.

The compiled output of both of these appear like they should be identical, but for whatever reason they are behaving differently. I'm wondering what is causing this difference in behavior. Why is the ternary version submitting the form while the && version isn't?

Here is a code snippet with the relevant parts along with a link to a codepen where I recreated the issue. State updates are handled with React Hooks. Thanks

const App = () => {
    const [isEditing, setIsEditing] = useState(false)
    const handleSubmit = event => {
        event.preventDefault()
        setIsEditing(false)
    }
    const handleClick = () => {
        setIsEditing(true)
    }

    return (
        <>
            <form onSubmit={handleSubmit}>
                {/* WORKING */}
                {isEditing && (
                    <button type="submit">Working Done</button>
                )}
                {!isEditing && (
                    <button onClick={handleClick}>Working Edit</button>
                )}

                {/* NOT WORKING */}
                {isEditing ? (
                    <button type="submit">Broken Done</button>
                ) : (
                    <button onClick={handleClick}>Broken Edit</button>
                )}
            </form>
        </>
    )
}

https://codepen.io/HoonKing123/pen/NWwgMar?editors=1010

Body:
Thanks for asking such an interesting question as it's very confusing as well but let me try to explain what I think is happening here.

Reason

This is not happening because of && vs Ternary, but because of using a single interpolation (curly braces in JSX) for the ternary operator.

As React tries to re-use DOM elements [wherever it needs] (especially for some particular elements like buttons, especially in the same/single interpolation) to couple DOM elements with react elements.

 So, React uses the same button element for each condition with the default behaviour of submitting the form when clicked.

 Note that the default type for a button inside the form is submit (ref1, ref2).

Using separate interpolation with && in your example above enforces React to use distinct elements for each button. [see Possible Solutions below to understand this better]

Check out this discussion here, specifically this comment.

This issue will persist with && as well [not only for ternary] if we use a single interpolation for it; something like this

{ isEditing && (
    <button type="submit">Working (But Now Broken) Done</button>
  ) || (
    <button onClick={handleClick}>Working (But Now Broken) Edit</button>
) }

See working example here

Possible Solutions

There are a couple of ways to fix this, let's discuss them one by one.

It can also work with the ternary operator just use a different interpolation statement for each case [like we did for &&] (ref). Showing this solution just to strengthen our understanding of this concept.

{ isEditing ? (
    <button type="submit">Broken (But Now Working) Done</button>
  ) : null }
{ !isEditing ? (
    <button onClick={handleClick}>Broken (But Now Working) Edit</button>
) : null }

Use a unique key for each button as it will force React not to reuse the existing element (ref).

Use event.preventDefault() in handleClick function to explicitly prevent the default behavior of the button which is form submission (ref1 ,ref2).

Use <input type="submit"> instead of <button type="submit"> as input is a different element, it will force React not reuse the existing element (ref).

Working Code Example

All the possible solutions and explanations with reference for each one are inside this code example - https://codepen.io/MominBinShahid/pen/vYWJYXW?editors=1010

P.S. In JSX, using ternary over && is recommended, check this for in-depth understanding https://kentcdodds.com/blog/use-ternaries-rather-than-and-and-in-jsx


问:
How to change coc.nvim floating window colors?
I'm using coc.nvim plugin for C++ in my vim editor, here it's showing error but its colors hurt my eyes, I've been searching for solution but still don't know how to customize the colors

cocnvim floating window color

答:
In their github Discussion, there is a conversation that can solve all problems with Coc FloatingWindow:

here is the link:
enter link description here


问:
Remove strings begining with 'AUTO_INCREMENT=' in 2 files
I am trying to create a ruby script that loads 2 .sql files and removes all strings that begin with 'AUTO_INCREMENT='
There are multiple occurrences of this in my .sql files and all I want is them to be removed from both files.
Thanks for any help or input as I am new to ruby and decided to give it a try.</p>

答:
Have you tried using Regex for this? If you want to remove the whole line, you could simply match ^AUTO_INCREMENT=.+$ and replace it with an empty string. That pattern should match an entire line beginning with AUTO_INCREMENT.

Here's a good site to learn Regex if you aren't familiar with it:

Hope that works for you.


问:
App Icon Not Showing on CallKit UI for Incoming Voice Calls
My problem is exactly like this one App icon is not showing in CallKit UI

I've already added transparent app icon in AppDelegate's didFinishLaunchingWithOptions method for incoming voice call

```<code>configuration.iconTemplateImageData = UIImage.appIconTransparent.pngData()
</code>```

App icon doesn't show on CallKit UI for client to client call (using twilio).

I've added exactly same line for incoming video call for which it shows correctly. In this case icon is added in VC's init() method.

Why it doesn't show for incoming voice call? Is AppDelegate wrong place to add it?

答:
The icon image should be a square with side length of 40 points. It also must be transparent.

```<code>config.iconTemplateImageData = UIImage.init(named: "CallkitIcon")?.pngData()
</code>```

https://developer.apple.com/documentation/callkit/cxproviderconfiguration/2274376-icontemplateimagedata

Body:
My problem is exactly like this one App icon is not showing in CallKit UI

I've already added transparent app icon in AppDelegate's didFinishLaunchingWithOptions method for incoming voice call

configuration.iconTemplateImageData = UIImage.appIconTransparent.pngData()

App icon doesn't show on CallKit UI for client to client call (using twilio).

I've added exactly same line for incoming video call for which it shows correctly. In this case icon is added in VC's init() method.

Why it doesn't show for incoming voice call? Is AppDelegate wrong place to add it?

Body:
The icon image should be a square with side length of 40 points. It also must be transparent.

config.iconTemplateImageData = UIImage.init(named: "CallkitIcon")?.pngData()

https://developer.apple.com/documentation/callkit/cxproviderconfiguration/2274376-icontemplateimagedata


问:
Angular CLI throws error: 'mat-tab-nav-panel' is not a known element
I am working on my angular project and on a specific section, I need to implement Material Tab Nav Bar (as shown working on tab material component page).

Here's the HTML:

```<code><nav mat-tab-nav-bar [tabPanel]="tabPanel">
<a mat-tab-link (click)= "SomeMethod()" > Office </a>
<a mat-tab-link (click)= "SomeOtherMethod()" > NHIU </a>
<a mat-tab-link (click)= "AnotherMethod()" > TIU </a>
</nav>

<mat-tab-nav-panel #tabPanel></mat-tab-nav-panel>
</code>```

The  works fine without the [tabPanel] directive and without the <mat-tab-nav-panel #tabPanel>

But when using tab panel and nav panel, angular cli throws following errors:

error NG8002: Can't bind to 'tabPanel' since it isn't a known property
of 'nav'.

If 'mat-tab-nav-panel' is an Angular component, then verify that it is part of this module.

If 'mat-tab-nav-panel' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component
to suppress this message.

error NG8001: 'mat-tab-nav-panel' is not a known element:

If 'mat-tab-nav-panel' is an Angular component, then verify that it is part of this module.

If 'mat-tab-nav-panel' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component
to suppress this message.

<mat-tab-nav-panel #tabPanel></ mat-tab-nav-panel>

I have already imported MatTabsModule in my material module and vanilla mat-tabs also works fine in the project.

Cannot understand what the problem is here. Please help.

答: mat-tab-nav-panel is a component introduced in AngularMaterial v13.2.0 . Are you sure your current version of AngularMaterial is above 13.2 ?</p>

Body:
I am working on my angular project and on a specific section, I need to implement Material Tab Nav Bar (as shown working on tab material component page).

Here's the HTML:

 Office
 NHIU
 TIU

<mat-tab-nav-panel #tabPanel></mat-tab-nav-panel>

The  works fine without the [tabPanel] directive and without the <mat-tab-nav-panel #tabPanel>

But when using tab panel and nav panel, angular cli throws following errors:

error NG8002: Can't bind to 'tabPanel' since it isn't a known property
of 'nav'.

If 'mat-tab-nav-panel' is an Angular component, then verify that it is part of this module.

If 'mat-tab-nav-panel' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component
to suppress this message.

error NG8001: 'mat-tab-nav-panel' is not a known element:

If 'mat-tab-nav-panel' is an Angular component, then verify that it is part of this module.

If 'mat-tab-nav-panel' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component
to suppress this message.

<mat-tab-nav-panel #tabPanel></ mat-tab-nav-panel>

I have already imported MatTabsModule in my material module and vanilla mat-tabs also works fine in the project.

Cannot understand what the problem is here. Please help.