springboot的优点之一就是快速搭建项目,省去了本身导入jar包和配置xml的时间,使用很是方便。css
一、建立项目project,而后选择Spring initializr,点击下一步 html
二、按图示进行勾选,点击下一步,给项目起个名字,点击肯定。java
三、项目生成有,点击add as maven project,idea 会自动下载jar包,时间比较长 mysql
四、项目生成后格式以下图所示:
其中DemoApplication.java是项目主入口,经过run/debug configuration进行配置,就可运行,由于集成了tomcat,因此该项目只需启动一遍便可,不用每次修改代码后重启项目,可是修改代码后需从新编译下,新代码才会生效。
五、生成的项目中,resources文件夹下,static文件夹下存放静态文件,好比css、js、html和图片等
templates下存放html文件,controller默认访问该文件夹下的html文件。
这个在application.properties配置文件中是能够修改的。
六、在application.properties中配置数据库信息web
spring.datasource.url = jdbc:mysql://localhost:3306/test spring.datasource.username = root spring.datasource.password = 1234 spring.datasource.driverClassName = com.mysql.jdbc.Driver #页面热加载 spring.thymeleaf.cache = false
建立一个controller类:helloworldspring
@Controller @EnableAutoConfiguration public class HelloWorld { @Autowired private IRegService regService; @RequestMapping("/") String home() { return "index"; } @RequestMapping("/reg") @ResponseBody Boolean reg(@RequestParam("loginPwd") String loginNum, @RequestParam("userId") String userId ){ String pwd = creatMD5(loginNum); System.out.println(userId+":"+loginNum); regService.regUser(userId,pwd); return true; } private String creatMD5(String loginNum){ // 生成一个MD5加密计算摘要 MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(loginNum.getBytes()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return new BigInteger(1, md.digest()).toString(16); } }
user类:sql
新建一个mapper接口数据库
public interface UserMapper { @Select("select * from users where userId = #{userId}") User findUserByUserid(@Param("userId") String userId); @Insert("insert into users (userId,pwd) values (#{userId},#{pwd})") boolean insertUsers (@Param("userId") String userId,@Param("pwd") String pwd); }
service接口及实现:json
public interface IRegService { boolean regUser(String uerId,String pwd); }
最后在主类名上添加mapperscan包扫描:缓存
@SpringBootApplication @MapperScan("com.example.mapper") public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
这是项目最后的包结构:
注意点:一、DemoApplication类跟controller包等平行
二、@controller注解返回指定页面,本文中即返回index页面,也就是templates文件夹下的index.html
三、若是须要返回json字符串、xml等,须要在有@controller类下相关的方法上加上注解@responsebody
四、@restcontroller注解的功能等同于@controller和@responsebody
有问题请留言,一块儿讨论。
五、springboot默认缓存templates下的文件,若是html页面修改后,看不到修改的效果,设置spring.thymeleaf.cache = false便可
转自:http://blog.csdn.net/alantuling_jt/article/details/54893383