前言:学习springboot后,做个小项目练习一下
新建SpringBoot项目
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 @Controller public class HelloController { @RequestMapping ("/hello" ) @ResponseBody public String hello () { return "hello world" ; } }
运行访问http://localhost:8080/hello 访问成功(注意要加注解@ResponseBody或者@RestController,@ResponseBody 表示该方法的返回结果直接写入HTTP response body中)
application.properties springboot配置文件 位于resources文件夹下
1 2 3 4 server.port =8080 server.servlet.context-path =/orangespring.thymeleaf.prefix =classpath:/templates/spring.thymeleaf.suffix =.html
maven中添加下列依赖用于使用thymeleaf
1 2 3 4 <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-thymeleaf</artifactId > </dependency >
在resources/templates中新建index.html,在resources/static中新建index2.html
HelloController新增以下代码
1 2 3 4 5 6 7 8 @RequestMapping ("/html" )public String html () { return "index" ; } @RequestMapping ("/html2" )public String html2 () { return "index.html" ; }
启动后target目录如下
访问Controller http://localhost:8080/orange/html
访问Controller http://localhost:8080/orange/html2
访问static下资源 http://localhost:8080/orange/index2.html
热部署 1、File | Settings | Build, Execution, Deployment | Compiler 中选择Build project automatically
2、Ctrl+Shift+a 搜索 registry 或者 Ctrl+Shift+Alt+/
compiler.automake.allow.when.app.running -> 自动编译 compile.document.save.trigger.delay -> 自动更新文件
主要是针对静态文件如JS,CSS的更新,将延迟时间减少后,直接按F5刷新页面就能看到效果!
3、Run/Debug Configurations
4、maven 添加下列依赖 spring-boot-devtools 是自动重启,但如果项目大,重启时间慢,建议还是别用,直接Ctrl+Shift+F9
1 2 3 4 5 <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-devtools</artifactId > <optional > true</optional > </dependency >
5、 浏览器缓存 F12 network中勾选Disable cache
或者F12 进入setting(F1),勾选Disable cache
html获取ModelAndView中的数据 1 2 3 4 5 6 7 @RequestMapping ("/getData" )public ModelAndView getData () { ModelAndView model = new ModelAndView(); model.addObject("method" ,"GetData" ); model.setViewName("index.html" ); return model; }
在index.htmk中使用Thymeleaf获取数据
1 <li th:text ="$ {method} " ></li >
目录结构层次
request包 新建BaseRequset.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 @Data public abstract class BaseRequset implements Serializable { private static final long serialVersionUID = 985010454743040538L ; public String requestIp; public String requestTime; }
request包 新建UserRequest.java
1 2 3 4 5 6 7 8 9 10 11 12 13 package com.scy.orange.request;import lombok.Getter;import lombok.Setter;@Getter @Setter public class UserRequest extends BaseRequset { private int id; private String username; }
enums包 新建CommonResultCodeEnum.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 package com.scy.orange.enums;public enum CommonResultCodeEnum { SUCCESS("000000" ,"成功" ), SYSTEM_ERROR("999999" ,"系统" ); private final String code; private final String desc; public String getCode () { return code; } public String getDesc () { return desc; } CommonResultCodeEnum(String code,String desc){ this .code = code; this .desc = desc; } public static CommonResultCodeEnum getResultCode (String code) { for (CommonResultCodeEnum resultCode:values()){ if (resultCode.getCode().equals(code)){ return resultCode; } } return SYSTEM_ERROR; } }
vo包 新建ResultModel.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 package com.scy.orange.vo;import com.scy.orange.enums.CommonResultCodeEnum;import lombok.Data;import java.io.Serializable;@Data public class ResultModel <T > implements Serializable { private static final long serialVersionUID = -9090347033463853016L ; private Integer count; private T result; private String code; private String msg; public ResultModel () {}; public ResultModel (String code, String msg) { this .code= code; this .msg = msg; } public ResultModel (T result,String msg,String code) { this .result = result; this .msg = msg; } public ResultModel<T> setSuccess (T result) { this .result = result; this .msg = CommonResultCodeEnum.SUCCESS.getDesc(); this .code= CommonResultCodeEnum.SUCCESS.getCode(); return this ; } public ResultModel<T> setSuccess () { return this .setSuccess(null ); } }
HelloController.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 import com.scy.orange.request.UserRequest;import com.scy.orange.vo.ResultModel;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import java.util.ArrayList;import java.util.List;@Controller public class HelloController { @RequestMapping ("/hello" ) @ResponseBody public String hello () { return "hello world" ; } @RequestMapping ("/getData" ) @ResponseBody public ResultModel<List<UserRequest>> userList(@RequestBody UserRequest userRequest){ List<UserRequest> userRequestlist = new ArrayList<UserRequest>(); String[] name = new String[]{ "Tom" ,"Jack" ,"Cameron" ,"Ewen" ,"William" ,"Matthew" ,"David" }; for (int i = 0 ;i<name.length;i++){ userRequest = new UserRequest(); userRequest.setId(i); userRequest.setUsername(name[i]); userRequestlist.add(userRequest); } return new ResultModel<List<UserRequest>>().setSuccess(userRequestlist); } @RequestMapping ("/index" ) public String index () { return "index" ; } }
index.html 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 <!DOCTYPE html> <html lang ="en" > <head > <meta charset ="UTF-8" > <title > index</title > <script type ="text/javascript" src ="/orange/js/jquery-3.4.1.min.js" > </script > </head > <body > <script type ="text/javascript" > $.fn.serializeJSON=function ( ) { var serializeObj={}; var array=this .serializeArray(); $(array).each(function ( ) { if (serializeObj[this .name]){ if ($.isArray(serializeObj[this .name])){ serializeObj[this .name].push(this .value); }else { serializeObj[this .name]=[serializeObj[this .name],this .value]; } }else { serializeObj[this .name]=this .value; } }); return serializeObj; } $(function ( ) { console .log("js ready" ); $("#submitForm" ).on('click' , function (event ) { event.preventDefault(); console .log("ajax requset" ); $.ajax({ url : "/orange/getData" , method : 'post' , contentType : 'application/json' , data : JSON .stringify($('#form1' ).serializeJSON()), success : function (data) { console .log(data); }, error : function (e) { console .log("Error" + e); } }); }); }); /* $(document ).ready(function ( ) { console .log("js ready" ); $("#submitForm" ).on('click' , function (event ) { event.preventDefault(); console .log("ajax requset" ); $.ajax({ url : "/orange/getData" , method : 'post' , contentType : 'application/json' , data : JSON .stringify($('#form1' ).serializeJSON()), success : function (data) { console .log(data); }, error : function (e) { console .log("Error" + e); } }); }); }); */ </script > <form id ="form1" > <table > <tr > <th > ID:</th > <th > <input type ="text" id ="id" name ="id" value ="1" > </th > </tr > <tr > <td > 用户名:</td > <td > <input type ="text" id ="name" name ="name" value ="Jack" > </td > </tr > <tr > <td > <input type ="button" value ="提交" id ="submitForm" > </td > </tr > </table > </form > </body > </html >
application.properties 1 2 3 4 5 server.port =8080 server.servlet.context-path =/orangespring.thymeleaf.prefix =classpath:/templates/spring.thymeleaf.suffix =.htmlspring.thymeleaf.cache =false
运行截图
访问 http://localhost:8080/orange/index 并提交表单
异常处理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 package com.scy.orange.exceptions;import com.scy.orange.enums.CommonResultCodeEnum;import org.springframework.util.StringUtils;import java.io.Serializable;public class BizException extends RuntimeException implements Serializable { private static final long serialVersionUID = -5728999797840771015L ; private String code; private String msg; private String detailMessage; public BizException () { super (); } public BizException (CommonResultCodeEnum resultCode) { super (); this .code = resultCode.getCode(); this .msg = resultCode.getDesc(); } public BizException (String code, String message) { super (); this .code = code; this .msg = message; } public BizException (CommonResultCodeEnum resultCode, String detailMessage) { super (); this .code = resultCode.getCode(); this .msg = resultCode.getDesc(); this .detailMessage = detailMessage; } public String getCode () { return code; } public void setCode (String code) { this .code = code; } public String getMsg () { return msg; } public void setMsg (String msg) { this .msg = msg; } public void setDetailMessage (String detailMessage) { this .detailMessage = detailMessage; } @Override public String getMessage () { return StringUtils.isEmpty(detailMessage) ? msg : detailMessage; } @Override public String toString () { StringBuffer controlExceptionStr = new StringBuffer(); controlExceptionStr.append("[BizException]" ); controlExceptionStr.append("code:" ); controlExceptionStr.append(code); controlExceptionStr.append(",msg:" ); controlExceptionStr.append(msg); controlExceptionStr.append(",detailMessage:" ); controlExceptionStr.append(detailMessage); return controlExceptionStr.toString(); } }
修改CommonResultCodeEnum类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 package com.scy.orange.enums;import com.scy.orange.exceptions.BizException;import org.springframework.util.Assert;public enum CommonResultCodeEnum { SUCCESS("000000" ,"运行成功" ), SYSTEM_ERROR("999999" ,"系统错误" ); private final String code; private final String desc; public String getCode () { return code; } public String getDesc () { return desc; } CommonResultCodeEnum(String code,String desc){ this .code = code; this .desc = desc; } public static CommonResultCodeEnum getResultCode (String code) { for (CommonResultCodeEnum resultCode:values()){ if (resultCode.getCode().equals(code)){ return resultCode; } } return SYSTEM_ERROR; } public static void main (String[] args) { Object s=null ; try { Assert.notNull(s, CommonResultCodeEnum.SYSTEM_ERROR.getDesc()); } catch (RuntimeException e) { throw new BizException(CommonResultCodeEnum.SYSTEM_ERROR); } } }
这就是对于异常的处理。main运行结果如下