Tmall_SpringBoot project practice
POJO
POJO is a simple, ordinary Java object that contains the business logic processing or persistence logic, etc., but not a JavaBean, EntityBean, which does not have any special role does not inherit or implement any other Java class or interface framework. It may contain similar JavaBean properties and getter and setter methods to access the property.
The basic meaning is to say a plain POJO Java object (not a JavaBean, EntityBean, etc.), do not play any special role, nor any Java framework to achieve the specified interface.
Wrong POJO
public class DbHello implements Hello {
//实现了接口,就不能称之为POJO,这已经不是简单的Java类了
private DictionaryDAO dao;
public void setDao(DictionaryDAO dao) {
this.dao = dao;
}
}
Right POJO
public class DbHello {
//简单的Java类,称之为POJO,不继承,不实现接口
private DictionaryDAO dao;
public void setDao(DictionaryDAO dao) {
this.dao = dao;
}
}
JPA annotations of @GeneratedValue
In JPA, @GeneratedValue
meaning annotation exists mainly as an entity to generate a primary key that uniquely identifies (JPA requires each entity Entity, you must have one and only one primary key)
@GeneratedValue
It provides primary key generation strategy. @GeneratedValue
Annotation has two attributes, respectively strategy
, and generator
wherein the generator
value of the property is a string, the default is "", which declares the name of the primary key generator (corresponding to the main key generator @SequenceGenerator same name and @TableGenerator).
JPA offers developers four primary key generation strategy, which is defined in the enumeration class GenerationType including GenerationType.TABLE
GenerationType.SEQUENCE
GenerationType.IDENTITY
GenerationType.AUTO
-IDENTITY: by way of self-ID database growth from increased primary key field, Oracle does not support this approach;
-AUTO: JPA automatically choose the right strategy is the default option;
-SEQUENCE: sequence generated by the primary key, the specified sequence annotation by @SequenceGenerator name, MySql does not support this mode
-TABLE: produced by the primary key table, the frame generated by the master key consists analog sequences, the policy may make it easier to apply database migration.
Examples
@Entity //jpa标注实体
@Table(name = "t_customer") // 创建/修改表的名称
@Data
public class Customer {
@Id // 主键
//@GeneratedValue(strategy = GenerationType.AUTO)
//主键自增 Auto为默认使用oracle自增的方式
//所以在运行时会多生成一张表 记录从1开始 记录主键
//这里不适用与mysql 但是使用
//@GeneratedValue(strategy = GenerationType.IDENTITY)报主键不能为空错误
private Long id;
@Column(name = "name", nullable = true)
// 数据库对应字段名 非空约束(可以为空)
private String name;
@Column(name = "remark", nullable = true)
// 数据库对应字段名 非空约束(可以为空)
private String remark;
......
}
RESULTFul
url redirection and forwarding
Web UI project, many Spring controller function to return directly html page views, and some view functions are to be redirected or forwarded to another url.
redirect and forward the difference between:
Redirect redirect: Redirect contains two complete request-response process,
The first is access to the original url
The second is the url server notifies the client access redirection after. After the completion of redirection, the browser's address url after redirect, rather than the original url
Redirect usage scenarios: Because the redirect will modify the browser address, so the form should be submitted using the redirect, so as not to repeat the user to refresh the page lead form submission.
Forwarding forward: complete forward contains only one request-response process, the user sends request, the server-side view of the function to deal with their own logic, then the server side there is another view of the function call, the response finally returned to the browser.
harrychinese Liuzhong Wu _ blog quoted Park
Calling sequence
Call service control layer layer
service call dao layer
dao call specific CRUD
Common Annotations
@PathVaribale
The data acquisition url
如果我们需要获取Url=localhost:8080/hello/id中的id值,实现代码如下:
@RestController
public class HelloController {
@RequestMapping(value="/hello/{id}",method= RequestMethod.GET)
public String sayHello(
@PathVariable("id") Integer id){
return "id:"+id;
}
}
同样,如果我们需要在url有多个参数需要获取,则如下代码所示来做就可以了。
@RestController
public class HelloController {
@RequestMapping(value="/hello/{id}/{name}",method=RequestMethod.GET)
public String sayHello(
@PathVariable("id") Integer id,
@PathVariable("name") String name){
return "id:"+id+" name:"+name;
}
}
@RequestParam
Gets Request Parameter
获取Url=localhost:8080/hello?id=98中id的值
@RestController
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
public String sayHello(@RequestParam("id") Integer id){
return "id:"+id;
}
}
@RequestParam注解给我们提供了这种解决方案,即允许用户不输入id时,使用默认值
@RestController
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
//required=false 表示url中可以不穿入id参数,此时就使用默认参数
public String sayHello(@RequestParam(value="id",required = false,defaultValue = "1") Integer id){
return "id:"+id;
}
}
@GetMapping
@GetMapping annotation is a combination, is an abbreviation @RequestMapping (method = RequestMethod.GET) a. The annotation HTTP Get mapped to a particular approach.
There may be employed @GetMapping (value = "/ hello") instead @RequestMapping (value = "/ hello", method = RequestMethod.GET). That allows us to streamline the code.
@RestController
After @RestController Spring 4 out of notes version of the framework, the previous version return json data needs @ResponseBody with @Controller
@RestController
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
public String sayHello(){
return "hello";
}
}
等同于下面
@Controller
@ResponseBody
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
public String sayHello(){
return "hello";
}
}
Add CORS support for cross-domain access
CORS (Cross-Origin Resource Sharing) "cross-domain resource sharing", is a W3C standard that allows the browser to send cross-domain Ajax request to the server, breaking the resource constraints in Ajax can only access this site
addMapping : configuration may be cross-domain path, any configuration can be specific to a direct request path.
allowedMethods : The method allows all requests to access the resource server across domains, such as: the POST, the GET, the PUT, the DELETE and the like.
allowedOrigins : allows all requests to access our cross-domain resource domain name, can be fixed single or multiple pieces of content, such as: "http://www.baidu.com", Baidu can only access our cross-domain resources.
allowedHeaders : allows all access request header, the request can customize any header information, such as: "X-YAUTH-TOKEN"
Unified exception handling ControllerAdvice
With spring Boot
doing web
when the background, often appear abnormal, if each exception are themselves a lot of trouble to deal with, so we create a global exception handler class to handle exceptions unity. By using @ControllerAdvice
the definition of a uniform exception handling class, rather than in each of Controller
the individually defined.
自定义全局异常处理类 GlobalExceptionHandler.java
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MyException.class)
@ResponseBody
public Result handleMyException(HttpServletRequest request, MyException e){
String message = e.getMessage();
Integer code = e.getCode();
Result result = new Result(code,message);
return result;
}
}
只需要使用 @ControllerAdvice 注解来标识即可,可以结合 @Controller 注解来理解.
@Controller 注解标识的类 拦截所有的web请求,使用 @RequestMappering() 进行匹配
@ControllerAdvice 注解标识的类 拦截程序抛出的异常,使用@ExceptionHandler() 进行匹配