1.pom.xml.
4.0.0
org.exam
testweb
war
1.0-SNAPSHOT
Maven Webapp
http://maven.apache.org
UTF-8
1.7.7
4.1.2.RELEASE
4.3.1.Final
3.2.5.RELEASE
org.apache.maven.plugins
maven-compiler-plugin
1.7
1.7
org.eclipse.jetty
jetty-maven-plugin
9.2.2.v20140723
/${project.artifactId}
8080
60000
org.slf4j
jcl-over-slf4j
${slf4j.version}
org.slf4j
slf4j-log4j12
${slf4j.version}
org.springframework
spring-webmvc
${spring.version}
commons-logging
commons-logging
org.springframework
spring-aop
${spring.version}
org.springframework
spring-orm
${spring.version}
org.springframework
spring-jdbc
${spring.version}
org.springframework.security
spring-security-web
${spring.security.version}
org.springframework.security
spring-security-config
${spring.security.version}
org.hibernate
hibernate-entitymanager
${hibernate.version}
org.springframework.data
spring-data-jpa
1.7.0.RELEASE
org.springframework
spring-test
${spring.version}
test
c3p0
c3p0
0.9.1.2
mysql
mysql-connector-java
5.1.26
com.fasterxml.jackson.core
jackson-databind
2.3.1
javax.servlet
javax.servlet-api
3.1.0
provided
javax.servlet.jsp
jsp-api
2.2.1-b03
provided
javax.servlet.jsp.jstl
javax.servlet.jsp.jstl-api
1.2.1
provided
org.apache.taglibs
taglibs-standard-impl
1.2.1
commons-fileupload
commons-fileupload
1.3.1
junit
junit
4.11
test
2.配置
package org.exam.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
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;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.util.Properties;
/**
* Created by xin on 15/1/7.
*/
@Configuration
@PropertySource("classpath:config.properties")
@EnableTransactionManagement
@EnableJpaRepositories(basePackages={"org.exam.repository"})
public class AppConfig{
@Resource
private Environment env;
@Bean(destroyMethod="close")
public DataSource dataSource() {
ComboPooledDataSource dataSource=new ComboPooledDataSource();
try {dataSource.setDriverClass(env.getProperty("c3p0.driverClass"));} catch (PropertyVetoException e) {e.printStackTrace();}
dataSource.setJdbcUrl(env.getProperty("c3p0.jdbcUrl"));
dataSource.setUser(env.getProperty("c3p0.user"));
dataSource.setPassword(env.getProperty("c3p0.password"));
dataSource.setInitialPoolSize(Integer.valueOf(env.getProperty("c3p0.initialPoolSize")));
dataSource.setAcquireIncrement(Integer.valueOf(env.getProperty("c3p0.acquireIncrement")));
dataSource.setMinPoolSize(Integer.valueOf(env.getProperty("c3p0.minPoolSize")));
dataSource.setMaxPoolSize(Integer.valueOf(env.getProperty("c3p0.maxPoolSize")));
dataSource.setMaxIdleTime(Integer.valueOf(env.getProperty("c3p0.maxIdleTime")));
dataSource.setIdleConnectionTestPeriod(Integer.valueOf(env.getProperty("c3p0.idleConnectionTestPeriod")));
return dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
HibernateJpaVendorAdapter jpaVendorAdapter=new HibernateJpaVendorAdapter();
jpaVendorAdapter.setGenerateDdl(true);
jpaVendorAdapter.setShowSql(true);
Properties jpaProperties=new Properties();
jpaProperties.setProperty("hibernate.hbm2ddl.auto", "update");//validate,create,create-drop
LocalContainerEntityManagerFactoryBean emf=new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource());
emf.setPackagesToScan("org.exam.domain");
emf.setJpaVendorAdapter(jpaVendorAdapter);
emf.setJpaProperties(jpaProperties);
return emf;
}
@Bean
public PlatformTransactionManager transactionManager(){
JpaTransactionManager transactionManager=new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
}
b.MvcConfig:spring mvc配置.启用Sprin gData Web支持,配置静态资源和视图解析器
package org.exam.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.web.config.EnableSpringDataWebSupport;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import java.util.List;
/**
* Created by xin on 15/1/7.
*/
@Configuration
@ComponentScan(basePackages={"org.exam.web"})
@EnableWebMvc
@EnableSpringDataWebSupport
public class MvcConfig extends WebMvcConfigurerAdapter{
@Override
public void configureMessageConverters(List> converters) {
converters.add(new MappingJackson2HttpMessageConverter());
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
}
@Bean
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/");
resolver.setSuffix(".jsp");
return resolver;
}
@Bean
public MultipartResolver multipartResolver(){
CommonsMultipartResolver bean=new CommonsMultipartResolver();
bean.setDefaultEncoding("UTF-8");
bean.setMaxUploadSize(8388608);
return bean;
}
}
c.SecurityConfig:spring security的配置
package org.exam.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;
/**
* Created by xin on 15/1/7.
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//暂时使用基于内存的AuthenticationProvider
auth.inMemoryAuthentication().withUser("username").password("password").roles("USER");
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/static/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//暂时禁用csrf,并自定义登录页和登出URL
http.csrf().disable()
.authorizeRequests().anyRequest().authenticated()
.and().formLogin().loginPage("/login").failureUrl("/login?error").usernameParameter("username").passwordParameter("password").permitAll()
.and().logout().logoutUrl("/logout").permitAll();
}
}
d.SecurityWebApplicationInitializer:主要任务是注册springSecurityFilterChain Filter
package org.exam.config;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
/**
* Created by xin on 15/1/7.
*/
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}
e.DispatcherServletInitializer:主要任务是注册DispatcherServlet Servlet
package org.exam.config;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
/**
* Created by xin on 15/1/7.
*/
public class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("encoding-filter", CharacterEncodingFilter.class);
encodingFilter.setInitParameter("encoding", "UTF-8");
encodingFilter.setInitParameter("forceEncoding", "true");
encodingFilter.setAsyncSupported(true);
encodingFilter.addMappingForUrlPatterns(null, true, "/*");
}
@Override
protected Class>[] getRootConfigClasses() {
return new Class>[] {AppConfig.class,SecurityConfig.class};
}
@Override
protected Class>[] getServletConfigClasses() {
return new Class>[] { MvcConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
另外:使用最小配置法FilterChainProxy的additionalFilters包含以下Filter(要注意顺序)
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter
org.springframework.security.web.context.SecurityContextPersistenceFilter
org.springframework.security.web.header.HeaderWriterFilter
org.springframework.security.web.authentication.logout.LogoutFilter
org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter
org.springframework.security.web.authentication.www.BasicAuthenticationFilter
org.springframework.security.web.savedrequest.RequestCacheAwareFilter
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter
org.springframework.security.web.authentication.AnonymousAuthenticationFilter
org.springframework.security.web.session.SessionManagementFilter
org.springframework.security.web.access.ExceptionTranslationFilter
org.springframework.security.web.access.intercept.FilterSecurityInterceptor
其中SecurityContextPersistenceFilter就是使用Session保存用户认证通过的Authentication.下面简要看看doFilter方法
//前面省略
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContext contextBeforeChainExecution = repo.loadContext(holder);
try {
SecurityContextHolder.setContext(contextBeforeChainExecution);
chain.doFilter(holder.getRequest(), holder.getResponse());
} finally {
SecurityContext contextAfterChainExecution = SecurityContextHolder.getContext();
// Crucial removal of SecurityContextHolder contents - do this before anything else.
SecurityContextHolder.clearContext();
repo.saveContext(contextAfterChainExecution, holder.getRequest(), holder.getResponse());
request.removeAttribute(FILTER_APPLIED);
if (debug) {
logger.debug("SecurityContextHolder now cleared, as request processing completed");
}
}
其中repo就是初始化spring容器时通过构造方法注入的HttpSessionSecurityContextRepository
源码:http://download.csdn.net/detail/xiejx618/8349559