龙空技术网

Myeclipse 开发SpringBoot 整合maven+mybatis+freemarker+oracle

Richard菌 154

前言:

而今各位老铁们对“myeclipse创建css文件”大约比较注意,朋友们都想要知道一些“myeclipse创建css文件”的相关资讯。那么小编也在网上搜集了一些对于“myeclipse创建css文件””的相关文章,希望你们能喜欢,同学们一起来学习一下吧!

本文参考了两篇写得很好的博文1.第二个博文地址里面是个系统的文章,可以完善的学习Spring boot

因为Spring boot 官方已经不推荐JSP作为页面引擎,所以这里选择了比较熟悉freemarker,当然并不是说Spring boot不能使用JSP了,如果要用JSP作为页面引擎可以参考此博文:

因为是基于Maven进行项目的构建,IDE工具选用的Myeclipse,所以必须安装插件,如果不会可以参考此篇博文:

网上整合博文很多,为什么这里我要自己写,自己搭建一遍,因为每个人的开发环境不尽相同,而且在实际搭建过程中也会遇到很多原作者没有遇到问题,所以在参考其他大牛的基础上,小弟会重新搭建一遍,做个备忘记录

右键–>new–>other–>搜索maven–>选择maven project 默认就好,选择Create a simple project 选项。

GroupId:公司名或组织名ArtifactId:一般是project项目名

生成的文件目录结构如下

通常情况下:src/main/resources下放各种配置文件src/main/java下放源代码test文件夹下放测试文件以此类推

maven工程建好后再pom.xml中配置jar支持完整的pom.xml 这里只是配置自己支持的,如果项目中需要其他的jar还需自行配置

<project xmlns="; xmlns:xsi=";    xsi:schemaLocation=" ;>    <modelVersion>4.0.0</modelVersion>    <groupId>com.wzh</groupId>    <artifactId>SpringBootDemo</artifactId>    <version>0.0.1-SNAPSHOT</version>    <!-- 编码集 -->    <properties>        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>    </properties>    <!-- Spring Boot 启动父依赖 -->    <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>1.5.1.RELEASE</version>    </parent>    <dependencies>        <!-- Spring Boot Web 依赖 -->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>        </dependency>        <!-- Spring Boot Test 依赖 -->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-test</artifactId>            <scope>test</scope>        </dependency>        <!--视图采用freemarker渲染 -->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-freemarker</artifactId>        </dependency>        <!-- JDBC -->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-jdbc</artifactId>        </dependency>                <!-- oracle驱动 因为maven不支持oracle的jar管理,这里我导入的是本地仓的,具体maven配置支持可以百度 -->        <dependency>            <groupId>com.oracle</groupId>            <artifactId>ojdbc6</artifactId>            <version>12.1.0.2.0</version>        </dependency>                <!-- mybatis -->        <dependency>            <groupId>org.mybatis</groupId>            <artifactId>mybatis-spring</artifactId>            <version>1.2.2</version>        </dependency>        <dependency>            <groupId>org.mybatis</groupId>            <artifactId>mybatis</artifactId>            <version>3.2.8</version>        </dependency>            </dependencies>    <build>        <plugins>            <plugin>                <artifactId>maven-compiler-plugin</artifactId>                <configuration>                    <source>1.6</source>                    <target>1.6</target>                </configuration>            </plugin>            <plugin>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-maven-plugin</artifactId>                <executions>                    <execution>                        <goals>                            <goal>repackage</goal>                        </goals>                    </execution>                </executions>                <dependencies>                    <dependency>                        <groupId>org.springframework</groupId>                        <artifactId>springloaded</artifactId>                        <version>1.2.5.RELEASE</version>                    </dependency>                </dependencies>            </plugin>        </plugins>        <!-- 指定最终生成jar包的文件名 -->        <finalName>springBootDemo</finalName>    </build></project>

虽然说boot的提倡的是约定优于配置,但是我们还是需要做少量的配置。

在src/main/resources创建application.properties文件,这里只是配置了部分,根据项目实际情况去配置。

