Java项目:在线新闻平台系统(java+jsp+jdbc+mysql)

2022/2/13 19:46:34

本文主要是介绍Java项目:在线新闻平台系统(java+jsp+jdbc+mysql),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

源码获取:博客首页 "资源" 里下载!

一、项目简述

功能: 用户的登录注册,新闻的分类查询,评论留言,投稿,新闻的后台管理,发布,审核,投稿管理以及汇总统计等等。

二、项目运行

环境配置: Jdk1.8 + Tomcat8.5 + mysql + Eclispe (IntelliJ IDEA,Eclispe,MyEclispe,Sts 都支持)

项目技术: Jsp + Jdbc + Servlert + html+ css + JavaScript + JQuery + Ajax + Fileupload

用户登录控制器:

/**
 * 用户登录控制器
 */
@WebServlet("/admin/*")
public class LoginServlet  extends BaseServlet{

    private UmsUserServiceImpl umsUserService = new UmsUserServiceImpl();
    private UmsUserDaoImpl userDao = new UmsUserDaoImpl();
    public void doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int  userId = 0;
        String userName = request.getParameter("userName");
        String passWord = request.getParameter("passWord");
        String roleStr = request.getParameter("role");
        String code = request.getParameter("code");
        Integer role = Integer.valueOf(roleStr);
        if (role == Role.Admin.getRoleCode()){
            Admin admin = new Admin();
            admin.setUserName(userName);
            admin.setPassWord(passWord);
            userId = umsUserService.login(admin);
        }else if (role == Role.User.getRoleCode()){
            User user = new User();
            user.setUserName(userName);
            user.setPassWord(passWord);
            userId = umsUserService.userLogin(user);
        }
        String codeSession = (String) request.getSession().getAttribute("code");
        System.out.println("验证码"+codeSession);
        if (!codeSession.equalsIgnoreCase(code)){
            ServletResp.resp(response, CommonResult.failed("验证码有误"));
            return;
        }

