关于IDEA中创建springboot+security+jpa
首先本文章不会分析框架的底层代码只是帮助小白快速搭建项目,因为官方文档都写的明明白白,其中spring Security安全框架可能有部分小白看不懂官方文档
推荐看:spring Security 里面有比较详细的框架分析
废话不多说了进入正题:因为springboot推荐使用Maven(依赖管理框架) 如何使用springboot呢? 在maven的项目目录src/main/java下创建BootApplication类(可以改名)
BootApplication类 (该类是springboot的入口类用于启动springboot):@EnableTransactionManagement //用于开启事务注解 @SpringBootApplication //Springboot的启动入口类 @EnableWebSecurity //启用web安全 //@Configuration //@Import({ // DispatcherServletAutoConfiguration.class, // EmbeddedServletContainerAutoConfiguration.class, // ErrorMvcAutoConfiguration.class, // HttpEncodingAutoConfiguration.class, // HttpMessageConvertersAutoConfiguration.class, // JacksonAutoConfiguration.class, // JmxAutoConfiguration.class, // MultipartAutoConfiguration.class, // ServerPropertiesAutoConfiguration.class, // PropertyPlaceholderAutoConfiguration.class, // ThymeleafAutoConfiguration.class, // WebMvcAutoConfiguration.class, // WebSocketAutoConfiguration.class, // //})//用于自定义加载哪些类 public class BootApplication extends SpringBootServletInitializer{public static void main(String[] args) {SpringApplication.run(BootApplication.class, args); }}
pom.xml
xml version="1.0" encoding="UTF-8"?>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"> 4.0.0 com boot 0.0.1-SNAPSHOT war boot Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 1.5.6.RELEASE UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter-thymeleaf org.thymeleaf.extras thymeleaf-extras-springsecurity4 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test mysql mysql-connector-java org.projectlombok lombok 1.16.10 org.springframework.boot spring-boot-starter-data-jpa com.alibaba druid 1.0.25 org.springframework.boot spring-boot-starter-security org.springframework.boot spring-boot-starter-test org.springframework.boot spring-boot-maven-plugin
现在只需要建一个Controller类即可
@RestController public class Rest {@Autowired private TestService testService; @Secured("ROLE_user")@RequestMapping("/v1/{name}")//Rest Api风格 //@PathVariable用于获取Url上的参数 public Listboot(@PathVariable String name) {List list=testService.findAll(); System.out.println(list.get(0).getUrole()); String data = "{\"name\":\"张三\"}"; return list; }}
@RestController是springboot中的新增注解用于开发restful风格api接口 该注解相当于@Controller和@ResponseBody 合用返回的是json格式数据
因为springboot内置了tomcat所以只需要运行BootApplocation类 输入 localhost:8080/v1/name 即可在浏览器中返回{“name”:“张三”}的数据
是不是相当简单,没有ssh或ssm那么多繁琐的配置文件,也不需要在web中配置mvc,spring
如果你想使用数据库,springboot提供了jpa用于操作数据库(至于什么是jpa,简单说jpa是貌似2006年5月提出的一种ORM持久化规范,它只是一种规范,而我们最常用的hibernate是对jpa的实现,也叫jpa产品) springboot的jpa是基于hibernate的但是他进行了进一步封装,使开发人员更好的与数据库进行交互,首先需要在pom.xml中加入依赖(上面的依赖已经假如,请看上边的pom) 在springboot的配置文件中加入
#配置数据库 spring.datasource.url=jdbc:mysql://localhost:3306/springboot spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.username=root spring.datasource.password=abc spring.datasource.driver-class-name=com.mysql.jdbc.Driver
在创建bean
//@Getter @Setter 是lok插件中用于帮助自动创建getset方法还有许多注解等用 如果使用@Data //@Min 是用于字段验证的注解 /*@Data :注解在类上;提供类所有属性的 getting 和 setting 方法,此外还提供了equals、canEqual、hashCode、toString 方法 @Setter:注解在属性上;为属性提供 setting 方法 @Getter:注解在属性上;为属性提供 getting 方法 @Log4j :注解在类上;为类提供一个 属性名为log 的 log4j 日志对象 @NoArgsConstructor:注解在类上;为类提供一个无参的构造方法 @AllArgsConstructor:注解在类上;为类提供一个全参的构造方法 @Transient表示属性不与数据库映射 */ @Entity @Table(name = "user") public class User {@Id @GeneratedValue(strategy = GenerationType.AUTO)@Getter @Setter private Integer uid; @NotBlank(message = "用户名不能为空")@Column(name = "username")@Getter @Setter private String username; @NotBlank(message = "密码不能为空")@Column(name = "password")@Getter @Setter private String password; @NotNull(message = "年龄不能为空")//NotNull用于基本数据类型 @Min(value =18,message = "年龄必须大于等于18")@Column(name = "sage")@Getter @Setter private Integer sage; /* @NotNull(message = "性别不能为空")*/ @Column(name = "ssex")@NotBlank(message = "性别不为空")//只能用于String @Getter @Setter private String ssex; @Column(name = "urole")@JsonIgnore //在json序列化时忽略该属性 因为在懒加载时候返回json数据时会出现错误重复加载 @ManyToMany(cascade = CascadeType.REFRESH,fetch = FetchType.LAZY)//optional设置外键是否可以为空 @JoinTable(name ="u_r",joinColumns ={@JoinColumn(name = "uid")},inverseJoinColumns = {@JoinColumn(name = "rid")})@Getter @Setter private Seturole=new HashSet (); }
可能有注意到为什么属性没有get set方法,因为我是用来lombok这个jar,它可以使用注解来自动生成get set用于简化代码
,接着我们新建DaoImpl接口继承JpaRepository(该类已经实现了简单的crud操作我们无需实现Test接口)如果你想自己写sql可以使用@Query注解在方法上按jpa规定的格式创建方法例如下面的findByUsername方法(没有使用@Query是因为这个方法太简单框架帮我们实现了)
public interface Test extends JpaRepository,Long>{User findByUsername(String username); }
在Server层我们直接调用Test接口即可
@Autowired private Test test; public ListfindAll() {return test.findAll(); }
在controller中调用test即可实现全查
接下来看如何使用security
原来在ssh中使用security中首先导入导入security的包接着在web中配置代理过滤器
在配置security的配置文件
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
看到上面的配置文件是不是眼花 没关系springboot与security高度集成 (web配置?不需要,xml?不需要)我们来零配置来使用security
首先我们在BootApplocation上用
@EnableWebSecurity 开启Web
创建一个类继承 WebSecurityConfigurerAdapter
@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true) //开启方法权限注解 public class WebSecurityConfig extends WebSecurityConfigurerAdapter {/* @Autowired private AuthenticationManager authenticationManager;*///如果想让权限注解生效必须加注入此bean @Autowired private MyAccessDeniedHandle myAccessDeniedHandle; @Autowired private MySecurity mySecurity; @Override public void configure(WebSecurity web) throws Exception {//配置静态资源不拦截 web.ignoring().antMatchers("/static/**", "/**/*.jsp"); }@Override protected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/","/excep").permitAll()//配置不拦截Url .anyRequest().authenticated().and()//相当于结束标签 .formLogin().loginPage("/").loginProcessingUrl("/action_security")//必须是post请求 如果为Get不生效 .usernameParameter("username").passwordParameter("password")//配置登陆页面 .successForwardUrl("/login").failureUrl("/").permitAll()//所有用户都能访问这个页面 .and().rememberMe().userDetailsService(mySecurity).tokenValiditySeconds(90000).key("abc").rememberMeParameter("rememberMe").rememberMeCookieName("zxl").and().exceptionHandling().accessDeniedHandler(myAccessDeniedHandle)//配置403权限页面 myAccessDeniedHandl自定义bean 如果不想自定义可以简单的使用.accessDeniedPage()指定403页面 .and().logout().invalidateHttpSession(false).permitAll().and().csrf().disable();//关闭csrf 如果开启后注销只能使用post请求用于防止别人伪造logout }//使用BCrypt密码加密 @Bean public PasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder(); }/* //异常消息加载类 @Bean public ReloadableResourceBundleMessageSource bundleMessageSource(){ ReloadableResourceBundleMessageSource bundleMessageSource=new ReloadableResourceBundleMessageSource(); bundleMessageSource.setBasename("classpath:messages_zh_CN"); return bundleMessageSource; } @Bean //自定义的验证类 public DaoAuthenticationProvider daoAuthenticationProvider(){ DaoAuthenticationProvider daoAuthenticationProvider=new DaoAuthenticationProvider(); daoAuthenticationProvider.setHideUserNotFoundExceptions(false); daoAuthenticationProvider.setPasswordEncoder(passwordEncoder()); daoAuthenticationProvider.setUserDetailsService(mySecurity); return daoAuthenticationProvider; } //加载异常消息 @Bean public ProviderManager providerManager(){ Listlist=new ArrayList<>(); list.add(daoAuthenticationProvider()); ProviderManager providerManager=new ProviderManager(list); providerManager.setMessageSource(bundleMessageSource()); return providerManager; }*/ @Bean //自定义的验证类 public DaoAuthenticationProvider daoAuthenticationProvider(){DaoAuthenticationProvider daoAuthenticationProvider=new DaoAuthenticationProvider(); daoAuthenticationProvider.setHideUserNotFoundExceptions(false);//用于捕捉用户不存在异常 daoAuthenticationProvider.setPasswordEncoder(passwordEncoder()); daoAuthenticationProvider.setUserDetailsService(mySecurity); return daoAuthenticationProvider; }}
该类相当于Security中xml配置文件 如果想使用xml与其混合使用可以使用@Configuration注解来引用xml
原来使用security的自定义国际化需要配置bean 现在无需配置只需要在maven的resources文件夹创建一个空的messages.properties 在创建一个messages_zh_CN.properties文件夹org/springframework/security/spring-security-core/4.2.3.RELEASE/spring-security-core-4.2.3.RELEASE.jar!/org/springframework/security/messages_zh_CN.properties
中复制到刚才的zh_CN文件夹中即可自定义异常消息
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