## datasource 配置数据源spring.datasource.url=jdbc:oracle:thin:@localhost:1521:oraclespring.datasource.username=systemspring.datasource.password=Passwordspring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver## 验证连接的有效性spring.datasource.primary.test-while-idle=true## 获取连接时候验证,会影响性能spring.datasource.primary.test-on-borrow=false## 在连接归还到连接池时是否测试该连接spring.datasource.primary.test-on-return=falsespring.datasource.primary.validation-query=SELECT 1 FROM DUAL## 空闲连接回收的时间间隔,与test-while-idle一起使用,设置5分钟spring.datasource.primary.time-between-eviction-runs-millis=300000## 连接池空闲连接的有效时间 ,设置30分钟spring.datasource.primary.min-evictable-idle-time-millis=1800000spring.datasource.primary.initial-size=5## 指定连接池中最大的活跃连接数.spring.datasource.primary.max-active=50## 指定连接池等待连接返回的最大等待时间,毫秒单位.spring.datasource.primary.max-wait=60000## 指定必须保持连接的最小值spring.datasource.primary.min-idle=5# FREEMARKER (FreeMarkerAutoConfiguration)spring.freemarker.allow-request-override=falsespring.freemarker.allow-session-override=falsespring.freemarker.cache=truespring.freemarker.charset=UTF-8spring.freemarker.check-template-location=truespring.freemarker.content-type=text/htmlspring.freemarker.enabled=truespring.freemarker.expose-request-attributes=falsespring.freemarker.expose-session-attributes=falsespring.freemarker.expose-spring-macro-helpers=truespring.freemarker.prefer-file-system-access=truespring.freemarker.suffix=.ftlspring.freemarker.template-loader-path=classpath:/templates/spring.freemarker.settings.template_update_delay=0spring.freemarker.settings.default_encoding=UTF-8spring.freemarker.settings.classic_compatible=truespring.freemarker.order=1

创建程序入口Application.java

package com.wzh.application;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.apache.ibatis.io.VFS;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.tomcat.jdbc.pool.DataSource;import org.mybatis.spring.SqlSessionFactoryBean;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import org.springframework.jdbc.datasource.DataSourceTransactionManager;import org.springframework.transaction.PlatformTransactionManager;/** * Spring Boot 应用启动类 */@SpringBootApplication // Spring Boot 应用的标识@ComponentScan(basePackages = { "com.wzh"}) // 指定spring管理路径,就是那些bean 注解的路径@MapperScan({ "com.wzh.**.mapper" }) // mapper 接口类扫描包配置,两个*为目录通配符public class Application {    // 程序启动入口    public static void main(String[] args) {        // 启动嵌入式的 Tomcat 并初始化 Spring 环境及其各 Spring 组件        SpringApplication.run(Application.class, args);    }    // 创建数据源,因为用是mybatis-spring 1.2 取消了数据源的自动注入,所以这里需要手动配置    @Bean    @ConfigurationProperties(prefix = "spring.datasource")// 指定数据源的前缀 ,在application.properties文件中指定    public DataSource dataSource() {        return new DataSource();    }    // 创建SqlSessionFactory    @Bean    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {        //解决myBatis下 不能嵌套jar文件的问题        VFS.addImplClass(SpringBootVFS.class);                SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();        sqlSessionFactoryBean.setDataSource(dataSource());        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();        // 两个*为目录通配符        sqlSessionFactoryBean.setMapperLocations(resolver                .getResources("classpath:/mapper/**/*.xml"));        //指定扫描别名包的路径,多个bean的扫描路径,拼接以分号隔开        String typeAliasesPackage = "com.wzh.demo.domain;";            sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);        return sqlSessionFactoryBean.getObject();    }    // 创建事物管理器    @Bean    public PlatformTransactionManager transactionManager() {        return new DataSourceTransactionManager(dataSource());    }}

解决Spring Boot集成MyBatis打包成jar时,setTypeAliasesPackage("xxx")找不到类的问题

