一个练习项目,好玩的bbs-java

java这个我是用springboot做的

目录结构

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/my_bbs?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2b8&allowPublicKeyRetrieval=true
    username: root
    password: "123456"

server:
  port: 1087

 

主要代码IndexController.java

package com.example.study_bbs_java.controller;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.study_bbs_java.entity.Countinfo;
import com.example.study_bbs_java.entity.Userinfo;
import com.example.study_bbs_java.entity.Postinfo;
import com.example.study_bbs_java.entity.Replyinfo;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.jdbc.core.PreparedStatementCreator;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.SQLException;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;

@RestController
@ResponseBody
public class IndexController {
    @Autowired
    JdbcTemplate jdbcTemplate;

    int pagesize = 20;
    String secretKey = "saacac3423@21212";

    @RequestMapping(value ="/")
    public String index(HttpServletResponse response){
        response.setHeader("Server", "java-springboot");
        return "此站接口使用java实现,<a href='api.html' target='_blank'>接口列表</a>";
    }

    @RequestMapping(value = "/user/register")
    public HashMap register(@RequestParam Map<String,Object> params, HttpServletResponse response){
        response.setHeader("Server", "java-springboot");
        String username = params.get("username") != null ? params.get("username").toString() : "";
        String password = params.get("password") != null ? params.get("password").toString() : "";
        String nickname = params.get("nickname") != null ? params.get("nickname").toString() : "";
        String passwordMd5 = getMD5(password);

        Userinfo userinfo1 = new Userinfo();
        try {
            String sql1 = "select id,username,nickname,addTime,sessionId from user where username='" + username + "'";
            userinfo1 = jdbcTemplate.queryForObject(sql1, new BeanPropertyRowMapper<>(Userinfo.class));

        } catch (Exception e) {
            //
        }

        HashMap res = new HashMap();
        if(userinfo1.getId() > 0){
            res.put("code", 0);
            res.put("msg", "");
            res.put("data", "用户名已经存在");
        }
        else{
            String sql2 = "insert into user(username, password, nickname) value('"+username+"', '"+passwordMd5+"', '"+nickname+"')";
            jdbcTemplate.execute(sql2);

            res.put("code", 0);
            res.put("msg", "");
            res.put("data", userinfo1);
        }

        return res;
    }

    @RequestMapping(value = "/user/login")
    public HashMap login(@RequestParam Map<String,Object> params, HttpServletResponse response){
        response.setHeader("Server", "java-springboot");
        String username = params.get("username") != null ? params.get("username").toString() : "";
        String password = params.get("password") != null ? params.get("password").toString() : "";
        String passwordMd5 = getMD5(password);

        String sql1 = "select id,username,nickname,addTime,sessionId from user where username='"+username+"' and password='"+passwordMd5+"'";
        Userinfo userinfo1 = jdbcTemplate.queryForObject(sql1,new BeanPropertyRowMapper<>(Userinfo.class));

        HashMap res = new HashMap();
        if(userinfo1.getId() > 0) {
            String sessionId = getMD5(secretKey + userinfo1.getId() + userinfo1.getAddTime());
            String sql2 = "update user set sessionId='" + sessionId + "' where id=" + userinfo1.getId();
            jdbcTemplate.execute(sql2);
            userinfo1.setSessionId(sessionId);

            res.put("code", 0);
            res.put("msg", "");
            res.put("data", userinfo1);
        }
        else{
            res.put("code", 0);
            res.put("msg", "");
            res.put("data", "用户名或者密码错误");
        }

        return res;
    }

    @RequestMapping(value = "/user/logout")
    public HashMap logout(@RequestParam Map<String,Object> params, HttpServletResponse response){
        response.setHeader("Server", "java-springboot");
        String sessionId = params.get("sessionId") != null ? params.get("sessionId").toString() : "";
        Userinfo userinfo1 = getloginuserinfo(sessionId);

        String sql1 = "update user set sessionId='' where sessionId='"+sessionId+"'";
        jdbcTemplate.execute(sql1);
        userinfo1.setSessionId("");

        HashMap res = new HashMap();
        res.put("code", 0);
        res.put("msg", "");
        res.put("data", userinfo1);

        return res;
    }

    @RequestMapping(value = "/user/getuserinfo")
    public HashMap getuserinfo(@RequestParam Map<String,Object> params, HttpServletResponse response){
        response.setHeader("Server", "java-springboot");
        String sessionId = params.get("sessionId") != null ? params.get("sessionId").toString() : "";

        String sql1 = "select id,username,nickname,addTime,sessionId from user where sessionId='"+sessionId+"'";
        Userinfo userinfo1 = jdbcTemplate.queryForObject(sql1,new BeanPropertyRowMapper<>(Userinfo.class));

        HashMap res = new HashMap();
        res.put("code", 0);
        res.put("msg", "");
        res.put("data", userinfo1);

        return res;
    }

