В этой статье мы увидим, как настроить и интегрировать SpringMVC4, Spring Data JPA с Hibernate и SpringSecurity с помощью JavaConfig.
1. Сначала давайте настроим все необходимые зависимости в pom.xml
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
|
< project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" < modelVersion >4.0.0</ modelVersion > < groupId >com.sivalabs</ groupId > < artifactId >spring-javaconfig</ artifactId > < version >1.0</ version > < packaging >war</ packaging > < name >SpringApp JavaConfig Demo</ name > < properties > < java.version >1.7</ java.version > < junit.version >4.11</ junit.version > < slf4j.version >1.7.5</ slf4j.version > < logback.version >1.0.13</ logback.version > < spring.version >4.0.0.RELEASE</ spring.version > < spring-data-jpa.version >1.4.1.RELEASE</ spring-data-jpa.version > < spring-security.version >3.2.0.RELEASE</ spring-security.version > < hibernate.version >4.2.6.Final</ hibernate.version > < aspectj.version >1.7.2</ aspectj.version > < mysql.version >5.1.26</ mysql.version > < jackson-json.version >2.3.1</ jackson-json.version > < commons-dbcp.version >1.2.2</ commons-dbcp.version > < commons-lang3.version >3.1</ commons-lang3.version > </ properties > < build > < finalName >${project.artifactId}</ finalName > < plugins > < plugin > < groupId >org.apache.maven.plugins</ groupId > < artifactId >maven-compiler-plugin</ artifactId > < version >3.1</ version > < configuration > < source >${java.version}</ source > < target >${java.version}</ target > </ configuration > </ plugin > </ plugins > </ build > < dependencies > <!-- Logging dependencies --> < dependency > < groupId >org.slf4j</ groupId > < artifactId >jcl-over-slf4j</ artifactId > < version >${slf4j.version}</ version > </ dependency > < dependency > < groupId >org.slf4j</ groupId > < artifactId >slf4j-api</ artifactId > < version >${slf4j.version}</ version > </ dependency > < dependency > < groupId >org.slf4j</ groupId > < artifactId >slf4j-log4j12</ artifactId > < version >${slf4j.version}</ version > </ dependency > < dependency > < groupId >ch.qos.logback</ groupId > < artifactId >logback-classic</ artifactId > < version >${logback.version}</ version > </ dependency > <!-- Spring dependencies --> < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-context-support</ artifactId > < exclusions > < exclusion > < groupId >commons-logging</ groupId > < artifactId >commons-logging</ artifactId > </ exclusion > </ exclusions > </ dependency > < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-webmvc</ artifactId > </ dependency > < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-test</ artifactId > </ dependency > <!-- Spring Data JPA dependencies --> < dependency > < groupId >org.springframework.data</ groupId > < artifactId >spring-data-jpa</ artifactId > < version >${spring-data-jpa.version}</ version > </ dependency > < dependency > < groupId >org.hibernate</ groupId > < artifactId >hibernate-entitymanager</ artifactId > < version >${hibernate.version}</ version > </ dependency > <!-- SpringSecurity dependencies --> < dependency > < groupId >org.springframework.security</ groupId > < artifactId >spring-security-core</ artifactId > < version >${spring-security.version}</ version > </ dependency > < dependency > < groupId >org.springframework.security</ groupId > < artifactId >spring-security-web</ artifactId > < version >${spring-security.version}</ version > </ dependency > < dependency > < groupId >org.springframework.security</ groupId > < artifactId >spring-security-config</ artifactId > < version >${spring-security.version}</ version > </ dependency > < dependency > < groupId >org.springframework.security</ groupId > < artifactId >spring-security-taglibs</ artifactId > < version >${spring-security.version}</ version > </ dependency > < dependency > < groupId >org.aspectj</ groupId > < artifactId >aspectjweaver</ artifactId > < version >${aspectj.version}</ version > </ dependency > < dependency > < groupId >org.aspectj</ groupId > < artifactId >aspectjrt</ artifactId > < version >${aspectj.version}</ version > </ dependency > <!-- Testing dependencies --> < dependency > < groupId >junit</ groupId > < artifactId >junit</ artifactId > < version >${junit.version}</ version > < scope >test</ scope > </ dependency > <!-- DB dependencies --> < dependency > < groupId >mysql</ groupId > < artifactId >mysql-connector-java</ artifactId > < version >${mysql.version}</ version > </ dependency > < dependency > < groupId >commons-dbcp</ groupId > < artifactId >commons-dbcp</ artifactId > < version >${commons-dbcp.version}</ version > </ dependency > < dependency > < groupId >com.fasterxml.jackson.core</ groupId > < artifactId >jackson-databind</ artifactId > < version >${jackson-json.version}</ version > </ dependency > < dependency > < groupId >javax.mail</ groupId > < artifactId >mail</ artifactId > < version >1.4.3</ version > </ dependency > <!-- Web dependencies --> < dependency > < groupId >javax.servlet</ groupId > < artifactId >javax.servlet-api</ artifactId > < version >3.0.1</ version > < scope >provided</ scope > </ dependency > < dependency > < groupId >taglibs</ groupId > < artifactId >standard</ artifactId > < version >1.1.2</ version > < scope >compile</ scope > </ dependency > < dependency > < groupId >jstl</ groupId > < artifactId >jstl</ artifactId > < version >1.2</ version > < scope >compile</ scope > </ dependency > </ dependencies > < dependencyManagement > < dependencies > < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-framework-bom</ artifactId > < version >${spring.version}</ version > < type >pom</ type > < scope >import</ scope > </ dependency > </ dependencies > </ dependencyManagement > </ project > |
2. Настройте свойства подключения к базе данных и параметры электронной почты в application.properties
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
|
################### DataSource Configuration ########################## jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql: //localhost:3306/test jdbc.username=root jdbc.password=admin init-db= false ################### Hibernate Configuration ########################## hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.show_sql= true hibernate.hbm2ddl.auto=update ################### JavaMail Configuration ########################## smtp.host=smtp.gmail.com smtp.port= 465 smtp.protocol=smtps smtp.username=sivaprasadreddy.k @gmail .com smtp.password= support.email=sivaprasadreddy.k @gmail .com |
3. Сконфигурируйте общие компоненты уровня сервиса, такие как PropertySourcesPlaceholderConfigurer, JavaMailSender и т. Д. В com.sivalabs.springapp.config.AppConfig.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
package com.sivalabs.springapp.config; import java.util.Properties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.context.annotation.FilterType; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.env.Environment; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.scheduling.annotation.EnableScheduling; @Configuration @ComponentScan (basePackages={ "com.sivalabs.springapp" }, excludeFilters= @ComponentScan .Filter(type=FilterType.REGEX, pattern={ "com.sivalabs.springapp.web.*" })) @PropertySource (value = { "classpath:application.properties" }) @EnableScheduling @EnableAspectJAutoProxy @EnableCaching public class AppConfig { @Autowired private Environment env; @Bean public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } @Bean public JavaMailSenderImpl javaMailSenderImpl() { JavaMailSenderImpl mailSenderImpl = new JavaMailSenderImpl(); mailSenderImpl.setHost(env.getProperty( "smtp.host" )); mailSenderImpl.setPort(env.getProperty( "smtp.port" , Integer. class )); mailSenderImpl.setProtocol(env.getProperty( "smtp.protocol" )); mailSenderImpl.setUsername(env.getProperty( "smtp.username" )); mailSenderImpl.setPassword(env.getProperty( "smtp.password" )); Properties javaMailProps = new Properties(); javaMailProps.put( "mail.smtp.auth" , true ); javaMailProps.put( "mail.smtp.starttls.enable" , true ); mailSenderImpl.setJavaMailProperties(javaMailProps); return mailSenderImpl; } @Bean public CacheManager cacheManager() { return new ConcurrentMapCacheManager(); } } |
Обратите внимание, что мы исключили пакет « com.sivalabs.springapp.web. * » Из сканирования компонентов, используя новый тип REGEX excludeFilter .
Если мы не исключаем связанные с сетью пакеты и пытаемся запустить тест JUnit для bean-компонентов уровня обслуживания, мы столкнемся со следующим исключением:
java.lang.IllegalArgumentException: ServletContext требуется для настройки обработки сервлета по умолчанию
Также обратите внимание, что мы включили кэширование с помощью @EnableCaching , поэтому мы должны объявить компонент CacheManager .
4. Сконфигурируйте bean-компоненты уровня постоянства в com.sivalabs.springapp.config.PersistenceConfig.java следующим образом:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
package com.sivalabs.springapp.config; import java.util.Properties; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import org.apache.commons.dbcp.BasicDataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.core.io.ClassPathResource; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver; import org.springframework.jdbc.datasource.init.DataSourceInitializer; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; import org.springframework.orm.hibernate4.HibernateExceptionTranslator; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement @EnableJpaRepositories (basePackages= "com.sivalabs.springapp.repositories" ) public class PersistenceConfig { @Autowired private Environment env; @Value ( "${init-db:false}" ) private String initDatabase; @Bean public PlatformTransactionManager transactionManager() { EntityManagerFactory factory = entityManagerFactory().getObject(); return new JpaTransactionManager(factory); } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); vendorAdapter.setGenerateDdl(Boolean.TRUE); vendorAdapter.setShowSql(Boolean.TRUE); factory.setDataSource(dataSource()); factory.setJpaVendorAdapter(vendorAdapter); factory.setPackagesToScan( "com.sivalabs.springapp.entities" ); Properties jpaProperties = new Properties(); jpaProperties.put( "hibernate.hbm2ddl.auto" , env.getProperty( "hibernate.hbm2ddl.auto" )); factory.setJpaProperties(jpaProperties); factory.afterPropertiesSet(); factory.setLoadTimeWeaver( new InstrumentationLoadTimeWeaver()); return factory; } @Bean public HibernateExceptionTranslator hibernateExceptionTranslator() { return new HibernateExceptionTranslator(); } @Bean public DataSource dataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(env.getProperty( "jdbc.driverClassName" )); dataSource.setUrl(env.getProperty( "jdbc.url" )); dataSource.setUsername(env.getProperty( "jdbc.username" )); dataSource.setPassword(env.getProperty( "jdbc.password" )); return dataSource; } @Bean public DataSourceInitializer dataSourceInitializer(DataSource dataSource) { DataSourceInitializer dataSourceInitializer = new DataSourceInitializer(); dataSourceInitializer.setDataSource(dataSource); ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); databasePopulator.addScript( new ClassPathResource( "db.sql" )); dataSourceInitializer.setDatabasePopulator(databasePopulator); dataSourceInitializer.setEnabled(Boolean.parseBoolean(initDatabase)); return dataSourceInitializer; } } |
Здесь мы настроили компонент DataSource и JPA EntityManagerFactory с использованием реализации Hibernate.
Также мы настроили bean-компонент DataSourceInitializer для инициализации и заполнения наших таблиц начальными данными. Мы можем включить / отключить выполнение этого сценария db.sql , изменив значение свойства init-db в application.properties.
И наконец, мы включили сканирование репозиториев Spring Data JPA с использованием @EnableJpaRepositories для сканирования пакета « com.sivalabs.springapp.repositories » для интерфейсов репозитория JPA.
5. Теперь давайте настроим bean-компоненты, связанные с Web, в com.sivalabs.springapp.web.config.WebMvcConfig.java.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
package com.sivalabs.springapp.web.config; import java.util.Properties; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @ComponentScan (basePackages = { "com.sivalabs.springapp.web" }) @EnableWebMvc public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { super .addViewControllers(registry); registry.addViewController( "login/form" ).setViewName( "login" ); registry.addViewController( "welcome" ).setViewName( "welcome" ); registry.addViewController( "admin" ).setViewName( "admin" ); } @Bean public ViewResolver resolver() { InternalResourceViewResolver url = new InternalResourceViewResolver(); url.setPrefix( "/WEB-INF/jsp/" ); url.setSuffix( ".jsp" ); return url; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler( "/resources/**" ).addResourceLocations( "/resources/" ); } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } @Bean (name = "messageSource" ) public MessageSource configureMessageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename( "classpath:messages" ); messageSource.setCacheSeconds( 5 ); messageSource.setDefaultEncoding( "UTF-8" ); return messageSource; } @Bean public SimpleMappingExceptionResolver simpleMappingExceptionResolver() { SimpleMappingExceptionResolver b = new SimpleMappingExceptionResolver(); Properties mappings = new Properties(); mappings.put( "org.springframework.dao.DataAccessException" , "error" ); b.setExceptionMappings(mappings); return b; } } |
6. Настройте DispatcherService с помощью удобного класса AbstractAnnotationConfigDispatcherServletInitializer .
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
package com.sivalabs.springapp.web.config; import javax.servlet.Filter; import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter; import org.springframework.web.filter.DelegatingFilterProxy; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import com.sivalabs.springapp.config.AppConfig; public class SpringWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[] { AppConfig. class }; } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] { WebMvcConfig. class }; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } @Override protected Filter[] getServletFilters() { return new Filter[]{ new OpenEntityManagerInViewFilter() }; } } |
Здесь следует отметить несколько вещей: мы настроили AppConfig.class как классы RootConfig и WebMvcConfig.class как ServletConfigClasses, что аналогично тому, как мы настраиваем в web.xml использование ContextLoaderListener и contextConfigLocation DispatcherServlet.
Также мы зарегистрировали OpenEntityManagerInViewFilter, чтобы включить отложенную загрузку графов сущностей JPA на этапе визуализации представления.
7. Давайте настроим SpringSecurity.
Сначала давайте создадим класс SecurityUser, который расширяет класс User для нашего приложения и реализует org.springframework.security.core.userdetails.UserDetails .
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
package com.sivalabs.springapp.web.config; import java.util.ArrayList; import java.util.Collection; import java.util.Set; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import com.sivalabs.springapp.entities.Role; import com.sivalabs.springapp.entities.User; public class SecurityUser extends User implements UserDetails { private static final long serialVersionUID = 1L; public SecurityUser(User user) { if (user != null ) { this .setId(user.getId()); this .setName(user.getName()); this .setEmail(user.getEmail()); this .setPassword(user.getPassword()); this .setDob(user.getDob()); this .setRoles(user.getRoles()); } } @Override public Collection<? extends GrantedAuthority> getAuthorities() { Collection<GrantedAuthority> authorities = new ArrayList<>(); Set<Role> userRoles = this .getRoles(); if (userRoles != null ) { for (Role role : userRoles) { SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role.getRoleName()); authorities.add(authority); } } return authorities; } @Override public String getPassword() { return super .getPassword(); } @Override public String getUsername() { return super .getEmail(); } @Override public boolean isAccountNonExpired() { return true ; } @Override public boolean isAccountNonLocked() { return true ; } @Override public boolean isCredentialsNonExpired() { return true ; } @Override public boolean isEnabled() { return true ; } } |
Мы реализуем пользовательский UserDetailsService и будем использовать репозитории Spring Data JPA для загрузки сведений о пользователе.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
package com.sivalabs.springapp.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import com.sivalabs.springapp.entities.User; import com.sivalabs.springapp.services.UserService; import com.sivalabs.springapp.web.config.SecurityUser; @Component public class CustomUserDetailsService implements UserDetailsService { @Autowired private UserService userService; @Override public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { User user = userService.findUserByEmail(userName); if (user == null ){ throw new UsernameNotFoundException( "UserName " +userName+ " not found" ); } return new SecurityUser(user); } } |
Теперь создайте com.sivalabs.springapp.config.SecurityConfig.java, который содержит определения связанных с SpeingSecurity компонентов.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
package com.sivalabs.springapp.config; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; //import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private DataSource dataSource; @Autowired private CustomUserDetailsService customUserDetailsService; @Override protected void configure(AuthenticationManagerBuilder registry) throws Exception { /* registry .inMemoryAuthentication() .withUser("siva") .password("siva") .roles("USER") .and() .withUser("admin") .password("admin") .roles("ADMIN","USER"); */ //registry.jdbcAuthentication().dataSource(dataSource); registry.userDetailsService(customUserDetailsService); } @Override public void configure(WebSecurity web) throws Exception { web .ignoring() .antMatchers( "/resources/**" ); } @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() .antMatchers( "/login" , "/login/form**" , "/register" , "/logout" ).permitAll() .antMatchers( "/admin" , "/admin/**" ).hasRole( "ADMIN" ) .anyRequest().authenticated() .and() .formLogin() .loginPage( "/login/form" ) .loginProcessingUrl( "/login" ) .failureUrl( "/login/form?error" ) .permitAll(); } } |
В соответствии с нашей конфигурацией формы входа SpringSecurity, мы будем использовать следующую форму входа в login.jsp .
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
<! DOCTYPE html> <%@taglib uri="http://www.springframework.org/tags" prefix="spring"%> <%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %> <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> <%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %> < c:url var = "rootURL" value = "/" /> < html > < head > < title >Login</ title > < link href = "${rootURL}resources/bootstrap/css/bootstrap.css" media = "screen" rel = "stylesheet" type = "text/css" /> < script type = "text/javascript" src = "${rootURL}resources/jquery/jquery-1.10.2.js" ></ script > < script type = "text/javascript" src = "${rootURL}resources/bootstrap/js/bootstrap.js" ></ script > < script type = "text/javascript" src = "${rootURL}resources/js/app.js" ></ script > </ head > < body > < div class = "col-md-6 col-md-offset-2" > < c:if test = "${param.error != null}" > < div class = "alert alert-danger" > Invalid UserName and Password. </ div > </ c:if > < c:if test = "${param.logout != null}" > < div class = "alert alert-success" > You have been logged out. </ div > </ c:if > </ div > < div class = "row" > < div class = "col-md-6 col-md-offset-2" > < h2 >User Login Form</ h2 > < form:form id = "loginForm" method = "post" action = "${rootURL}login" modelAttribute = "user" class = "form-horizontal" role = "form" cssStyle = "width: 800px; margin: 0 auto;" > < div class = "form-group" > < label for = "username" class = "col-sm-2 control-label" >UserName*</ label > < div class = "col-sm-4" > < input type = "text" id = "username" name = "username" class = "form-control" placeholder = "UserName" /> </ div > </ div > < div class = "form-group" > < label for = "password" class = "col-sm-2 control-label" >Password*</ label > < div class = "col-sm-4" > < input type = "password" id = "password" name = "password" class = "form-control" placeholder = "Password" /> </ div > </ div > < div class = "form-group" > < div class = "col-sm-offset-2 col-sm-4" > < input type = "submit" class = "btn btn-primary" value = "Login" > </ div > </ div > </ form:form > </ div > </ div > </ body > </ html > |
Как только мы успешно войдем в систему, мы можем получить аутентифицированные детали использования, используя и обезопасить части представления, используя следующие:
1
2
3
4
5
6
7
8
|
< h3 >Email: < sec:authentication property = "name" /></ h3 > < h3 > < sec:authorize access = "hasRole('ROLE_ADMIN')" > < a href = "admin" >Administration</ a > </ sec:authorize > </ h3 > < p > < a href = "logout" >Logout</ a ></ p > </ body > |
- Вы можете найти исходный код на github https://github.com/sivaprasadreddy/sivalabs-blog-samples-code/tree/master/springmvc-datajpa-security-demo