package com.wzh.application;import java.io.IOException;import java.net.URI;import java.net.URL;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import org.apache.ibatis.io.VFS;import org.springframework.core.io.Resource;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import org.springframework.core.io.support.ResourcePatternResolver;/** * Spring Boot集成MyBatis打包成jar时,找不到类的问题 * @author yuejing */public class SpringBootVFS extends VFS {    @Override    public boolean isValid() {        return true;    }    @Override    protected List<String> list(URL url, String path) throws IOException {        ClassLoader cl = this.getClass().getClassLoader();        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);        Resource[] resources = resolver.getResources(path + "/**/*.class");        List<Resource> resources1 = Arrays.asList(resources);        List<String> resourcePaths = new ArrayList<String>();        for (Resource resource: resources1) {            resourcePaths.add(preserveSubpackageName(resource.getURI(), path));        }        return resourcePaths;    }    private static String preserveSubpackageName(final URI uri, final String rootPath) {        final String uriStr = uri.toString();        final int start = uriStr.indexOf(rootPath);        return uriStr.substring(start, uriStr.length());    }}

到这里我进行了一下启动测试,看下有没有问题,能正常启动,看日志有个warn,是因为我mapper的文件夹下是空的

下面进行整合完成的整体测试,建了几个demo文件夹来放这些文件。

测试类

bean

