MVC2 项目实践

 

组员:黄杰辉 201731062223

谢仁峻 201731062209  

一、数据库访问层

创建一个BaseDao,用于继承,方便之后的操作

package Dao.Impl;

import Utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public abstract class BaseDao {

    private QueryRunner queryRunner = new QueryRunner();

    public int update(String sql, Object... args) {
        Connection connection = JdbcUtils.getConnection();
        try {
            return queryRunner.update(connection, sql, args);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(connection);
        }
        return -1;
    }


    public <T> T queryForOne(Class<T> type, String sql, Object... args) {
        Connection con = JdbcUtils.getConnection();
        try {
            return queryRunner.query(con, sql, new BeanHandler<T>(type), args);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(con);
        }
        return null;
    }


    public <T> List<T> queryForList(Class<T> type, String sql, Object... args) {
        Connection con = JdbcUtils.getConnection();
        try {
            return queryRunner.query(con, sql, new BeanListHandler<T>(type), args);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(con);
        }
        return null;
    }


    public Object queryForSingleValue(String sql, Object... args){

        Connection conn = JdbcUtils.getConnection();

        try {
            return queryRunner.query(conn, sql, new ScalarHandler(), args);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(conn);
        }
        return null;

    }
}

创建NewsDao接口,定义增删改查的方法

package Dao;
import Entity.News;
import java.util.List;

public interface NewsDao {
    public int addNews(News news);

    public int deleteNews( Integer id);

    public int updateNews(News news);

    public  News queryNewsById(Integer id);

    public List<News> queryNews();
}

创建NewsDaoImpl实现NewsDao接口,具体实现新闻数据的增删改查

package Dao.Impl;

import Dao.NewsDao;
import Entity.News;
import java.util.List;

public class NewsDaoImpl extends BaseDao implements NewsDao  {
    @Override
    public int addNews(News news) {
        String sql = "insert into news(`title`,`content`,`author`,`date`) values(?,?,?,?)";
        return update(sql,news.getTitle(),news.getContent(),news.getAuthor(),news.getDate());
    }

    @Override
    public int deleteNews(Integer id) {
        String sql = "delete from news where id = ?";
        return update(sql,id);
    }

    @Override
    public int updateNews(News news) {
        String sql = "update news set `title` = ?, `content`= ?,`author`= ?,`date`= ? where id = ?";
        System.out.println(news);
        return update(sql,news.getTitle(),news.getContent(),news.getAuthor(),news.getDate(),news.getId());
    }

    @Override
    public News queryNewsById(Integer id) {
       String sql = "select * from news where id = ?";
       return queryForOne(News.class,sql,id);
    }

    @Override
    public List<News> queryNews() {
        String sql = "select * from news";
        return queryForList(News.class,sql);
    }
}

 

二、业务逻辑层

创建NewsService

package Service;

import Entity.News;
import java.util.List;

public interface NewsService {

    public void addNews(News news);

    public void deleteNewsById(Integer id);

    public void updateNews(News news);

    public News queryNewsById(Integer id);

    public List<News> queryNews();
}

创建NewsService的实现类

package Service.Impl;

import Dao.Impl.NewsDaoImpl;
import Dao.NewsDao;
import Entity.News;
import Service.NewsService;

import java.util.List;

public class NewsServiceImpl implements NewsService {
    private NewsDao newsDao = new NewsDaoImpl();

    @Override
    public void addNews(News news) {
        newsDao.addNews(news);
    }

    @Override
    public void deleteNewsById(Integer id) {
        newsDao.deleteNews(id);
    }

    @Override
    public void updateNews(News news) {
        newsDao.updateNews(news);
    }

    @Override
    public News queryNewsById(Integer id) {
        return newsDao.queryNewsById(id);
    }

    @Override
    public List<News> queryNews() {
        return newsDao.queryNews();
    }
}

三、控制层

创建BaseServlet,用于继承

package Controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;


