第一步:创建工程
点击next
点击next
这一步需要注意的是springboot不要选2.0以后的版本(2.0以后版本笔者亲试有问题,可能是本人技术问题O(∩_∩)O~),创建好工程后如果mavean仓库没有相关的jar需要花一点时间下载,请耐心等待。
第二步:配置application.properties文件
spring.datasource.url = jdbc:mysql://localhost:3306/testspring.datasource.username = rootspring.datasource.password = 123456spring.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;@RestControllerpublic class TestCotroller {@Autowired UserServiceuserService; @RequestMapping("/test")public ModelAndViewtest(@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 { UsergetUserById(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;@Servicepublic class UserServiceimplimplements UserService{@Autowired UserMapperuserMapper; @Override public UsergetUserById(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}") UserfindUserById(@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模板文件
Title 我是${user.name}
第九步:结果测试
OK,成功了,是不是很简单。
项目地址:https://github.com/seaeel/springboot-mybait-freemarker.git
欢迎加入博主技术交流群,群号:239025382
网友评论