首先上整体的项目文件路径:
Spring Security是为基于Spring的应用程序提供声明式安全保护的安全性框架。Spring Security提供了完整的安全性解决方案,它能够在Web请求级别和方法调用级别处理身份认证和授权。因为基于Spring框架,所以Spring Security充分利用了依赖注入(dependency injection,DI)和面向切面的技术。Spring Security借助一系列Servlet Filter来提供各种安全性功能,但是我们只需要配置一个Filter就可以了,DelegatingFilterProxy是一个特殊的Servlet Filter,它本身所做的工作并不多。只是将工作委托给一个javax.servlet.Filter实现类,这个实现类作为一个
要使用springSecurity要添加相关的jar包
org.springframework.security
spring-security-web
4.2.2.RELEASE
org.springframework.security
spring-security-config
4.2.2.RELEASE
AbstractSecurityWebApplicationInitializer实现了WebApplicationInitializer,因此Spring会发现它,并用它在Web容器中注册DelegatingFilterProxy。尽管我们可以重载它的appendFilters()或insertFilters()方法来注册自己选择的Filter,但是要注册DelegatingFilterProxy的话,我们并不需要重载任何方法。
package spittr.config;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
/**
* AbstractSecurityWebApplicationInitializer实现了WebApplicationInitializer
* 因此Spring会发现它,并用它在Web容器中注册DelegatingFilterProxy
*/
public class SecurityWebInitializer extends AbstractSecurityWebApplicationInitializer {
}
DelegatingFilterProxy会拦截发往应用中的请求,并将请求委托给ID为springSecurityFilterChain bean。springSecurityFilterChain本身是另一个特殊的Filter,它也被称
启用Web安全性功能的最简单配置,这里只是在内存中模拟数据库用户数据
package spittr.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication() //启用内存用户存储
// withUser()方法为内存用户存储添加新的用户
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER", "ADMIN");
}
}
在pom.xmlh中引入jar包
org.apache.commons
commons-dbcp2
2.1.1
mysql
mysql-connector-java
5.1.42
org.springframework
spring-jdbc
4.3.8.RELEASE
这里使用DBCP,c3p0和这个设置差不多
配置数据源、使用JDBC模板
package spittr.config;
import java.io.IOException;
import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
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.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan("spittr")
// 自动扫描包spittr.web下的所有控制器
public class WebConfig extends WebMvcConfigurerAdapter {
// 配置jsp视图解析器
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
// 配置静态资源的处理
@Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
// 配置StandardServletMultipartResolver 上传文件用
@Bean
public MultipartResolver multipartResolver() throws IOException {
return new StandardServletMultipartResolver();
}
// 使用dbcp连接池
@Bean
public BasicDataSource dataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("com.mysql.cj.jdbc.Driver"); // com.mysql.jdbc.Driver,也可以用这个
ds.setUrl("jdbc:mysql://localhost:3306/springTest?useUnicode=true&characterEncoding=utf-8&rewriteBatchedStatements=true");
ds.setUsername("root");
ds.setPassword("root");
ds.setInitialSize(5);
ds.setMaxTotal(10);
ds.setMaxIdle(3000);
return ds;
}
// 配置JDBC模板
@Bean
public JdbcTemplate jdbcTemplate(BasicDataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
注意:如果引入mysql-connector-java的版本是6.XX的那么需要在jdbc的url后加上时区的参数,serverTimezone=UTC
不然会报错:
但是也引入了一个问题,添加了时区,但是utc默认是0时区,而北京市东八区,如果写成serverTimezone=utc+8,也不行,这样就导致存入数据库的时间会比北京时间少八小时,我看网上有说是修改本地MySQL的时区为东八区,SET GLOBAL time_zone='+8:00', 或者修改MySQL的初始化配置文件my.ini在里边[mysqld]下添加:default-time-zone=+8:00
还有一个办法是就是直接把mysql-connector-java的版本改为5.X的,然后去掉url后边serverTimezone的参数!
userInte 接口文件package spittr.inte;
import java.util.List;
import spittr.models.User;
public interface UserInte {
List findUsers(int count);
/**
* @param user
* @return the number of rows affected
*/
int add(User user);
User findById(Integer id);
}
package spittr.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import spittr.dao.UserDao;
import spittr.inte.UserInte;
import spittr.models.User;
@Component
public class UserImpl implements UserInte {
@Autowired
private UserDao userDao;
@Override
public List findUsers(int count) {
List list = new ArrayList();
for(int i=0; i
userDao dao中注入JdbcOperation
package spittr.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import spittr.models.User;
@Component
public class UserDao {
@Autowired
private JdbcOperations jdbcOperations;
public int add(User user) {
String sql = "INSERT INTO USER(NAME,PASSWORD,TIME) VALUES(?, ?, ?)";
int updateResult = jdbcOperations.update(sql, user.getName(), user.getPassword(), new Date());
return updateResult;
}
/**
* 把查找数据映射为对象
* @param id
* @return
*/
public User findById(Integer id) {
String sql = "SELECT id,NAME,PASSWORD,TIME FROM USER WHERE id=?";
User user = jdbcOperations.queryForObject(sql, new UserRowMapper(), id);
return user;
}
private static final class UserRowMapper implements RowMapper{
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
return new User(rs.getInt("id"), rs.getString("name"),rs.getString("password"),rs.getDate("time"));
}
}
}
@RequestMapping(value="/add", method=RequestMethod.GET)
public String add(){
User user = new User();
user.setName("test666");
user.setPassword("666");
int addResult = userInte.add(user);
System.out.println(addResult);
return "users";
}
@RequestMapping(value="/findById", method=RequestMethod.GET)
public String findById(@RequestParam(value="id", defaultValue="1") int id){
User user = userInte.findById(id);
System.out.println(user);
return "users";
}