Eclipse手把手写接口
概览
本节将使用Eclipse构建SpringBoot项目,整合spring security、druid、mybatis一步一步写一个接口。
整合druid+mybatis
德鲁伊、Mybatis配置部分
-
引入 maven
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- 引入 myBatis,这是 MyBatis官方提供的适配 Spring Boot 的,而不是Spring Boot自己的--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.12</version> </dependency> <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
-
配置yaml ,请根据自己配置来修改此文件!
spring: datasource: username: root password: 123456 #?serverTimezone=UTC解决时区的报错 url: jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource #Spring Boot 默认是不注入这些属性值的,需要自己绑定 #druid 数据源专有配置 initialSize: 5 minIdle: 5 maxActive: 20 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入 #如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority #则导入 log4j 依赖即可,Maven 地址: https://mvnrepository.com/artifact/log4j/log4j filters: stat,wall,log4j maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500 mybatis: #config-location: classpath:mybatis/mapper/*.xml mapper-locations: classpath:mybatis/mapper/*.xml type-aliases-package: com.kuang.mybatis.pojo
-
编写DruidConfig ,推荐在config目录下编写。
@Configuration public class DruidConfig { /* 将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建 绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效 @ConfigurationProperties(prefix = "spring.datasource"):作用就是将 全局配置文件中 前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中 */ @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource druidDataSource() { return new DruidDataSource(); } //配置 Druid 监控管理后台的Servlet; //内置 Servler 容器时没有web.xml文件,所以使用 Spring Boot 的注册 Servlet 方式 @Bean public ServletRegistrationBean statViewServlet() { ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); Map<String, String> initParams = new HashMap<>(); initParams.put("loginUsername", "admin"); //后台管理界面的登录账号 initParams.put("loginPassword", "123456"); //后台管理界面的登录密码 //后台允许谁可以访问 //initParams.put("allow", "localhost"):表示只有本机可以访问 //initParams.put("allow", ""):为空或者为null时,表示允许所有访问 initParams.put("allow", ""); //deny:Druid 后台拒绝谁访问 //initParams.put("kuangshen", "192.168.1.20");表示禁止此ip访问 //设置初始化参数 bean.setInitParameters(initParams); return bean; //这些参数可以在 com.alibaba.druid.support.http.StatViewServlet 的父类 com.alibaba.druid.support.http.ResourceServlet 中找到 } //配置 Druid 监控 之 web 监控的 filter //WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计 @Bean public FilterRegistrationBean webStatFilter() { FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(new WebStatFilter()); //exclusions:设置哪些请求进行过滤排除掉,从而不进行统计 Map<String, String> initParams = new HashMap<>(); initParams.put("exclusions", "*.js,*.css,/druid/*"); bean.setInitParameters(initParams); //"/*" 表示过滤所有请求 bean.setUrlPatterns(Arrays.asList("/*")); return bean; } }
-
配置完毕后,我们可以选择访问 : http://localhost:8080/druid/login.html
此时使用用户密码登录看看是否可以访问到德鲁伊页面。
搭建接口
-
添加实体类,记得加入自动生成get/set插件或者手动编写get/set及构造器。
@Data @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String name; private String pwd; }
-
配置mapper接口类
//@Mapper : 表示本类是一个 MyBatis 的 Mapper,等价于以前 Spring 整合 MyBatis 时的 Mapper 接口 @Mapper @Repository public interface UserMapper { //选择全部用户 List<User> selectUser(); //根据id选择用户 User selectUserById(int id); //添加一个用户 int addUser(User user); //修改一个用户 int updateUser(User user); //根据id删除用户 int deleteUser(int id); }
-
mapper映射文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.kuang.mybatis.pojo.mapper.UserMapper"> <select id="selectUser" resultType="User"> select * from user </select> <select id="selectUserById" resultType="User"> select * from user where id = #{id} </select> <insert id="addUser" parameterType="User"> insert into user (id,name,pwd) values (#{id},#{name},#{pwd}) </insert> <update id="updateUser" parameterType="User"> update user set name=#{name},pwd=#{pwd} where id = #{id} </update> <delete id="deleteUser" parameterType="int"> delete from user where id = #{id} </delete> </mapper>
-
编写controller
@RestController public class UserController { @Autowired private UserMapper userMapper; //选择全部用户 @GetMapping("/selectUser") public String selectUser(){ List<User> users = userMapper.selectUser(); for (User user : users) { System.out.println(user); } return "ok"; } //根据id选择用户 @GetMapping("/selectUserById") public String selectUserById(){ User user = userMapper.selectUserById(1); System.out.println(user); return "ok"; } //添加一个用户 @GetMapping("/addUser") public String addUser(){ userMapper.addUser(new User(5,"阿毛","456789")); return "ok"; } //修改一个用户 @GetMapping("/updateUser") public String updateUser(){ userMapper.updateUser(new User(5,"阿毛","421319")); return "ok"; } //根据id删除用户 @GetMapping("/deleteUser") public String deleteUser(){ userMapper.deleteUser(5); return "ok"; } }
现在打开服务访问http://localhost:8080/selectUser看看会不会成功。
注意!以上文件均需要自己按照自己项目进一步配置!!
配置Spring Security
-
引入maven
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
-
编写配置文件,推荐写到config目录下,和上面的druid配置文件一样。
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin() // 表单登录。跳转到security默认的登录表单页 // http.httpBasic() //basic登录 .and() .authorizeRequests() // 对请求授权 .antMatchers("/**").permitAll() //允许所有人访问/noAuth .anyRequest() // 任何请求 .authenticated()// 需要身份认证 ; //添加這行否則德魯伊登不上 http.csrf().ignoringAntMatchers("/druid/*"); http.authorizeRequests() .antMatchers("/").permitAll() .antMatchers("level1/**").hasRole("vip") .antMatchers("level2/**").hasRole("vip3") .antMatchers("level3/**").hasRole("vip2"); } //認證! @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("user").roles("USER") .and() .withUser("admin").password("admin").roles("ADMIN"); auth.jdbcAuthentication(); // auth.authenticationProvider(custAuthenticationProvider); } }
github源码:
https://github.com/modderBUG/ssminit
Druid首页点击登录无反应
https://blog.csdn.net/qq_31279347/article/details/86616305
参考地址:
https://www.cnblogs.com/hellokuangshen/p/11331338.html
来源:CSDN
作者:modderBUG
链接:https://blog.csdn.net/weixin_44499120/article/details/103879342