总结一下后端代码的规范


1. entities类的规范

/**
 * <pre>
 *     服务器信息
 * </pre>
 *
 */
@Data
@TableName("server")
public class Server implements Serializable {

    private static final long serialVersionUID = -5144055068797033748L;

    /**
     * ID
     */
    @TableId(type = IdType.AUTO)
    private Long id;

    /**
     * 使用人
     */
    private String applyUserName;


    /**
     * 服务器名称
     */
    private String serverName;

    /**
     * 服务器状态
     */
    private String serverStatus;

    /**
     * 申请时间
     */
    private Long applyTime;

    /**
     * 释放时间
     */
    private Long releaseTime;

    /**
     * 项目名称
     */
    private String projectName;

}

总结:

  1. 不写基本类型 , 写基本类型对应的类。 会防止些错误的。
  2. 添加注释,变量是干嘛用的。
  3. 使用lombok 的依赖,@Data

2. xxxMapper.xml 规范

因为创建数据库的字段 连接是使用 _ 来进行连接的,Java中使用驼峰式进行结合的。、
所以当Java中对象的属性和表中对应的字段不同时,就需要创建下面的map了。

<mapper namespace="com.example.sens.mapper.MessageMapper">

    <resultMap id="BaseResultMap" type="com.example.sens.entity.Message">
        <id column="id" jdbcType="INTEGER" property="id"/>
        <result column="status" jdbcType="VARCHAR" property="status"/>
        <result column="content" jdbcType="VARCHAR" property="content"/>
        <result column="user_id" jdbcType="INTEGER" property="userId"/>
        <result column="create_time" jdbcType="INTEGER" property="createTime"/>
    </resultMap>

不是规范,但是是必须写的。


3. controller

@RestController
@RequestMapping("/api/user")
public class UserController {


    @Autowired
    private UserService userService;

    @Autowired
    private MessageService messageService;

    @PostMapping("/login")
    public Response login(@RequestParam("userName") String userName,
                          @RequestParam("userPass") String userPass,
                          HttpSession session) {
        User user = userService.findByUserName(userName);
        if (user == null) {
            return Response.no("用户名不存在!");
        }
        if (!Objects.equals(user.getUserPass(), userPass)) {
            return Response.no("密码不正确!");
        }
        session.setAttribute("user", user); // user的所有信息都返回,这里出了问题
        return Response.yes(user);
    }
  1. 返回的是:json, 所以,@RestController
  2. 是get请求就行 @GetMapping() , post请求就写 @PostMapping()
  3. 无论是从请求体中拿到参数,还是从请求头中拿到参数,get。post使用 @RequestParam 获得参数,@RequestBody 数据封装为一个对象一般使用post请求中。,绑定 必须
  4. 返回的必须是json对象,这个json对象方便查看。 注意!!!

版权声明:本文为qq_46539281原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。