    @RequestMapping(value = "/post/list")
    public HashMap postlist(@RequestParam Map<String,Object> params, HttpServletResponse response){
        response.setHeader("Server", "java-springboot");
        String keyword = params.get("keyword") != null ? params.get("keyword").toString() : "";
        Integer page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1;
        Integer start = (page - 1) * pagesize;

        String addsql = " isDel=0 ";
        if(!keyword.equals("")){
            addsql = addsql + " and title='%"+keyword+"%'";
        }
        String sql1 = "select count(1) as count from content where "+addsql;
        Countinfo postcount = jdbcTemplate.queryForObject(sql1,new BeanPropertyRowMapper<>(Countinfo.class));

        String sql2 = "select id,title,userId,userNickename,replyNum,updateTime from content where "+addsql+" order by updateTime desc limit "+start+","+pagesize;
        List<Map<String, Object>> postlist = jdbcTemplate.queryForList(sql2);
        if(postlist.size() > 0){
            for(int i = 0; i < postlist.size(); i++){
                Map<String, Object> item = postlist.get(i);
                String updateTime = DateTimeFormatter((Date)item.get("updateTime"));
                item.put("updateTime", updateTime);
                postlist.set(i, item);
            }
        }

        long totalpage = Math.round(Math.ceil(postcount.getCount() / (double)pagesize));
        HashMap res1 = new HashMap();
        res1.put("totalpage", totalpage);
        res1.put("data", postlist);

        HashMap res = new HashMap();
        res.put("code", 0);
        res.put("msg", "");
        res.put("data", res1);

        return res;
    }

    @RequestMapping(value = "/post/detail")
    public HashMap postdetail(@RequestParam Map<String,Object> params, HttpServletResponse response){
        response.setHeader("Server", "java-springboot");
        Integer id = params.get("id") != null ? Integer.parseInt(params.get("id").toString()) : 0;

        String sql1 = "select id,title,content,userId,userNickename,replyNum,updateTime from content where isDel=0 and id="+id;
        Postinfo postinfo1 = jdbcTemplate.queryForObject(sql1,new BeanPropertyRowMapper<>(Postinfo.class));

        HashMap res = new HashMap();
        res.put("code", 0);
        res.put("msg", "");
        res.put("data", postinfo1);

        return res;
    }

    @RequestMapping(value = "/post/add")
    public HashMap postadd(@RequestParam Map<String,Object> params, HttpServletResponse response){
        response.setHeader("Server", "java-springboot");
        final String title = params.get("title") != null ? params.get("title").toString() : "";
        final String content = params.get("content") != null ? params.get("content").toString() : "";
        String sessionId = params.get("sessionId") != null ? params.get("sessionId").toString() : "";

        final Userinfo userinfo1 = getloginuserinfo(sessionId);
        if(userinfo1.getId() <= 0){
            HashMap res = new HashMap();
            res.put("code", 0);
            res.put("msg", "");
            res.put("data", "请先登录");
            return res;
        }

        final String sql1 = "insert into content(title, content, userId, userNickename) value(?, ?, ?, ?)";
        KeyHolder keyHolder = new GeneratedKeyHolder();

        int count = jdbcTemplate.update(new PreparedStatementCreator() {
        @Override
        public PreparedStatement createPreparedStatement(Connection conn)
                throws SQLException {
                    PreparedStatement pstmt=conn.prepareStatement(sql1, Statement.RETURN_GENERATED_KEYS);
                    pstmt.setString(1, title);
                    pstmt.setString(2, content);
                    pstmt.setInt(3, userinfo1.getId());
                    pstmt.setString(4, userinfo1.getNickname());
                    return pstmt;
                }
        },keyHolder);

        HashMap res = new HashMap();
        res.put("code", 0);
        res.put("msg", "");
        res.put("data", keyHolder.getKey().longValue());

        return res;
    }

