最近写了一个 Spring Boot社区项目 ,支持发帖,评论等功能,给大家分享一下。

1.项目预览

1.主页

2.问题详情页回复

3.回复通知

2.项目地址:

话不多说,先给出项目地址。

  1. Github 地址
  2. 在线预览地址

3.项目核心:

  1. 接入github,使用户可以直接使用github账号登录。
  2. 集成editormd插件,实现markdown语法编辑并显示为html。
  3. 在editormd中使用ucloud上传图片。
  4. 数据库查询分页。
  5. 使用ajax提交请求,实现二级评论的加载。

4.核心代码

1.Github登录相关

private String client_id;
    private String client_secret;
    private String code;
    private String redirect_uri;
    private String state;

    public String getClient_id() {
        return client_id;
    }

    public void setClient_id(String client_id) {
        this.client_id = client_id;
    }

    public String getClient_secret() {
        return client_secret;
    }

    public void setClient_secret(String client_secret) {
        this.client_secret = client_secret;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getRedirect_uri() {
        return redirect_uri;
    }

    public void setRedirect_uri(String redirect_uri) {
        this.redirect_uri = redirect_uri;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }
}

2.编写GithubProvider.class:调用github官方给出的 OAuth Apps api,实现Github登录

@Component
public class GithubProvider {
    public String getAccessToken(AccessTokenDTO accessTokenDto){
        MediaType mediaType
                = MediaType.get("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();
            RequestBody body = RequestBody.create(mediaType,JSON.toJSONString(accessTokenDto));
            Request request = new Request.Builder()
                    .url("https://github.com/login/oauth/access_token")
                    .post(body)
                    .build();
            try (Response response = client.newCall(request).execute()) {
               String string =response.body().string();
               String access_token=string.split("&")[0].split("=")[1];
                return access_token;
            }catch (Exception e)
            {
                e.printStackTrace();
            }
        return null;
    }
    public GithubUserDTO getGithubUser(String accessToken) {

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://api.github.com/user?access_token=" + accessToken)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            GithubUserDTO githubUserDTO = JSON.parseObject(string, GithubUserDTO.class);
            return githubUserDTO;
        } catch (IOException e) {
            return null;
        }
    }
      }

3. Controller中调用GithubProvider获取用户数据并写入数据库

