第一步:创建工程
点击next
点击next
这一步需要注意的是springboot不要选2.0以后的版本(2.0以后版本笔者亲试有问题,可能是本人技术问题O(∩_∩)O~),创建好工程后如果mavean仓库没有相关的jar需要花一点时间下载,请耐心等待。
第二步:配置application.properties文件
spring.datasource.url = jdbc:mysql://localhost:3306/test spring.datasource.username = root spring.datasource.password = 123456 spring.datasource.driverClassName = com.mysql.jdbc.Driver #设定ftl文件路径 spring.freemarker.template-loader-path=classpath:/templates #设定静态文件路径,js,css等 spring.mvc.static-path-pattern=/static/**
前4行是数据库配置,后2行是freemarker配置
第三步:写cotroller
package com.example.demo.controller; import com.example.demo.bean.User; import com.example.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; @RestController public class TestCotroller { @Autowired UserService userService; @RequestMapping("/test") public ModelAndView test(@RequestParam(defaultValue = "0")long id) { ModelAndView modelAndView = new ModelAndView(); User user = userService.getUserById(id); modelAndView.addObject("user",user); modelAndView.setViewName("test"); return modelAndView; } }
第四步:写service
接口package com.example.demo.service; import com.example.demo.bean.User; public interface UserService { User getUserById(long id); }实现类
package com.example.demo.service.impl; import com.example.demo.bean.User; import com.example.demo.dao.UserMapper; import com.example.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserServiceimpl implements UserService{ @Autowired UserMapper userMapper; @Override public User getUserById(long id) { return userMapper.findUserById(id); } }
第五步:写DAO
package com.example.demo.dao; import com.example.demo.bean.User; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; public interface UserMapper { @Select("select * from user where id = #{userId}") User findUserById(@Param("userId") long userId); }
第六步:数据表结构
第七步:配置扫描包
package com.example.demo; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.example.demo.dao") public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
第八步:写一个ftl模板文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> 我是${user.name} </body> </html>
第九步:结果测试
OK,成功了,是不是很简单。项目地址:https://github.com/seaeel/springboot-mybait-freemarker.git
我是郭委权,欢迎加入博主技术交流群,群号:239025382