Spring Boot项目构建

步骤

(1)初始化

SpringBoot - 图1

(2)配置

SpringBoot - 图2

(3)项目依赖

SpringBoot - 图3

(4)存放位置

SpringBoot - 图4

(5)测试

新建ControllerServlet

  1. @Controller
  2. public class UserController {
  3. @ResponseBody
  4. @RequestMapping("/user/login")
  5. public String userLogin(){
  6. return "user login...";
  7. }
  8. }

启动项目

  1. @SpringBootApplication
  2. public class HomeworkApplication {
  3. public static void main(String[] args) {
  4. SpringApplication.run(HomeworkApplication.class, args);
  5. }
  6. }

注:

项目结构

SpringBoot - 图5

Web项目依赖

SpringBoot - 图6

项目配置

基本配置

application.properties

  1. # 服务器配置
  2. server.port=5000
  3. server.servlet.context-path=/app

多环境配置

示例如下

SpringBoot - 图7

application.properties

  1. # 服务器配置
  2. spring.profiles.active=dev

组件赋值

@ConfigurationProperties

示例代码

  1. @Component
  2. @ConfigurationProperties(prefix = "db")
  3. @Data
  4. public class User {
  5. private String username;
  6. private String password;
  7. }

属性配置文件

  1. # 用户信息
  2. db.username=zs
  3. db.password=123456

测试

  1. @SpringBootApplication
  2. public class Application {
  3. public static void main(String[] args) {
  4. ApplicationContext app = SpringApplication.run(Application.class, args);
  5. User user = (User) app.getBean("user");
  6. System.out.println(user.getUsername());
  7. }
  8. }

在Spring容器初始化完成之后,如果想要进行一些操作,就可以实现ComnandLineRunnerApplicationRunner接口。会自动执行run方法

示例代码

  1. @Component
  2. @ConfigurationProperties(prefix = "db")
  3. @Data
  4. public class User implements CommandLineRunner {
  5. private String username;
  6. private String password;
  7. @Override
  8. public void run(String... args) throws Exception {
  9. System.out.println("Spring容器初始化完成...");
  10. }
  11. }

控制台

SpringBoot - 图8

Servlet

示例代码

AdminServlet

  1. public class AdminServlet extends HttpServlet {
  2. public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
  3. response.getWriter().println("admin模块...");
  4. }
  5. }

注册成为容器中的组件

  1. @Configuration
  2. public class WebApplicationConfig {
  3. @Bean
  4. public ServletRegistrationBean servletRegist(){
  5. ServletRegistrationBean bean = new ServletRegistrationBean();
  6. bean.setServlet(new AdminServlet());
  7. bean.addUrlMappings("/admin");
  8. return bean;
  9. }
  10. }

过滤器

自定义过滤器

  1. public class SetCharsetEncodingFilter implements Filter {
  2. @Override
  3. public void init(FilterConfig filterConfig) throws ServletException {
  4. }
  5. @Override
  6. public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
  7. // 统一编码设置
  8. servletRequest.setCharacterEncoding("utf8");
  9. servletResponse.setCharacterEncoding("utf8");
  10. servletResponse.setContentType("text/html;charset=utf8");
  11. // 放行请求
  12. filterChain.doFilter(servletRequest, servletResponse);
  13. }
  14. @Override
  15. public void destroy() {
  16. }
  17. }

注册为容器中的组件

  1. @Component
  2. public class WebApplicationConfig {
  3. @Bean
  4. public FilterRegistrationBean charsetFilter(){
  5. FilterRegistrationBean bean = new FilterRegistrationBean();
  6. bean.setFilter(new SetCharsetEncodingFilter());
  7. bean.addUrlPatterns("/*");
  8. return bean;
  9. }
  10. }

拦截器

自定义拦截器

  1. public class PermissionInterceptor implements HandlerInterceptor {
  2. @Override
  3. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  4. // 请求拦截
  5. HttpSession session = request.getSession();
  6. if(session.getAttribute("username") == null){
  7. // 未登录, 给用户提示
  8. response.getWriter().println("请登录...");
  9. return false;
  10. }else{
  11. return true;
  12. }
  13. }
  14. @Override
  15. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
  16. }
  17. @Override
  18. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
  19. }
  20. }

注册拦截器

  1. @Configuration
  2. public class WebMvcConfig implements WebMvcConfigurer {
  3. @Override
  4. public void addInterceptors(InterceptorRegistry registry) {
  5. PermissionInterceptor permissionInterceptor = new PermissionInterceptor();
  6. registry.addInterceptor(permissionInterceptor)
  7. .addPathPatterns("/user/**")
  8. .excludePathPatterns("/user/login");
  9. }
  10. }

集成Mybatis框架

数据库配置

  1. # 数据库配置
  2. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  3. spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8
  4. spring.datasource.username=root
  5. spring.datasource.password=123456

方式一

dao层代理对象

  1. @Mapper
  2. public interface UserDao {
  3. User selectUserByUserNameAndPassword(String username, String password);
  4. }

方式二

组件扫描器

  1. @SpringBootApplication
  2. @MapperScan(basePackages = "com.cskaoyan.demo.dao")
  3. public class Application {
  4. public static void main(String[] args){
  5. SpringApplication.run(Application.class, args);
  6. }
  7. }

开启日志

  1. # Mybatis开启日志
  2. mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

事务

注解方式

开启事务

@EnableTransactionManagement

  1. @SpringBootApplication
  2. @MapperScan(basePackages = "com.cskaoyan.demo.dao")
  3. @EnableTransactionManagement
  4. public class Application {
  5. public static void main(String[] args){
  6. SpringApplication.run(Application.class, args);
  7. }
  8. }

给需要添加事务的方法添加注解

@Transactional

示例代码

  1. @Transactional
  2. @Override
  3. public int insertUser(String username, String password) {
  4. int res = userDao.insertUser(username, password);
  5. // 模拟操作异常
  6. int a = 1 / 0;
  7. return res;
  8. }