@Controller
public class AuthorizeController {
    @Autowired
    private GithubProvider githubProvider = null;
    @Autowired
    private UserService userService = null;
    @Value("${github.client.id}")
    private String clientID;
    @Value("${github.client.secret}")
    private String clientSC;
    @Value("${github.redirect.url}")
    private String redirectURL;
    @Autowired
    QuesDtoService quesDtoService;
    @RequestMapping("/callback")
    public String callback(@RequestParam(name = "code") String code,
                           @RequestParam(name = "state") String state,
                           HttpServletResponse response,
                           HttpServletRequest request) {
        AccessTokenDTO accessTokenDto = new AccessTokenDTO();
        accessTokenDto.setCode(code);
        accessTokenDto.setState(state);
        accessTokenDto.setClient_id(clientID);
        accessTokenDto.setClient_secret(clientSC);
        accessTokenDto.setRedirect_uri(redirectURL);
        String accesstaken = githubProvider.getAccessToken(accessTokenDto);
        GithubUserDTO githubUserDTO = githubProvider.getGithubUser(accesstaken);
        if (githubUserDTO != null) {
            User user1 = null;
            String token = UUID.randomUUID().toString();
            try {
                user1 = userService.findByGithubId(String.valueOf(githubUserDTO.getId()));
                if (user1 != null) {
                    response.addCookie(new Cookie("token", token));
                    user1.setUser_token(token);
                    userService.upTokenById(token, user1.getUser_id());
                } else {
                    User user = new User();
                    user.setUser_token(token);
                    user.setUser_name(githubUserDTO.getName());
                    user.setAccount_id(String.valueOf(githubUserDTO.getId()));
                    user.setGmt_create(System.currentTimeMillis());
                    user.setGmt_modified(user.getGmt_create());
                    user.setUser_img(githubUserDTO.getAvatarUrl());
                    user.setUser_bio(githubUserDTO.getBio());
                    user.setUser_blog(githubUserDTO.getBlog());
                    user.setUser_github(githubUserDTO.getHtml_url());
                    userService.Insert(user);
                    request.getSession().setAttribute("user", user);
                    response.addCookie(new Cookie("token", token));
                }
            } catch (Exception w) {

            }
            return "redirect:/";
        } else {

            return "redirect:/";
        }
    }

2.Ucloud 对象存储 UFile

1.UcloudProvider.class:

//ucloud上传文件
@Service
public class UcloudProvider {
    private String buckname = "yremp";
    @Value("${ucloud.publickey}")
    private String publickey;
    @Value("${ucloud.privatekey}")
    private String privatekey;
    public String upload(InputStream fileStream, String mimeType, String filename) {
        String fileName;
        String[] FilleName = filename.split("\\.");
        if (FilleName.length > 1) {
            fileName = UUID.randomUUID().toString() + "." + FilleName[FilleName.length - 1];

        } else {
            return null;
        }
        try {
            //    授权
            ObjectAuthorization OBJECT_AUTHORIZER = new UfileObjectLocalAuthorization(publickey, privatekey);
            //    配置
            ObjectConfig config = new ObjectConfig("hk", "ufileos.com");
            PutObjectResultBean response = UfileClient.object(OBJECT_AUTHORIZER, config)
                    .putObject(fileStream, mimeType)
                    .nameAs(fileName)
                    .toBucket(buckname)
                    .setOnProgressListener(new OnProgressListener() {
                        @Override
                        public void onProgress(long bytesWritten, long contentLength) {

                        }
                    })

                    .execute();
            if (response != null && response.getRetCode() == 0) {
                String url = UfileClient.object(OBJECT_AUTHORIZER, config)
                        .getDownloadUrlFromPrivateBucket(fileName, buckname, 24 * 60 * 60 * 365 *10)
                        .createUrl();
                return url;
            } else {
                throw new PeculiarException(PeculiarExceptionCodeAndMessage.FILE_UPLOAD_ERROR);
            }
        } catch (UfileClientException e) {
            throw new PeculiarException(PeculiarExceptionCodeAndMessage.FILE_UPLOAD_ERROR);
        } catch (UfileServerException e) {
            throw new PeculiarException(PeculiarExceptionCodeAndMessage.FILE_UPLOAD_ERROR);
        }
    }
}

2.前端请求后调用UcloudProvider

@Controller
public class FileUploadController {
    private String fileurl;
    @Autowired
    private UcloudProvider ucloudProvider;
    @RequestMapping("/file/upload")
    @ResponseBody
    public FileDTO upload(HttpServletRequest request){
        MultipartHttpServletRequest multipartHttpServletRequest=(MultipartHttpServletRequest) request;
        MultipartFile file = multipartHttpServletRequest.getFile("editormd-image-file");
        try {
          //ucloudProvider 拿到文件url
          String fileurl=  ucloudProvider.upload(file.getInputStream(),file.getContentType(),file.getOriginalFilename());
            FileDTO fileDTO = new FileDTO();
            fileDTO.setSuccess(1);
            fileDTO.setMessage("成功");
            fileDTO.setUrl(fileurl);
            return fileDTO;
        } catch (Exception e) {
            e.printStackTrace();
        }
        FileDTO fileDTO = new FileDTO();
        fileDTO.setSuccess(1);
        fileDTO.setMessage("成功");
        fileDTO.setUrl(fileurl);
        return fileDTO;
    }
}

3.其他

至于集成editormd、数据库分页、和ajax 的简单使用感觉比较简单,教程也很多就不细说。

标签云

Bootstrap cdn Chevereto Editormd Hexo IDEA JavaScript jsDeliver JS樱花特效 Linux markdown Maven MyBatis MyBatis-plus MySQL Pictures Sakura SEO Spring Boot SpringMVC SSR Thymeleaf Web WebSocket Wechat Social WordPress Yoast SEO 代理 分页 图床 小幸运