    @RequestMapping(value = "/post/edit")
    public HashMap postedit(@RequestParam Map<String,Object> params, HttpServletResponse response){
        response.setHeader("Server", "java-springboot");
        Integer id = params.get("id") != null ? Integer.parseInt(params.get("id").toString()) : 0;
        String title = params.get("title") != null ? params.get("title").toString() : "";
        String content = params.get("content") != null ? params.get("content").toString() : "";
        String sessionId = params.get("sessionId") != null ? params.get("sessionId").toString() : "";

        Userinfo userinfo1 = getloginuserinfo(sessionId);
        if(userinfo1.getId() <= 0){
            HashMap res = new HashMap();
            res.put("code", 0);
            res.put("msg", "");
            res.put("data", "请先登录");
            return res;
        }

        String sql1 = "update content set title='"+title+"',content='"+content+"',userId="+userinfo1.getId()+",userNickename='"+userinfo1.getNickname()+"' where id="+id+" and userId="+userinfo1.getId();
        jdbcTemplate.execute(sql1);

        HashMap res = new HashMap();
        res.put("code", 0);
        res.put("msg", "");
        res.put("data", "");

        return res;
    }

    @RequestMapping(value = "/post/delete")
    public HashMap postdelete(@RequestParam Map<String,Object> params, HttpServletResponse response){
        response.setHeader("Server", "java-springboot");
        Integer id = params.get("id") != null ? Integer.parseInt(params.get("id").toString()) : 0;
        String sessionId = params.get("sessionId") != null ? params.get("sessionId").toString() : "";

        Userinfo userinfo1 = getloginuserinfo(sessionId);
        if(userinfo1.getId() <= 0){
            HashMap res = new HashMap();
            res.put("code", 0);
            res.put("msg", "");
            res.put("data", "请先登录");
            return res;
        }

        String sql1 = "update content set isDel=1 where id="+id+" and userId="+userinfo1.getId();
        jdbcTemplate.execute(sql1);

        HashMap res = new HashMap();
        res.put("code", 0);
        res.put("msg", "");
        res.put("data", "");

        return res;
    }

    @RequestMapping(value = "/reply/list")
    public HashMap replylist(@RequestParam Map<String,Object> params, HttpServletResponse response){
        response.setHeader("Server", "java-springboot");
        Integer contentId = params.get("contentId") != null ? Integer.parseInt(params.get("contentId").toString()) : 0;
        Integer page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1;
        Integer start = (page - 1) * pagesize;

        String addsql = " isDel=0 and contentId="+contentId+" ";
        String sql1 = "select count(1) as count from reply where "+addsql;
        Countinfo replycount = jdbcTemplate.queryForObject(sql1,new BeanPropertyRowMapper<>(Countinfo.class));

        String sql2 = "select id,content,replyUserId,replyUserNickename,addTime from reply where "+addsql+" order by id asc limit "+start+","+pagesize;
        List<Map<String, Object>> replylist = jdbcTemplate.queryForList(sql2);
        if(replylist.size() > 0){
            for(int i = 0; i < replylist.size(); i++){
                Map<String, Object> item = replylist.get(i);
                String addTime = DateTimeFormatter((Date)item.get("addTime"));
                item.put("addTime", addTime);
                replylist.set(i, item);
            }
        }

        long totalpage = Math.round(Math.ceil(replycount.getCount() / (double)pagesize));
        HashMap res1 = new HashMap();
        res1.put("totalpage", totalpage);
        res1.put("data", replylist);

        HashMap res = new HashMap();
        res.put("code", 0);
        res.put("msg", "");
        res.put("data", res1);

        return res;
    }

    @RequestMapping(value = "/reply/detail")
    public HashMap replydetail(@RequestParam Map<String,Object> params, HttpServletResponse response){
        response.setHeader("Server", "java-springboot");
        Integer id = params.get("id") != null ? Integer.parseInt(params.get("id").toString()) : 0;

        String sql1 = "select id,content,replyUserId,replyUserNickename,addTime from reply where isDel=0 and id="+id;
        Replyinfo replyinfo1 = jdbcTemplate.queryForObject(sql1,new BeanPropertyRowMapper<>(Replyinfo.class));

        HashMap res = new HashMap();
        res.put("code", 0);
        res.put("msg", "");
        res.put("data", replyinfo1);

        return res;
    }

