使用基本MVC2模式创建新闻网站

使用基本MVC2模式创建新闻网站

MVC的全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,是一种软件设计典范。它是用一种业务逻辑、数据与界面显示分离的方法来组织代码,将众多的业务逻辑聚集到一个部件里面,在需要改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑,达到减少编码的时间。

MVC开始是存在于桌面程序中的,M是指业务模型,V是指用户界面,C则是控制器。

使用的MVC的目的:在于将M和V的实现代码分离,从而使同一个程序可以使用不同的表现形式。比如Windows系统资源管理器文件夹内容的显示方式,下面两张图中左边为详细信息显示方式,右边为中等图标显示方式,文件的内容并没有改变,改变的是显示的方式。不管用户使用何种类型的显示方式,文件的内容并没有改变,达到M和V分离的目的。

在网页当中,

V即View视图是指用户看到并与之交互的界面。比如由html元素组成的网页界面,或者软件的客户端界面。MVC的好处之一在于它能为应用程序处理很多不同的视图。在视图中其实没有真正的处理发生,它只是作为一种输出数据并允许用户操纵的方式。

M即model模型是指模型表示业务规则。在MVC的三个部件中,模型拥有最多的处理任务。被模型返回的数据是中立的,模型与数据格式无关,这样一个模型能为多个视图提供数据,由于应用于模型的代码只需写一次就可以被多个视图重用,所以减少了代码的重复性。

C即controller控制器是指控制器接受用户的输入并调用模型和视图去完成用户的需求,控制器本身不输出任何东西和做任何处理。它只是接收请求并决定调用哪个模型构件去处理请求,然后再确定用哪个视图来显示返回的数据。

下图说明了三者之间的调用关系。

用户首先在界面中进行人机交互,然后请求发送到控制器,控制器根据请求类型和请求的指令发送到相应的模型,模型可以与数据库进行交互,进行增删改查操作,完成之后,根据业务的逻辑选择相应的视图进行显示,此时用户获得此次交互的反馈信息,用户可以进行下一步交互,如此循环。

 

项目简介

使用IDEA作为编译环境,项目目录如下:

为了方便Usditor文本编译器的使用,将.jsp文件放在了utf8的文件夹下。

主要java类的介绍:

DBConn类作为连接数据库和对数据库进行增删改查方法的设计类

package myJava;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

public final class DBConn {
    @Test
    //连接数据库
    public  static SqlSession getSqlSession() {
        String resource = "myXML/mybatis-config.xml";
        InputStream inputStream = null;
        SqlSession session = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            session = sqlSessionFactory.openSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return session;
    }

    //校验用户信息
    public static Boolean check(Employee emp){
        SqlSession sqlSession = getSqlSession();
        try {
            //selectOne的第一个参数为Mapper.xml的mapper的namespace+id
            //参数二为映射的需要传入的参数
            Employee employee = sqlSession.selectOne(
                    "EmployeeMapper.selectEmployee_name", emp.getName());
            if (employee!=null && employee.getPassword().equals(emp.getPassword()))
                return true;
            else
                return false;
        } finally {
            free(sqlSession);
        }
    }

    //获取数据库的全部数据
    public static List<News> getAllNews(){
        SqlSession sqlSession = getSqlSession();
        List<News> list = sqlSession.selectList("EmployeeMapper.selectNews");
        free(sqlSession);
        return list;
    }

    public static News getNewsById(int id){
        SqlSession sqlSession = getSqlSession();
        News news = sqlSession.selectOne("EmployeeMapper.selectById",id);
        free(sqlSession);
        return news;
    }

    //向数据库添加数据,并且需要sqlSession.commit()
    public static void insertNews(News news){
        SqlSession sqlSession = getSqlSession();
        int result =sqlSession.insert("EmployeeMapper.insertNews",news);
        sqlSession.commit();
        free(sqlSession);
    }

    //删除新闻
    public static int deleteNews(int id){
        SqlSession sqlSession = getSqlSession();
        int result = sqlSession.delete("EmployeeMapper.deleteNewsById",id);
        sqlSession.commit();
        free(sqlSession);
        return result;
    }



    //修改新闻信息
    public static int upDataNewsById(News news){
        SqlSession sqlSession = getSqlSession();
        int res = sqlSession.update("EmployeeMapper.upDataNewsById",news);
        sqlSession.commit();
        free(sqlSession);
        return res;
    }


    //释放Sqlsession
    public static void free(SqlSession sqlSession){
        sqlSession.close();
    }
}

 

 

HelloWorld类作为请求映射的响应和逻辑业务的处理类,即Controller。

package mySpringMVC;
import myJava.DBConn;
import myJava.Employee;
import myJava.Modify;
import myJava.News;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;