package com.wzh.demo.domain;import java.io.Serializable;public class UserBean implements Serializable{    private static final long serialVersionUID = -2959897964759682757L;        private Long id;    private String name;    private String sex;    private Long age;        public UserBean() {        super();        // TODO Auto-generated constructor stub    }    public UserBean(Long id, String name, String sex, Long age) {        super();        this.id = id;        this.name = name;        this.sex = sex;        this.age = age;    }    public Long getId() {        return id;    }    public void setId(Long id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getSex() {        return sex;    }    public void setSex(String sex) {        this.sex = sex;    }    public Long getAge() {        return age;    }    public void setAge(Long age) {        this.age = age;    }    @Override    public String toString() {        return "UserBean [id=" + id + ", name=" + name + ", sex=" + sex                + ", age=" + age + "]";    }}

dao和service是一样的,这里只写一个

package com.wzh.demo.service.impl;import java.util.List;import java.util.Map;import javax.annotation.Resource;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.stereotype.Service;import org.springframework.transaction.TransactionStatus;import org.springframework.transaction.support.TransactionCallbackWithoutResult;import org.springframework.transaction.support.TransactionTemplate;import com.wzh.demo.dao.UserDao;import com.wzh.demo.domain.UserBean;import com.wzh.demo.service.IUserService;@Service("userService")public class UserServiceImpl implements IUserService {    @Autowired    @Qualifier(value="userDao")    private UserDao userDao;    @Override    public List<UserBean> selectUserByName(String name) {        // TODO Auto-generated method stub        return userDao.selectUserByName(name);    }        }

mapper.java

package com.wzh.demo.mapper;import java.util.List;import com.wzh.demo.domain.UserBean;public interface UserMapper {        public List<UserBean> selectUserByName(String name);}

mapper.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"";><mapper namespace="com.wzh.demo.mapper.UserMapper">    <resultMap type="UserBean" id="user">        <id property="id" column="id" />        <result property="name" column="u_name" javaType="String" />        <result property="sex" column="u_sex" javaType="String" />        <result property="age" column="u_age" javaType="java.lang.Long" />    </resultMap>    <select id="selectUserByName" resultMap="user" parameterType="UserBean">        select t.u_id,t.u_name,t.u_sex,t.u_age from t_user t where t.u_name =        #{name}    </select></mapper>

controller

package com.wzh.demo.controller;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import com.wzh.demo.domain.UserBean;import com.wzh.demo.service.IUserService;@Controller@RequestMapping("/user")public class userTestController {    @Autowired    @Qualifier(value="userService")    private IUserService userServiceImpl;        @RequestMapping("/userInfo")    public String showUserInfoByName(HttpServletRequest requset,HttpServletResponse response,Model mode)    {                //这里名字写死,然后只取一个,方便测试        UserBean user = userServiceImpl.selectUserByName("张三").get(0);        mode.addAttribute("user", user);                return "/test/userInfo";            }}

ftl模板

<!DOCTYPE html><html>  <head>    <title>MyHtml.html</title>        <meta name="keywords" content="keyword1,keyword2,keyword3">    <meta name="description" content="this is my page">    <meta name="content-type" content="text/html; charset=UTF-8">        <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->  </head>    <body>        姓名:<b>${user.name}</b></br>        性别:<b>${user.sex}</b></br>        年龄:<b>${user.age}</b></br>  </body></html>

浏览器直接访问:

展示效果

目录结构

到这一步为止就是spring boot的基本用法。不过我们还会遇到不需要内嵌tomcat的情况,需要打包为war部署到外部的tomcat,下面展示一下修改部分

pom.xml修改部分

<groupId>com.wzh</groupId>    <artifactId>SpringBootDemo</artifactId>    <version>1.0-SNAPSHOT</version>    <!--修改打包文件为war,如果需要部署到外部tomcat需放开此配置-->    <!--<packaging>war</packaging>-->
<!--如果需部署到外部tomcat需放开此配置-->        <!--        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-tomcat</artifactId>            <scope>provided</scope>        </dependency>        -->

Application.java修改部分

启动类修改继承SpringBootServletInitializer并重写SpringApplicationBuilder方法

package com.wzh.application;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.apache.ibatis.io.VFS;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.tomcat.jdbc.pool.DataSource;import org.mybatis.spring.SqlSessionFactoryBean;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import org.springframework.jdbc.datasource.DataSourceTransactionManager;import org.springframework.transaction.PlatformTransactionManager;import org.springframework.boot.builder.SpringApplicationBuilder;import org.springframework.boot.web.support.SpringBootServletInitializer;/** * Spring Boot 应用启动类,这里继承SpringBootServletInitializer并重写SpringApplicationBuilder方法 * 是为了打包为war进行外部tomcat的部署 */@SpringBootApplication // Spring Boot 应用的标识@ComponentScan(basePackages = { "com.wzh"}) // 指定spring管理路径,就是那些bean 注解的路径@MapperScan({ "com.wzh.**.mapper" }) // mapper 接口类扫描包配置,两个*为目录通配符public class Application extends SpringBootServletInitializer  {    // 程序启动入口    public static void main(String[] args) {        // 启动嵌入式的 Tomcat 并初始化 Spring 环境及其各 Spring 组件        SpringApplication.run(Application.class, args);    }    @Override    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {        return application.sources(Application.class);    }    // 创建数据源,因为用是mybatis-spring 1.2 取消了数据源的自动注入,所以这里需要手动配置    @Bean    @ConfigurationProperties(prefix = "spring.datasource")// 指定数据源的前缀 ,在application.properties文件中指定    public DataSource dataSource() {        return new DataSource();    }    // 创建SqlSessionFactory    @Bean    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {        //解决myBatis下 不能嵌套jar文件的问题        VFS.addImplClass(SpringBootVFS.class);                SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();        sqlSessionFactoryBean.setDataSource(dataSource());        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();        // 两个*为目录通配符        sqlSessionFactoryBean.setMapperLocations(resolver                .getResources("classpath:/mapper/**/*.xml"));        //指定扫描别名包的路径,多个bean的扫描路径,拼接以分号隔开        String typeAliasesPackage = "com.wzh.demo.domain;";            sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);        return sqlSessionFactoryBean.getObject();    }    // 创建事物管理器    @Bean    public PlatformTransactionManager transactionManager() {        return new DataSourceTransactionManager(dataSource());    }}

application.properties修改部分

## 项目名,方便项目访问server.contextPath=/SpringBootDemo/

现在就是打包为war 通过 进行访问了。

标签: #myeclipse创建css文件