        if (userId != 0){
             request.getSession().setAttribute("userName", userName);
             request.getSession().setAttribute("role", role);
            request.getSession().setAttribute("userId", userId);
             ServletResp.resp(response, CommonResult.success());
        }else {
            ServletResp.resp(response, CommonResult.failed("登录失败,账号密码有误!"));
        }

    }


    public void toLogin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.getRequestDispatcher("front/page/login/login.html").forward(request, response);
    }

    public void toIndex(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Integer role = (Integer) request.getSession().getAttribute("role");
        if (role == null){
            response.sendRedirect("admin?method=toLogin");
            return;
        }
        if (Role.Admin.getRoleCode()!=role || role == null){
            response.sendRedirect("admin?method=toLogin");
            return;
        }
        request.getRequestDispatcher("front/index.html").forward(request, response);
    }

    public void doLogOut(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.getSession().removeAttribute("userName");
        request.getSession().removeAttribute("userId");
        request.getSession().removeAttribute("role");
        ServletResp.resp(response, CommonResult.success("注销成功"));
    }


    public void toRegist(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.getRequestDispatcher("front/page/login/regist.html").forward(request, response);
    }

    /**
     * 普通用户注册
     * @param request
     * @param response
     */
    public void doRegist(HttpServletRequest request, HttpServletResponse response)  {
        String reqBody = JsonUtils.getJson(request);
        User user = JsonUtils.fromJson(reqBody, User.class);
        int result = userDao.regist(user);
        if (result == 0){
            ServletResp.resp(response, CommonResult.failed("注册失败"));
        }else{
            ServletResp.resp(response, CommonResult.success("注册成功"));
        }
    }

    /**
     * 检查用户名是否重复
     * @param request
     * @param response
     */
    public void checkUsername(HttpServletRequest request, HttpServletResponse response){
            String userName = request.getParameter("userName");
        int result = userDao.checkUsername(userName);
        if (result == 1){
            ServletResp.resp(response, CommonResult.success("用户名可用"));
        }else {
            ServletResp.resp(response, CommonResult.failed("用户名已存在"));
        }
    }

    public void getCode(HttpServletRequest request, HttpServletResponse response){
        //创建对象
        VerifyCode vc = new VerifyCode();
        //获取图片对象
        BufferedImage bi = vc.getImage();
        //获得图片的文本内容
        String text = vc.getText();
        // 将系统生成的文本内容保存到session中
        request.getSession().setAttribute("code", text);
        //向浏览器输出图片
        try {
            VerifyCode.output(bi, response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

评论模块:

/**
 * 评论模块
 */
@WebServlet("/comment/*")
public class CommentServlet extends BaseServlet {

    /**
     * (客户端)获取文章评论
     * @param request
     * @param response
     */
    public void getComments(HttpServletRequest request, HttpServletResponse response){
        String idStr = request.getParameter("articleId");
        Integer articleId = Integer.valueOf(idStr);
        List<Comment> commentList = new CmsCommentDaoImpl().getComments(articleId);
        if (commentList!=null){
            ServletResp.resp(response, CommonPage.success(commentList));
        }else {
            ServletResp.resp(response, CommonResult.failed());
        }
    }


    /**
     * (客户端)添加文章评论
     * @param request
     * @param response
     */
    public void addComment(HttpServletRequest request, HttpServletResponse response){
        String reqBody = JsonUtils.getJson(request);
        Comment comment = JsonUtils.fromJson(reqBody, Comment.class);
        String userName = (String) request.getSession().getAttribute("userName");
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        Integer role = (Integer) request.getSession().getAttribute("role");
        if (userId == null || Role.Admin.getRoleCode()==role){
            ServletResp.resp(response, CommonResult.unauthorized());
        }
        comment.setUsername(userName);
        comment.setUserId(userId);
        int result = new CmsCommentDaoImpl().doComment(comment);
        if (result == 1){
            ServletResp.resp(response, CommonResult.success("评论成功,审核通过后显示"));
        }else {
            ServletResp.resp(response, CommonResult.failed("评论失败"));
        }
    }

    /**
     * (管理端)获取等待审核的评论
     * @param request
     * @param response
     */
    public void getCommentWaitCheck(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Integer role = (Integer) request.getSession().getAttribute("role");
        if (Role.Admin.getRoleCode()!=role){
            response.sendRedirect("admin?method=toLogin");
        }
        String pageNumStr = request.getParameter("page");
        String pageSizeStr = request.getParameter("limit");
        if (pageNumStr == null || pageSizeStr == null){
            ServletResp.resp(response, CommonResult.validateFailed());
        }
        int pageSize = Integer.valueOf(pageSizeStr);
        int pageNum = Integer.valueOf(pageNumStr);
        pageNum = (pageNum-1) * pageSize;
        List<Map<String,Object>> allComments = new CmsCommentDaoImpl().getCommentWaitCheck(pageNum,pageSize);
        if (allComments!=null){
            ServletResp.resp(response, CommonPage.success(allComments));
        }else{
            ServletResp.resp(response, CommonResult.failed());
        }

    }

    /**
     * 更新评论
     * @param request
     * @param response
     */
    public void updateComment(HttpServletRequest request, HttpServletResponse response){
        String reqBody = JsonUtils.getJson(request);
        Comment comment = JsonUtils.fromJson(reqBody, Comment.class);
        int result = new CmsCommentDaoImpl().updateComment(comment);
        if (result == 1){
            ServletResp.resp(response, CommonResult.success("修改评论状态成功"));
        }else {
            ServletResp.resp(response, CommonResult.failed());
        }
    }

}

文章控制器:

/**
 * 文章控制器
 */
@WebServlet("/article/*")
public class ArticleServlet extends BaseServlet {

    private CmsArticleService cmsArticleService = new CmsArticleServiceImpl();

    /**
     * (管理端)分页获取文章
     * @param request
     * @param response
     */
    public void getAllArticle(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Integer role = (Integer) request.getSession().getAttribute("role");
        if (Role.Admin.getRoleCode()!=role){
            response.sendRedirect("admin?method=toLogin");
        }
        String pageNumStr = request.getParameter("page");
        String pageSizeStr = request.getParameter("limit");
        if (pageNumStr == null || pageSizeStr == null){
            ServletResp.resp(response, CommonResult.validateFailed());
        }
        int pageSize = Integer.valueOf(pageSizeStr) ;
        int pageNum = Integer.valueOf(pageNumStr);
        pageNum = (pageNum-1) * pageSize;

        List<Article> allArticleInfo = cmsArticleService.getAllArticleInfo(pageNum, pageSize);
        if (allArticleInfo != null){
            String success = CommonPage.success(allArticleInfo);
            ServletResp.resp(response, success);
        }else {
            ServletResp.resp(response, CommonResult.failed());
        }
    }

    /**
     * (管理端|客户端)查看文章详情
     * @param request
     * @param response
     */
    public void getArticleById(HttpServletRequest request, HttpServletResponse response) {
        String articleIdStr = request.getParameter("articleId");
        Integer articleId = Integer.valueOf(articleIdStr);
        Article article = cmsArticleService.getArticleById(articleId);
        System.out.println("request.getSession().getAttribute(\"role\") = " + request.getSession().getAttribute("role"));
        if (article != null){
            if(article.getIsShow() == 1 || request.getSession().getAttribute("role").equals(Role.Admin.getRoleCode())){
                ServletResp.resp(response, CommonResult.success(article));
            }else {
                ServletResp.resp(response, CommonResult.failed("文章不见了,去看看其他文章吧"));
            }

        }else {
            ServletResp.resp(response, CommonResult.failed("文章不存在"));
        }
    }

    /**
     * (管理端)获取投稿文章
     * @param request
     * @param response
     */
    public void getArticleByUser(HttpServletRequest request, HttpServletResponse response){
        String pageNumStr = request.getParameter("page");
        String pageSizeStr = request.getParameter("limit");
        if (pageNumStr == null || pageSizeStr == null){
            ServletResp.resp(response, CommonResult.validateFailed());
        }
        int pageSize = Integer.valueOf(pageSizeStr);
        int pageNum = Integer.valueOf(pageNumStr);
        pageNum = (pageNum-1) * pageSize;

        List<Article> allArticleInfo = cmsArticleService.getArticleByUser(pageNum, pageSize);
        if (allArticleInfo != null){
            String success = CommonPage.success(allArticleInfo);
            ServletResp.resp(response, success);
        }else {
            ServletResp.resp(response, CommonResult.failed());
        }
    }

    /**
     * (客户端|管理端)添加(投稿)文章
     * @param request
     * @param response
     */
    public void add(HttpServletRequest request, HttpServletResponse response){
        String reqBody = JsonUtils.getJson(request);
        Article article = JsonUtils.fromJson(reqBody, Article.class);
        String userName = (String)request.getSession().getAttribute("userName");
        Integer role = (Integer) request.getSession().getAttribute("role");
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        if (userId == null){
            ServletResp.resp(response, CommonResult.unauthorized());
            //return;
        }
        // 根据角色
        int count = 0;
        article.setEditorId(userId);
        article.setRole(role);
        if (role == Role.Admin.getRoleCode()){
             article.setIsCheck(1);
             count = cmsArticleService.add(article);
        }else{
            // 用户需要审核才可以发布
            article.setIsCheck(0);
            count = cmsArticleService.add(article);
        }

        if (count != 0){
            ServletResp.resp(response, CommonResult.success());
        }else {
            ServletResp.resp(response, CommonResult.failed());
        }
    }

    /**
     * (管理端)更新文章
     * @param request
     * @param response
     */
    public void update(HttpServletRequest request, HttpServletResponse response){
        String reqBody = JsonUtils.getJson(request);
        Article article = JsonUtils.fromJson(reqBody, Article.class);
        int count = cmsArticleService.update(article);
        if (count != 0){
            ServletResp.resp(response, CommonResult.success());
        }else {
            ServletResp.resp(response, CommonResult.failed());
        }
    }

    /**
     * (客户端)查询该分类下可以显示的文章列表
     * @param request
     * @param response
     */
    public void getArticleListByCatelogyId(HttpServletRequest request, HttpServletResponse response){
        String categoryIdStr = request.getParameter("categoryId");
        Integer categoryId = Integer.valueOf(categoryIdStr);
        Map<String,Object> map = cmsArticleService.getArticleListByCatelogyId(categoryId);
        if (map != null){
            ServletResp.resp(response, CommonResult.success(map));
        }else {
            ServletResp.resp(response, CommonResult.failed());
        }
    }

    /**
     * (管理端)删除文章
     * @param request
     * @param response
     */
    public void delete(HttpServletRequest request, HttpServletResponse response){
        String newsIdStr = request.getParameter("newsId");
        Integer newsId = Integer.valueOf(newsIdStr);
        int count = cmsArticleService.delete(newsId);
        if (count != 0){
            ServletResp.resp(response, CommonResult.success("删除成功"));
        }else {
            ServletResp.resp(response, CommonResult.failed());
        }
    }

    /**
     * (客户端)跳转客户端投稿
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void toPostNews(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      response.sendRedirect("postNewsDetail.html");
        //request.getRequestDispatcher("front/page/news/postNewsDetail.html").forward(request, response);
    }

    /**
     * (管理端)更新状态
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void changeCheck(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String reqBody = JsonUtils.getJson(request);
        Article article = JsonUtils.fromJson(reqBody, Article.class);
        int count = cmsArticleService.changeCheck(article);
        if (count != 0){
            ServletResp.resp(response, CommonResult.success());
        }else {
            ServletResp.resp(response, CommonResult.failed());
        }
    }

    /**
     * (管理端)获取统计数据
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void getTotalData(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String reqBody = JsonUtils.getJson(request);
        Article article = JsonUtils.fromJson(reqBody, Article.class);
        Map<String, Object> totalData = new CmsArticleDaoImpl().getTotalData();
        if (totalData != null){
            ServletResp.resp(response, CommonResult.success(totalData));
        }else {
            ServletResp.resp(response, CommonResult.failed());
        }
    }

    /**
     * 上传文件
     * @param request
     * @param response
     * @throws IOException
     */
    public void uploadFile(HttpServletRequest request,HttpServletResponse response) throws IOException {
        SmartUpload su=new SmartUpload();
        try{

            su.initialize(this.getServletConfig(), request,response);
            su.upload();
            File file = su.getFiles().getFile(0);
            String filePath  =
                    request.getSession().getServletContext().getRealPath("/")+ "upload\\";
            java.io.File path = new java.io.File(filePath);
            if (!path.exists()){
                System.out.println("文件夹不存在,创建文件夹");
                path.mkdir();
            }
            String filename = file.getFileName();
            String str = filename.substring(filename.lastIndexOf("."), filename.length());
            System.out.println(filename);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String finalname  = sdf.format(new Date()) + str;
            System.out.println("filePath + finalname = " + filePath + finalname);
            file.saveAs(filePath + finalname , File.SAVEAS_PHYSICAL);
            Map<String,Object> map = new HashMap<>();
            map.put("title",filename);
            map.put("src", "http://localhost:8008/news/upload/"+finalname);
            int result = new CmsArticleDaoImpl().uploadFile(map);
            if (result == 1) {
                ServletResp.resp(response, CommonResult.result(0, "文件上传成功", map));
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
            ServletResp.resp(response, CommonResult.failed("文件上传失败"));
        }
    }

    /**
     * (客户端)搜索功能
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void getSearchResult(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String title = request.getParameter("title");
        List<Map<String, Object>> searchResult = new CmsArticleDaoImpl().getSearchResult(title);
        if (searchResult != null){
            ServletResp.resp(response, CommonResult.success(searchResult));
        }else {
            ServletResp.resp(response, CommonResult.failed());
        }
    }




}

源码获取:博客首页 "资源" 里下载!



这篇关于Java项目:在线新闻平台系统(java+jsp+jdbc+mysql)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程