    @RequestMapping(value = "/reply/add")
    public HashMap replyadd(@RequestParam Map<String,Object> params, HttpServletResponse response){
        response.setHeader("Server", "java-springboot");
        final Integer contentId = params.get("contentId") != null ? Integer.parseInt(params.get("contentId").toString()) : 0;
        final String content = params.get("content") != null ? params.get("content").toString() : "";
        String sessionId = params.get("sessionId") != null ? params.get("sessionId").toString() : "";

        final Userinfo userinfo1 = getloginuserinfo(sessionId);
        if(userinfo1.getId() <= 0){
            HashMap res = new HashMap();
            res.put("code", 0);
            res.put("msg", "");
            res.put("data", "请先登录");
            return res;
        }

        String sql2 = "update content set replyNum=replyNum+1 where id="+contentId;
        jdbcTemplate.execute(sql2);

        final String sql1 = "insert into reply(contentId, content, replyUserId, replyUserNickename) value(?, ?, ?, ?)";
        KeyHolder keyHolder = new GeneratedKeyHolder();

        int count = jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection conn)
                    throws SQLException {
                PreparedStatement pstmt=conn.prepareStatement(sql1, Statement.RETURN_GENERATED_KEYS);
                pstmt.setInt(1, contentId);
                pstmt.setString(2, content);
                pstmt.setInt(3, userinfo1.getId());
                pstmt.setString(4, userinfo1.getNickname());
                return pstmt;
            }
        },keyHolder);

        HashMap res = new HashMap();
        res.put("code", 0);
        res.put("msg", "");
        res.put("data", keyHolder.getKey().longValue());

        return res;
    }

    @RequestMapping(value = "/reply/edit")
    public HashMap replyedit(@RequestParam Map<String,Object> params, HttpServletResponse response){
        response.setHeader("Server", "java-springboot");
        Integer id = params.get("id") != null ? Integer.parseInt(params.get("id").toString()) : 0;
        String content = params.get("content") != null ? params.get("content").toString() : "";
        String sessionId = params.get("sessionId") != null ? params.get("sessionId").toString() : "";

        Userinfo userinfo1 = getloginuserinfo(sessionId);
        if(userinfo1.getId() <= 0){
            HashMap res = new HashMap();
            res.put("code", 0);
            res.put("msg", "");
            res.put("data", "请先登录");
            return res;
        }

        String sql1 = "update reply set content='"+content+"',replyUserId="+userinfo1.getId()+",replyUserNickename='"+userinfo1.getNickname()+"' where id="+id+" and replyUserId="+userinfo1.getId();
        jdbcTemplate.execute(sql1);

        HashMap res = new HashMap();
        res.put("code", 0);
        res.put("msg", "");
        res.put("data", "");

        return res;
    }

    @RequestMapping(value = "/reply/delete")
    public HashMap replydelete(@RequestParam Map<String,Object> params, HttpServletResponse response){
        response.setHeader("Server", "java-springboot");
        Integer id = params.get("id") != null ? Integer.parseInt(params.get("id").toString()) : 0;
        String sessionId = params.get("sessionId") != null ? params.get("sessionId").toString() : "";

        Userinfo userinfo1 = getloginuserinfo(sessionId);
        if(userinfo1.getId() <= 0){
            HashMap res = new HashMap();
            res.put("code", 0);
            res.put("msg", "");
            res.put("data", "请先登录");
            return res;
        }

        Replyinfo replyinfo1 = new Replyinfo();
        try {
            String sql0 = "select id,content,replyUserId,replyUserNickename,addTime,contentId from reply where isDel=0 and id=" + id;
            replyinfo1 = jdbcTemplate.queryForObject(sql0, new BeanPropertyRowMapper<>(Replyinfo.class));
        }
        catch (Exception e){
            //
        }

        if(replyinfo1.getId() > 0) {
            String sql2 = "update content set replyNum=replyNum-1 where id=" + replyinfo1.getContentId();
            jdbcTemplate.execute(sql2);

            String sql1 = "update reply set isDel=1 where id=" + id + " and replyUserId=" + userinfo1.getId();
            jdbcTemplate.execute(sql1);
        }

        HashMap res = new HashMap();
        res.put("code", 0);
        res.put("msg", "");
        res.put("data", "");

        return res;
    }

    private String DateTimeFormatter(Date currentDate){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = sdf.format(currentDate);
        return formattedDate;
    }

    private Userinfo getloginuserinfo(String sessionId){
        Userinfo userinfo1 = new Userinfo();
        try{
            String sql1 = "select id,username,nickname,addTime,sessionId from user where sessionId='"+sessionId+"'";
            userinfo1 = jdbcTemplate.queryForObject(sql1,new BeanPropertyRowMapper<>(Userinfo.class));
        }
        catch(Exception e){
            //
        }

        return userinfo1;
    }

    private String getMD5(String plainText) {
        String md5 = new String();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();

            int i;

            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }

            md5 = buf.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return md5;
    }
}

 

启动输出:

 

posted @ 2024-06-21 15:01  河北大学-徐小波  阅读(8)  评论(0编辑  收藏  举报