• 使用mavens创建SpringBoot和Mybatis的web项目


    file->new->other 搜索maven,

     

     右键项目点击Properties,然后Project Facets

    项目结构

    创建一张角色表lv_role

    CREATE TABLE `lv_role` (
      `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
      `roleName` varchar(25) DEFAULT NULL COMMENT '名称',
      `permissions` text,
      `timeline` int(11) DEFAULT NULL COMMENT '创建时间',
      `updateTime` int(11) DEFAULT NULL COMMENT '修改时间',
      PRIMARY KEY (`id`),
      KEY `id` (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4;

    配置pom.xml

    <project 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">
      <modelVersion>4.0.0</modelVersion>
      <groupId>xiangxuan</groupId>
      <artifactId>xiangxuan-user</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>jar</packaging>
      <name>xiangxuan-user</name>
      <url>http://maven.apache.org</url>
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <tomcat.version>7.0.90</tomcat.version>
      </properties>
       <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.2.RELEASE</version>
            <relativePath/> 
        </parent>
      <dependencies>
      <!-- tomcatjar包 -->
      <dependency> 
       <groupId>org.apache.tomcat</groupId> 
       <artifactId>tomcat-juli</artifactId> 
       <version>${tomcat.version}</version> 
     </dependency>
       <!-- 单元测试 -->
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
         <!-- mybatis整和springboot包statr -->
              <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <!-- mybatis整和springboot 的架-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.2.0</version>
            </dependency>
            <!-- Mysql的驱动架包 -->
            <dependency>
              <groupId>mysql</groupId>
              <artifactId>mysql-connector-java</artifactId>
              <version>5.1.38</version>
            </dependency>
            <!-- 数据库连接池 --> 
            <dependency>
              <groupId>c3p0</groupId>
              <artifactId>c3p0</artifactId>
              <version>0.9.1.2</version>
            </dependency>
            <!-- redis整合springboot 的架包-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-redis</artifactId>
                <version>1.3.7.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>jaxen</groupId>
                <artifactId>jaxen</artifactId>
                <version>1.1.1</version>
            </dependency>
             <!-- mybatis整和springboot包end -->
            <!--编译jsp的jasper包依赖 statr -->
           <dependency>
                <groupId>org.apache.tomcat.embed</groupId>
                <artifactId>tomcat-embed-jasper</artifactId>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
            </dependency>
            <!--编译jsp的jasper包依赖 end -->
      </dependencies>
    </project>

    在src/main/resources文件下

    (1)添加一个config文件夹,文件夹中添加SqlMapConfig.xml文件  

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <!-- 全局settings配置,根据需要再加上 -->
        <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        </settings>
    </configuration>

    (2)添加Spring Boot 的配置application.properties文件,注意有两种格式.properties 和 .yml,它们的区别主要是书写格式不同

    ①.properties

       app.user.name = javastack

    ②.yml

      app:

        user:

         name: javastack

    我们使用的是.properties这种

    mybatis.config-location=classpath:config/SqlMapConfig.xml
    mybatis.mapper-locations=classpath*:mapper/*Mapper.xml
    spring.http.multipart.maxFileSize=100Mb
    spring.http.multipart.maxRequestSize=100Mb
    
    #--------c3p0--------------
    c3p0.jdbcUrl=jdbc:mysql://localhost:3306/xiangxuan?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull
    c3p0.user=root
    c3p0.password=root
    c3p0.driverClass=com.mysql.jdbc.Driver
    c3p0.minPoolSize=2
    c3p0.maxPoolSize=10
    c3p0.maxIdleTime=1800000
    c3p0.acquireIncrement=3
    c3p0.maxStatements=1000
    c3p0.initialPoolSize=3
    c3p0.idleConnectionTestPeriod=60
    c3p0.acquireRetryAttempts=30
    c3p0.acquireRetryDelay=1000
    c3p0.breakAfterAcquireFailure=false
    c3p0.testConnectionOnCheckout=false
    
    #----------配置项目路径------------
    server.context-path=/xiangxuan
    #----------配置端口号80------------
    server.port=80 #-----------------------配置jsp---------- spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp #-------------------配置redis------------------------ spring.redis.database=0 spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password= spring.redis.pool.maxActive=80 spring.redis.pool.maxWait=-1 spring.redis.pool.maxIdle=8 spring.redis.pool.minIdle=0 spring.redis.timeout=1000

    (3)添加log4j.properties文件

    #This is the configuring for logging displayed in the Application Server
    log4j.rootCategory=WARN,stdout
    
    #stdout configure
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern= %d %p [%t][%c.%M()][%L] - <%m>%n
    #cxf configure
    log4j.appender.cxf=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.cxf.File=../logs/cxf.log
    log4j.appender.cxf.layout=org.apache.log4j.PatternLayout
    log4j.appender.cxf.layout.ConversionPattern= %d %p [%t][%c.%M()][%L] - <%m>%n
    #third configure
    log4j.appender.third=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.third.File=../logs/third.log
    log4j.appender.third.layout=org.apache.log4j.PatternLayout
    log4j.appender.third.layout.ConversionPattern= %d %p [%t][%c.%M()][%L] - <%m>%n
    
    #fmb-platform-finance-server
    log4j.appender.financeServer=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.financeServer.File=../logs/fmb-platform-finance.log
    log4j.appender.financeServer.layout=org.apache.log4j.PatternLayout
    log4j.appender.financeServer.layout.ConversionPattern= %d %p [%t][%c.%M()][%L] - <%m>%n
    #fmb-platform-openapi
    log4j.appender.openApi=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.openApi.File=../logs/fmb-platform-openapi.log
    log4j.appender.openApi.layout=org.apache.log4j.PatternLayout
    log4j.appender.openApi.layout.ConversionPattern= %d %p [%t][%c.%M()][%L] - <%m>%n
    #fmb-platform-external
    log4j.appender.external=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.external.File=../logs/fmb-platform-external.log
    log4j.appender.external.layout=org.apache.log4j.PatternLayout
    log4j.appender.external.layout.ConversionPattern= %d %p [%t][%c.%M()][%L] - <%m>%n
    
    # Control logging for 3rd library, changing log level to DEBUG when debug
    log4j.logger.org.springframework=WARN,third
    log4j.logger.org.hibernate=WARN,third
    log4j.logger.net.sf.ehcache=WARN,third
    log4j.logger.org.apache.cxf=WARN,cxf
    log4j.logger.org.apache.catalina=WARN,cxf
    # Changing the log level to DEBUG will display SQL Hibernate generated
    log4j.logger.org.hibernate.SQL=ERROR,third
    # fmb platform project log
    log4j.logger.cn.nnj.platform.external=INFO,financeServer
    log4j.logger.cn.nnj.openapi=INFO,openApi
    log4j.logger.cn.nnj.openapi=INFO,external
    
    log4j.logger.java.sql.Connection=WARN
    log4j.logger.java.sql.Statement=WARN
    log4j.logger.java.sql.PreparedStatement=WARN

    在src/main/java文件夹下

    (1)Application.java启动类

    package org.xiangxuan.user;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication 
    public class Application 
    {
        public static void main( String[] args )
        {
            SpringApplication.run(Application.class,args);
        }
    }

    (2)RoleController控制层

    package org.xiangxuan.user.controller;
    
    import java.util.List;
    
    import javax.annotation.Resource;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.servlet.ModelAndView;
    import org.xiangxuan.user.base.BasicResult;
    import org.xiangxuan.user.entity.Role;
    import org.xiangxuan.user.service.RoleService;
    
    @RequestMapping("role")
    @Controller
    public class RoleController {
        public final Log logger = LogFactory.getLog(this.getClass());
        @Resource
        private RoleService roleService;
        
        @RequestMapping(value="/findByAll",method=RequestMethod.POST)
        @ResponseBody
        public BasicResult findByAll(Integer pageSize,Integer page) {
            BasicResult result=new BasicResult();
            result.setResult("400");
            try {
               List<Role> list=roleService.findByAll(pageSize, page);
               if(list==null||list.size()==0){
                    result.setResult("108");
                    result.setMessageString("数据不存在");    
               }else {
                    result.setData(list);
                    result.setResult("100");
                    result.setMessageString("成功");    
               }
               return result;
            } catch (Exception e) {
                logger.info("角色列表异常", e);
                result.setResult("500");
                result.setMessageString("失败");
                return result;
    
            }
            
        }
        
        @RequestMapping(value="/roleList",method=RequestMethod.GET)
        public ModelAndView roleList(Integer pageSize,Integer page,ModelAndView model) {
            BasicResult result=new BasicResult();
            result.setResult("400");
            try {
               List<Role> list=roleService.findByAll(pageSize, page);
               //将数据放置到ModelAndView对象view中,第二个参数可以是任何java类型
               model.addObject("rList", list);
               //放入jsp路径
               model.setViewName("role_list");
               return model;
            } catch (Exception e) {
               logger.info("角色列表异常", e);
               return model;
    
            }
            
        }
        
    }

    (3) bean层Role类

    package org.xiangxuan.user.entity;
    import java.io.Serializable;
    
    /**
     * 角色bean
     * @author lyy
     *
     */
    public class Role implements Serializable{
        private static final long serialVersionUID = 1L;
        private int id;//id
        private String roleName;//角色名称
        private String permissions;//权限
        private int  timeline;//创建时间
            private int updateTime;//更改时间
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getRoleName() {
            return roleName;
        }
        public void setRoleName(String roleName) {
            this.roleName = roleName;
        }
        public String getPermissions() {
            return permissions;
        }
        public void setPermissions(String permissions) {
            this.permissions = permissions;
        }
        public int getTimeline() {
            return timeline;
        }
        public void setTimeline(int timeline) {
            this.timeline = timeline;
        }
        public int getUpdateTime() {
            return updateTime;
        }
        public void setUpdateTime(int updateTime) {
            this.updateTime = updateTime;
        }
        
    }

     (4)mapper层  RoleMapper

    package org.xiangxuan.user.mapper;
    
    import java.util.List;
    
    import org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Param;
    import org.apache.ibatis.annotations.Select;
    import org.xiangxuan.user.entity.Role;
    
    /**
     * mapper层
     * @author lyy
     *
     */
    @Mapper
    public interface RoleMapper {
        
        @Select("select r.id,r.roleName,r.timeline from lv_role r ORDER BY r.timeline desc  LIMIT #{page},#{pageSize}")
        List<Role> findByAll(@Param("pageSize") Integer pageSize,@Param("page") Integer page);
    
    }

    (5)service层 RoleService

    package org.xiangxuan.user.service;
    import java.util.List;
    import org.springframework.stereotype.Service;
    import org.xiangxuan.user.entity.Role;
    
    /**
     * service层
     * @author lyy
     *
     */
    @Service
    public interface RoleService {
        List<Role> findByAll(Integer pageSize,Integer page);
    
    }

    (6)serviceimpl层 RoleServiceImpl

    package org.xiangxuan.user.service;
    import java.util.List;
    import org.springframework.stereotype.Service;
    import org.xiangxuan.user.entity.Role;
    
    /**
     * serviceimpl层
     * @author lyy
     *
     */
    @Service
    public interface RoleService {
        List<Role> findByAll(Integer pageSize,Integer page);
    
    }

    在src/main/java/wabapp/WEB-INF文件下添加jsp文件夹,在jsp文件夹下添加role_list.jsp文件

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <html>
    <head>
    <title>Insert title here</title>
    </head>
    <body>
    <table style="border: 1px solid black;">
         <tr>
          <td>角色id</td>
          <td>角色名称</td>
         </tr>
         <c:forEach items="${rList}" var="r">
            <tr>
               <td> ${r.id} <td>  
                <td> ${r.roleName}  </td>
            </tr>
        </c:forEach>
    </table>
    </body>
    </html>

    最终的结果

  • 相关阅读:
    判断操作系统
    Oracle之初体验
    判断PDF文件是否相同(通过二进制流判断)
    jQuery基础 html+css3+jquery 点击按钮切换内容
    Jquery基础,点击事件click,鼠标移入事件mouseover。通过事件改变DOM结构
    Jquery教学基础,简单的淡入淡出,隐藏显示,改变CSS等
    Vuex的高级使用及localStorage
    Vuex实现数据共享
    Vue项目代码结构简单介绍
    Vue项目环境准备
  • 原文地址:https://www.cnblogs.com/1-9-9-5/p/10952132.html
Copyright © 2020-2023  润新知