public abstract class BaseServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String action = req.getParameter("action");
        try {
            Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

创建WebUtil工具类,将参数转化为实体对象

package Utils;

import org.apache.commons.beanutils.BeanUtils;

import java.util.Map;

public class WebUtils {

    public static <T> T copyParamToBean( Map value , T bean ){
        try {
            System.out.println("注入之前:" + bean);
            BeanUtils.populate(bean, value);
            System.out.println("注入之后:" + bean);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
    }
    public static int parseInt(String strInt,int defaultValue) {
        try {
            return Integer.parseInt(strInt);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return defaultValue;
    }
}

创建NewsServlet类

package Controller;

import Entity.News;
import Service.Impl.NewsServiceImpl;
import Service.NewsService;
import Utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/Controller.NewsServlet")
public class NewsServlet extends BaseServlet {
    private Service.NewsService NewsService = new NewsServiceImpl();


    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        News News = WebUtils.copyParamToBean(req.getParameterMap(),new News());
        NewsService.addNews(News);
        resp.sendRedirect(req.getContextPath() + "/Controller.NewsServlet?action=list");

    }



    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        NewsService.deleteNewsById(id);
        resp.sendRedirect(req.getContextPath() + "/Controller.NewsServlet?action=list");
    }



    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        News News = WebUtils.copyParamToBean(req.getParameterMap(),new News());
        NewsService.updateNews(News);
        resp.sendRedirect(req.getContextPath() + "/Controller.NewsServlet?action=list");
    }


    protected void getNews(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        News News = NewsService.queryNewsById(id);
        req.setAttribute("News", News) ;
        req.getRequestDispatcher("/pages/manager/news_edit.jsp").forward(req,resp);
    }



    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<News> News = NewsService.queryNews();
        req.setAttribute("News", News);
        req.getRequestDispatcher("/pages/manager/news_manager.jsp").forward(req,resp);
        System.out.println(News);
    }

}

四、视图层

创建news_manager.jsp,用于显示新闻列表

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>产品管理</title>
    <link rel="stylesheet" type="text/css" href="css/Iframe.css" />
    <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" media="screen" />
</head>
<body>
<span class="cp_title">新闻管理</span>
    <div class="add_cp">
        <a href="pages/manager/news_edit.jsp">+添加产品</a>
    </div>
    <div class="table_con">
        <table>
            <tr >
            <tr class="tb_title">
                <td width="10%">ID</td>
                <td width="12%">标题</td>
                <td width="30%">内容</td>
                <td width="12%">作者</td>
                <td width="10%">时间</td>
                <td width="26%">操作</td>
            </tr>
            </tr>        

            <c:forEach items="${requestScope.News}" var="news">
                <tr>
                    <td width="10%">${news.id}</td>
                    <td width="12%">${news.title}</td>
                    <td width="30%">${news.content}</td>
                    <td width="12%">${news.author}</td>
                    <td width="10%">${news.date}</td>
                    <td><a class="bj_btn"  href="Controller.NewsServlet?action=getNews&id=${news.id}">修改</a></td>
                    <td><a class="del_btn" class="deleteClass" href="Controller.NewsServlet?action=delete&id=${news.id}">删除</a></td>
                </tr>
            </c:forEach>

        </table>
    </div>


</body>
</html>

创建news_edit,作为添加,修改信息的界面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>编辑图书</title>

</head>
<body>
        
        <div id="main">
            <form action="/ServletDemo_war_exploded/Controller.NewsServlet" method="get">
                <input type="hidden" name="action" value="${ empty param.id ? "add" : "update" }" />
                <input type="hidden" name="id" value="${ requestScope.News.id }" />
                <table>
                    <tr>
                        <td>标题</td>
                        <td>内容</td>
                        <td>作者</td>
                        <td>日期</td>
                        <td colspan="2">操作</td>
                    </tr>        
                    <tr>
                        <td><input name="title" type="text" value="${requestScope.News.title}"/></td>
                        <td><input name="content" type="text" value="${requestScope.News.content}"/></td>
                        <td><input name="author" type="text" value="${requestScope.News.author}"/></td>
                        <td><input name="date" type="text" value="${requestScope.News.date}"/></td>
                        <td><input type="submit" value="提交"/></td>
                    </tr>    
                </table>
            </form>
        </div>

</body>
</html>

 代码地址:https://gitee.com/ioklkiol/javaee_second_job/tree/master/MVC2