@Controller
@RequestMapping("/utf8")
public class HelloWorld{

    @RequestMapping("/helloWorld")
    public String showNews(News news){
        System.out.println("Hello World!");
        System.out.println(news);
//        String exec = new ActionEnter(request, rootPath).exec();
        return "success";
    }

    @RequestMapping("/back")
    public ModelAndView back(){
        return getAllData();
    }

    @RequestMapping("/login")
    public ModelAndView checkLogin(Employee employee){
        //判断用户账号和密码
        Boolean isTrue = DBConn.check(employee);
        if (isTrue)
        {
            return getAllData();
        }
        else
            return new ModelAndView("loginAgain");//在视图解析器中添加前缀和后缀
    }

    @RequestMapping("/Info")
    public ModelAndView newsInfo(@RequestParam("id") int id){
        News news =DBConn.getNewsById(id);
        ModelAndView modelAndView = new ModelAndView("info");
        modelAndView.addObject("one",news);
        return modelAndView;
    }

    @RequestMapping(value = "/AddNews")
    public ModelAndView addNews(@RequestParam("title") String title, @RequestParam("author") String author,
                                @RequestParam("content") String content){

        News news = new News();
        news.setTitle(title);
        news.setAuthor(author);
        news.setContent(content);
        news.setTime(new Date());

        if (!Modify.modify){
            //向数据库写入数据
            DBConn.insertNews(news);
        }
        else{
            news.setId(Modify.modifyId);
            DBConn.upDataNewsById(news);
            //重置Modify为默认状态
            Modify.modify = false;
            Modify.modifyId = -1;
        }
        return getAllData();
    }

    @RequestMapping("/delete")
    public ModelAndView deleteNews(@RequestParam("id") int id){
        DBConn.deleteNews(id);
        return getAllData();
    }

    @RequestMapping("/upData")
    public ModelAndView upDataMethod(@RequestParam("id") int id){
        //数据库获取待修改的新闻信息
        News news = DBConn.getNewsById(id);
        //将数据发送至新闻编辑页面进行填充
        ModelAndView modelAndView = new ModelAndView("addNews");
        modelAndView.addObject("updata",news);
        //设置修改操作的标识
        Modify.modify = true;
        //设置修改的新闻id
        Modify.modifyId = id;
        return modelAndView;
    }


    public ModelAndView getAllData(){
        List<News> list = DBConn.getAllNews();
        //创建返回数据的ModelAndView
        ModelAndView modelAndView = new ModelAndView("newsPublish");
        modelAndView.addObject("list",list);
        return modelAndView;
    }
}

 

Employee和News为对应用户和新闻属性的JavaBean。

配置文件介绍:

myXML/EmployeeMapper.xml作为mybatis的mapper的SQL语句映射。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="EmployeeMapper">
    <select id="selectEmployee_name" parameterType="String" resultType="myJava.Employee">
        select * from employee where name = #{name}
   </select>

    <select id="selectNews" resultType="myJava.News">
        select * from news
   </select>

    <select id="selectById" parameterType="int" resultType="myJava.News">
        select * from news where id = #{id}
    </select>

    <insert id="insertNews" useGeneratedKeys="true" keyProperty="id">
        insert into news (title, author, content, time) values (#{title},#{author},#{content},#{time})
    </insert>

    <delete id="deleteNewsById" parameterType="int">
        delete from news where id = #{id}
    </delete>

    <update id="upDataNewsById">
        update news set title=#{title},author=#{author},content=#{content} where id = #{id}
    </update>
</mapper>

 

 

myXML/mybatis-config.xml则是MySQL数据库的连接操作。

*****当连接MySQL数据库时,有时会出现连接错误,具体错误类型忘了,可以将url设置为

url="jdbc:mysql://localhost:3306/mydatabase?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=true&amp;serverTimezone=GMT%2B8"

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!--jdbc:mysql://localhost:3306/mydatabase?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=true&amp;serverTimezone=GMT%2B8-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mydatabase?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=true&amp;serverTimezone=GMT%2B8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="myXML/EmployeeMapper.xml"/>
    </mappers>
</configuration>

 

运行效果展示:

1.登录及账户或者密码错误

 

新闻发布页面(要实现修改,删除和点击标题跳转到info.jsp页面显示具体新闻内容,固定每一个新闻的宽高,当超过固定值时则用.....省略显示):

添加新闻:

 

 

百度网盘:链接: https://pan.baidu.com/s/1d-Z1hFB6iV0_a0Mx8IuQlQ 提取码: g4s6 

 

posted @ 2019-04-14 19:13  、所剩无几  阅读(402)  评论(0编辑  收藏  举报