为类名提供了错误类型的ID预期:类java.lang.Long,得到了类java.lang.String

时间:2019-03-12 18:26:19

标签: java spring security spring-security

我正在为我的项目使用spring security,但是在数据库中命名用户的实体主键列ID类型为bigint。该实体ID类型长。这些类型是兼容的。但是项目错误“ com.app.model.User。期望:类java.lang.Long,得到类java.lang.String”。字符串的用户实体ID列长要我更改。


用户模型

 @Entity
 @Table(name = "user")
 public class User implements Serializable {

private static final long serialVersionUID = 1L;

public User() {

}

@Id
@Column(name = "id")
private Long id;

public Long getUserid() {
    return id;
}

public void setUserid(Long id) {
    this.id = id;
}

@Column(name = "username")
private String username;

@Column(name = "password", nullable = false)
private String password;

@Column(name = "enabled", nullable = false)
private boolean enabled;

@OneToMany(mappedBy = "user")
private List<UserRole> userRoles;

//getter setter

UserRole模型

@Entity
@Table(name = "user_role")
public class UserRole implements Serializable {
/**
 * 
 */
private static final long serialVersionUID = 1L;

public UserRole() {

}

@Id
private Long id;

@ManyToOne(fetch = FetchType.LAZY, targetEntity = User.class)
@MapsId("user_id")
public User user;

@ManyToOne(fetch = FetchType.LAZY, targetEntity = Role.class)
@MapsId("role_id")
private Role role;

//getter setter

角色模型

@Entity
@Table(name = "user_role")
public class Role implements Serializable{
/**
 * 
 */
private static final long serialVersionUID = 1L;

@Id
private Long id;

@Column(name = "role_name")
private String roleName;

@OneToMany(mappedBy = "role", cascade = CascadeType.ALL, fetch = 
FetchType.LAZY)
private List<UserRole> userRoles;

//getter setter

UserDetailsS​​erviceImpl

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

public UserDetailsServiceImp() {
}

@Autowired
private UserService userService;

@Transactional(readOnly = true)
@Override
public UserDetails loadUserByUsername(String username) throws 
UsernameNotFoundException {

    com.app.model.User user = userService.findUserByUsername(username);
    if (user == null) {
        throw new UsernameNotFoundException("User not found.");
    }

    User securityUser = new User(user.getUsername(), user.getPassword(), 
true, true, true, true,
            buildUserAuthority(user.getUserRoles()));
    return securityUser;
}

private List<GrantedAuthority> buildUserAuthority(List<UserRole> userRoles) {
    Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();

    for (UserRole userRole : userRoles) {
        setAuths.add(new 
SimpleGrantedAuthority(userRole.getRole().getRoleName()));
    }

    List<GrantedAuthority> results = new ArrayList<GrantedAuthority>(setAuths);
    return results;
}

}


安全配置

 @ComponentScan("com.app")
 @EnableWebSecurity
 public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

@Bean
public BCryptPasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
};

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/login", "/").permitAll().antMatchers("/**").hasRole("ADMIN").and()
            .formLogin().loginPage("/login").defaultSuccessUrl("/main").failureUrl("/login-status-error")
            .permitAll().usernameParameter("username").passwordParameter("password").and().logout()
            .logoutSuccessUrl("/logout-success").invalidateHttpSession(true).permitAll().and().csrf();
}

@Autowired
protected void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    // auth.authenticationProvider(authenticationProvider());
}

应用配置

@Configuration
@EnableWebMvc
@ComponentScan("com.app")
@EnableTransactionManagement
public class AppConfig implements WebMvcConfigurer{

private static final Logger logger = LoggerFactory.getLogger(AppConfig.class);

@Autowired
public AppConfig() {

}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

@Bean
public ViewResolver getInternalResourceViewResolver() {
    InternalResourceViewResolver bean = new InternalResourceViewResolver();
    bean.setViewClass(JstlView.class);
    bean.setPrefix("/WEB-INF/pages/");
    bean.setSuffix(".jsp");
    return bean;
}
@Bean
public LocalSessionFactoryBean getSessionFactory() {
    logger.info("Building session factory...");

    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();

    sessionFactory.setDataSource(getApplicationDataSource());

    sessionFactory.setPackagesToScan("com.app.model");

    Properties hibernateProperties = new Properties();
    hibernateProperties.setProperty("hibernate.dialect", "com.app.config.CustomPostgreSQLDialect");
    hibernateProperties.setProperty("hibernate.show_sql", "true");
    hibernateProperties.setProperty("hibernate.format_sql", "false");
    hibernateProperties.setProperty("hibernate.temp.use_jdbc_metadata_defaults","false");
    hibernateProperties.setProperty("hibernate.default_schema","public");

    //Caching
    hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", "true");
    hibernateProperties.setProperty("hibernate.cache.use_query_cache","true");
    hibernateProperties.setProperty("hibernate.generate_statistics","false");
    hibernateProperties.setProperty("hibernate.cache.region.factory_class","infinispan");
    hibernateProperties.setProperty("hibernate.cache.infinispan.cfg","org/infinispan/hibernate/cache/commons/builder/infinispan-configs-local.xml");
    hibernateProperties.setProperty("javax.persistence.sharedCache.mode","ENABLE_SELECTIVE");

    sessionFactory.setHibernateProperties(hibernateProperties);

    logger.info("Session factory builded successfully...");

    return sessionFactory;
}

@Bean("applicationDataSource")
public DataSource getApplicationDataSource() {
    logger.info("Initializing data source...");
    HikariDataSource ds = new HikariDataSource();
    ds.setDriverClassName("org.postgresql.Driver");
    ds.setJdbcUrl("jdbc:postgresql://localhost:5432/vbs_db");
    ds.setUsername("postgres");
    ds.setPassword("postgress");
    ds.setConnectionTimeout(Integer.parseInt("20000"));
    ds.setMinimumIdle(Integer.parseInt("5"));
    ds.setMaximumPoolSize(Integer.parseInt("20"));
    ds.setIdleTimeout(Integer.parseInt("300000"));
    return ds;
}

@Bean
@Autowired
public PlatformTransactionManager getTransactionManager(SessionFactory sessionFactory) {
    HibernateTransactionManager transactionManager = new HibernateTransactionManager();
    transactionManager.setSessionFactory(sessionFactory);
    return transactionManager;
}

ApplicationServletInitializer

public class ApplicationServletInitializer extends 
 AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
    return new Class[] { SecurityConfig.class, AppConfig.class };
}

@Override
protected Class<?>[] getServletConfigClasses() {
    return new Class[] { AppConfig.class };
}

@Override
protected String[] getServletMappings() {
    return new String[] { "/" };
}

Pom XML

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>VeterinerBilgiSistemi</groupId>
<artifactId>VeterinerBilgiSistemi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<dependencies>
    <!-- SPRİNG -->

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.1.4.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.1.4.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>5.1.4.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.1.4.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.1.4.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <version>5.1.4.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-core -->
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
        <version>5.1.3.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-web -->
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>5.1.3.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-config -->
    <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-config -->
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>5.1.4.RELEASE</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>5.1.3.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>5.1.4.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>5.1.4.RELEASE</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/jstl/jstl -->
    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet/jsp-api -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.0</version>
        <scope>provided</scope>
    </dependency>

    <!-- HİBERNATE -->
    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.3.7.Final</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.3.7.Final</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-tools -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-tools</artifactId>
        <version>5.3.7.Final</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.3.6.Final</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/com.zaxxer/HikariCP -->
    <dependency>
        <groupId>com.zaxxer</groupId>
        <artifactId>HikariCP</artifactId>
        <version>3.3.1</version>
    </dependency>


    <!-- CACHE -->
    <!-- https://mvnrepository.com/artifact/org.infinispan/infinispan-hibernate-cache-v53 -->
    <dependency>
        <groupId>org.infinispan</groupId>
        <artifactId>infinispan-hibernate-cache-v53</artifactId>
        <version>9.4.6.Final</version>
    </dependency>

    <!-- JAXB -->
    <!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api -->
    <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
        <version>2.3.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-impl -->
    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-impl</artifactId>
        <version>2.3.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.glassfish.jaxb/jaxb-runtime -->
    <dependency>
        <groupId>org.glassfish.jaxb</groupId>
        <artifactId>jaxb-runtime</artifactId>
        <version>2.3.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.1-api</artifactId>
        <version>1.0.2.Final</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.json/json -->
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20180813</version>
    </dependency>


    <!-- PostgreSQL -->
    <!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>42.2.5</version>
    </dependency>

    <!-- Jackson JSON Mapper -->
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.7</version>
    </dependency>

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.7.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.json.bind/javax.json.bind-api -->
    <dependency>
        <groupId>javax.json.bind</groupId>
        <artifactId>javax.json.bind-api</artifactId>
        <version>1.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.8</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.json/json -->
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20180813</version>
    </dependency>

</dependencies>


<build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.0</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <version>3.2.1</version>
            <configuration>
                <warSourceDirectory>WebContent</warSourceDirectory>
            </configuration>
        </plugin>
    </plugins>
</build>


登录JSP

<div class="d-flex justify-content-center h-100">
    <div class="card">
        <div class="card-header">
            <h3>VBS GİRİŞ PANELİ</h3>
            <div class="d-flex justify-content-end social_icon">
                <span><i class="fab fa-google-plus-square"></i></span>
            </div>
        </div>
        <div class="card-body">
            <form name='login' action="${context}/login" method='POST'>
                <div class="input-group form-group">
                    <div class="input-group-prepend">
                        <span class="input-group-text"><i class="fas fa-user"></i></span>
                    </div>
                    <input type="text" name="username" class="form-control" placeholder="Kullanıcı Adı">

                </div>
                <div class="input-group form-group">
                    <div class="input-group-prepend">
                        <span class="input-group-text"><i class="fas fa-key"></i></span>
                    </div>
                    <input type="password" name="password" class="form-control" placeholder="Parola">
                </div>
                <div class="row align-items-center remember">
                    <input type="checkbox">Beni Hatırla
                </div>
                <div class="form-group">
                    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
                    <input type="submit" value="Giriş" class="btn float-right login_btn">
                </div>
            </form>
                <c:if test="${not empty errorMessge}"><div style="color:red; font-weight: bold;
                 margin: 30px 0px;">${errorMessge}</div></c:if>
        </div>
    </div>
</div>

0 个答案:

没有答案