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