SSM框架学习

SSM(Spring+SpringMVC+MyBatis)框架中的新闻管理系统

最近,开始学习SSM框架,经过3天,终于学会了在SSM框架中的增删改查,以及controller层的操作
说明:数据库用的是mySQL,用了Navicat可视化工具,IDE是idea
1. 打开SSM项目,找到我们的SSM项目framework web目录下的pom.xml打开它
这里写图片描述
2. 在这里展示一下SSM项目的目录结构
这是大体上的目录,大概有.idea service web三大层目录
这里写图片描述


a. 开始数据库连接
找到web->resources->database-config.xml
将蓝色区域换成自己建的数据库名即可,其他的不用管,都是MyBatis里面的语句
这里写图片描述
后面要写的内容如目录所示
这里写图片描述
b. 开始写实体类entity
找到service->common->entity->News

    package com.pandawork.common.entity;

import com.pandawork.core.common.entity.AbstractEntity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * 新闻实体类
 * Created by 侯淑婷 on 2017/8/6.
 */
@Table(name = "t_news") //表名
@Entity //实体类
public class News extends AbstractEntity {

    //新闻ID
    @Id
    public Integer id;

    //新闻标题
    @Column(name = "news_title")
    private String newsTitle;

    //作者姓名
    @Column(name = "author")
    private String author;

    //发布日期
    @Column(name = "date")
    private String date;

    //文章内容
    @Column(name = "content")
    private String content;

    //文章类型
    @Column(name = "news_type")
    private String newsType;


    //获取新闻ID
    public Integer getId() {
        return id;
    }

    //设置新闻ID
    public void setId(Integer id) {
        this.id = id;
    }

    //获取新闻标题
    public String getNewsTitle() {
        return newsTitle;
    }

    //设置新闻标题
    public void setNewsTitle(String newsTitle) {
        this.newsTitle = newsTitle;
    }

    //获取新闻作者
    public String getAuthor() {
        return author;
    }

    //设置新闻作者
    public void setAuthor(String author) {
        this.author = author;
    }

    //获取发布日期
    public String getDate() {
        return date;
    }

    //设置发布日期
    public void setDate(String date) {
        this.date = date;
    }

    //获取新闻内容
    public String getContent() {
        return content;
    }

    //设置新闻内容
    public void setContent(String content) {
        this.content = content;
    }

    //获取新闻类型
    public String getNewsType() {
        return newsType;
    }

    //设置新闻类型
    public void setNewsType(String newsType) {
        this.newsType = newsType;
    }

    //重写新闻的toString方法
    @Override
    public String toString() {
        return "News{" +
                "id=" + id +
                ", newsTitle='" + newsTitle + '\'' +
                ", author='" + author + '\'' +
                ", date='" + date + '\'' +
                ", content='" + content + '\'' +
                ", newsType='" + newsType + '\'' +
                '}';
    }

}

c. 写Mapper目录下对应的NewsMapper

package com.pandawork.mapper;

import com.pandawork.common.entity.News;

import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * 新闻信息管理Mapper层
 * (增加新闻,删除新闻,更新新闻,
 * 根据id查询新闻内容,根据关键字查询新闻,
 * 根据新闻类型查找所存在的新闻,
 * 查询所有新闻列表)
 * Created by 侯淑婷 on 2017/8/6.
 */
public interface NewsMapper {

    /**
     * 增加新闻
     * @param news 新闻
     * @throws Exception 异常
     */
    public void insertNews(@Param("news") News news) throws Exception;


    /**
     *删除新闻
     * @param id id
     * @throws Exception 异常
     */
    public boolean delById(@Param("id") int id) throws Exception;


    /**
     * 更新新闻
     * @param news 新闻
     * @return 返回新闻类
     * @throws Exception 异常
     */
    public void updateNews(@Param("news") News news) throws Exception;


    /**
     * 根据id查询新闻内容
     * @param id id
     * @return 返回新闻
     * @throws Exception 异常
     */
    public News selectById(@Param("id") int id) throws Exception;


    /**
     * 根据关键字查询新闻
     * @param keyWord 关键字
     * @return 返回list
     * @throws Exception 异常
     */
    public List<News> queryByWord(@Param("keyWord") String keyWord) throws Exception;


    /**
     * 根据新闻类型查找所存在的新闻
     * @param newsType 类型关键字
     * @return 返回list
     * @throws Exception 异常
     */
    public List<News> queryByType(@Param("newsType") String newsType) throws Exception;


    /**
     * 查询所有新闻列表
     * @return 返回List值
     * @throws Exception 异常
     */
    public List<News> listAll( ) throws Exception;


}

这些是要实现的功能,其中要说明注意的一点就是:
这里参数前面的@Param(“…”)要与表单的name值一样
因为Spring会自动将表单参数注入到方法参数,和表单的name属性保持一致

d. 写NewsMapper对应的xml
找到service->resources->NewsMapper.xml

<?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="com.pandawork.mapper.NewsMapper">

    <!--增加新闻-->
    <insert id="insertNews">
        INSERT INTO `t_news`
        (`id`, `news_title`, `author`, `date`,
        `content`, `news_type`)
        VALUES (#{news.id}, #{news.newsTitle},
        #{news.author}, #{news.date},
        #{news.content}, #{news.newsType})
    </insert>

    <!--删除新闻-->
    <delete id="delById">
        DELETE FROM `t_news`
        WHERE `id` = #{id}
    </delete>

    <!--修改新闻-->
    <update id="updateNews">
        UPDATE `t_news`
        SET `news_title` = #{news.newsTitle},
            `author` = #{news.author},
            `date` = #{news.date},
            `content` = #{news.content},
            `news_type` = #{news.newsType}
        WHERE `id` = #{news.id}
    </update>

    <!--根据ID查询新闻内容-->
    <select id="selectById" resultMap="pw.News" >
        SELECT *
        FROM `t_news`
        WHERE `id` = #{id}
    </select>


    <!--根据keyWord查询新闻内容-->
    <select id="queryByWord" resultMap="pw.News">
        SELECT *
        FROM `t_news`
        WHERE `news_title` LIKE CONCAT ('%',#{keyWord},'%')
    </select>


    <!--根据Type查新闻列表-->
    <select id="queryByType" resultMap="pw.News">
        SELECT *
        FROM `t_news`
        WHERE `news_type` = #{newsType}
    </select>

    <!--查询新闻列表-->
    <select id="listAll" resultMap="pw.News">
        SELECT *
        FROM `t_news`
    </select>

</mapper>

e. 写service目录下的接口及其实现
找到service->NewsService

package com.pandawork.service;

import com.pandawork.common.entity.News;

import com.pandawork.core.common.exception.SSException;

import java.util.List;

/**
 * 新闻管理系统(增加新闻,删除新闻,更新新闻,
 * 根据ID查询新闻内容,根据Keyword查询新闻,
 * 根据Type查询新闻列表,新闻列表)
 * newsService层
 * Created by 侯淑婷 on 2017/8/6.
 */
public interface NewsService {


    /**
     * 增加新闻
     * @throws SSException 异常
     */
    public void insertNews(News news) throws SSException;


    /**
     * 删除新闻
     * @throws SSException 异常
     */
    public boolean delById(int id) throws SSException;


    /**
     * 更新新闻
     * @throws SSException 异常
     */
    public void updateNews(News news) throws SSException;


    /**
     * 根据ID查询新闻内容
     * @param id id
     * @return 返回新闻类
     * @throws SSException 异常
     */
    public News selectById(int id) throws SSException;


    /**
     * 根据Keyword查询新闻
     * @param keyWord 关键字
     * @return 返回list
     * @throws SSException 异常
     */
    public List<News> queryByWord(String keyWord) throws SSException;


    /**
     * 根据Type查询新闻列表
     * @param newsType 新闻类型
     * @return 返回list
     * @throws SSException 异常
     */
    public List<News> queryByType(String newsType) throws SSException;


    /**
     * 新闻列表
     * @return 返回list
     * @throws SSException 异常
     */
    public List<News> listAll( ) throws SSException;

}

与前面写的Mapper不同的地方就是没有@Param(“…”)
写srvice的实体类
找到service->impl->NewsServiceImpl

package com.pandawork.service.impl;

import com.pandawork.common.entity.News;
import com.pandawork.common.utils.NFException;
import com.pandawork.core.common.exception.SSException;
import com.pandawork.core.common.log.LogClerk;
import com.pandawork.core.common.util.Assert;
import com.pandawork.mapper.NewsMapper;
import com.pandawork.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

/**
 * 新闻管理系统
 * newsService的实现
 * Created by 侯淑婷 on 2016/8/6.
 */
@Service("newsService")
public class NewsServiceImpl implements NewsService {

    @Autowired
    NewsMapper newsMapper;
    //有的时候这里会冒红线,这不影响整个项目的运行,可以不用管它

    /**
     * 增加新闻
     * @param news 新闻
     * @throws SSException 异常
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {SSException.class, Exception.class, RuntimeException.class})
    public void insertNews(News news) throws SSException {
        if (Assert.isNull(news)) {
            return;
        }
        Assert.isNotNull(news.getNewsTitle(), NFException.NewsTitleNotNull);
        Assert.isNotNull(news.getAuthor(), NFException.AuthorNotNull);
        Assert.isNotNull(news.getDate(), NFException.DateNotNull);
        Assert.isNotNull(news.getContent(), NFException.NewsContentNotNull);
        try {
            newsMapper.insertNews(news);
        } catch (Exception e) {
            LogClerk.errLog.error(e);
            throw SSException.get(NFException.SystemException, e);
        }
    }

    /**
     * 删除新闻
     * @param id id
     * @return 返回布尔类型
     * @throws SSException 异常
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {SSException.class, Exception.class, RuntimeException.class})
    public boolean delById(int id) throws SSException {
        if (Assert.lessOrEqualZero(id)) {
            return false;
        }
        try {
            return newsMapper.delById(id);
        } catch (Exception e) {
            LogClerk.errLog.error(e);
            throw SSException.get(NFException.DelNewsNull, e);
        }
    }

    /**
     * 修改新闻
     * @param news 新闻
     * @throws SSException 异常
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {SSException.class, Exception.class, RuntimeException.class})
    public void updateNews(News news) throws SSException {
        if (Assert.isNull(news))
             return;
        try {
            newsMapper.updateNews(news);
        } catch (Exception e) {
            LogClerk.errLog.error(e);
            throw SSException.get(NFException.UpdateNewsFailed, e);
        }
    }

    /**
     * 根据ID查找新闻
     * @param id id
     * @return 返回新闻类
     * @throws SSException
     */
    @Override
    public News selectById(int id) throws SSException {
        if (Assert.lessOrEqualZero(id)) {
            return null;
        }
        try {
           return newsMapper.selectById(id);
        } catch (Exception e) {
            LogClerk.errLog.error(e);
            throw SSException.get(NFException.SelectNewsByIdFailed, e);
        }

    }

    /**
     * 根据关键字查找新闻列表
     * @param keyWord 关键字
     * @return 返回list
     * @throws SSException 异常
     */
    public List<News> queryByWord(String keyWord) throws SSException{
        if(Assert.isNull(keyWord)){
            return null;
        }
        try{
            return newsMapper.queryByWord(keyWord);
        }catch (Exception e){
            LogClerk.errLog.error(e);
            throw SSException.get(NFException.QueryByKeyWordFailed);
        }
    }

    /**
     * 根据类型查找新闻列表
     * @param newsType 新闻类型
     * @return 返回file
     * @throws SSException 异常
     */
    @Override
    public List<News> queryByType(String newsType) throws SSException {
        if (Assert.isNull(newsType)) {
            return null;
        }
        try {
            return newsMapper.queryByType(newsType);
        } catch (Exception e) {
            LogClerk.errLog.error(e);
            throw SSException.get(NFException.QueryByTypeFailed, e);
        }
    }


    /**
     * 新闻列表
     * @return 返回list
     * @throws SSException 异常
     */
    @Override
    public List<News> listAll() throws SSException {
        List<News> newsList = Collections.emptyList();
        try {
            newsList = newsMapper.listAll();
        } catch (Exception e) {
            LogClerk.errLog.error(e);
            throw SSException.get(NFException.ListNewsAll, e);
        }
        return newsList;
    }
}

f. 开始写测试类,测试上述方法
目录如下
这里写图片描述
我们一开始打开它的时候,如果不是绿色的,请设置一下:
单击右键Test文件夹->Make Directory as->Test Sources Root即可
这里写图片描述
除此之外,还有一点注意的地方,要将NewsService加入到一个地方:
找到web->java->spring
这里写图片描述
在后面加上
这里写图片描述

package com.pandawork.test;

import com.pandawork.common.entity.News;
import com.pandawork.core.common.exception.SSException;
import com.pandawork.service.NewsService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * 新闻管理系统(测试新增新闻,测试删除新闻,测试更新新闻,
 * 测试根据ID查询新闻内容,测试根据Type查询新闻,
 * 测试根据关键字查询新闻内容,测试查询新闻列表)
 * 测试service页面
 * newsService
 * Created by fujia on 2016/3/26.
 */
public class NewsServiceTest extends AbstractTestCase {

    @Autowired
    NewsService newsService;

    //测试新增新闻
    @Test
    public void testInsertNews() throws SSException {
        News news = new News();
        news.setNewsTitle("鹿晗来长春了");
        news.setAuthor("娱乐小道");
        news.setDate("8月2日");
        news.setContent("他来这儿干嘛?骗你的啦!");
        news.setNewsType("娱乐");
        newsService.insertNews(news);
        System.out.println("添加成功");
    }


    //测试删除新闻
    @Test
    public void testDelById() throws SSException{
        News news = new News();
        news.setId(11);
        newsService.delById(news.getId());
        System.out.println("16");
    }


    //测试更新新闻
    @Test
    public void testUpdate() throws SSException{
        News news = new News();
        news.setNewsTitle("当你心情不好的时候要干啥?");
        news.setAuthor("心灵小静");
        news.setDate("10月15日");
        news.setContent("最好的办法就是锻炼!");
        news.setNewsType("心情");
        news.setId(15);
        newsService.updateNews(news);
        System.out.println("12");
    }


    //测试根据ID查询新闻内容
    @Test
    public void testSelectById() throws SSException {
        newsService.selectById(1);
        System.out.println(newsService.selectById(1));
    }

    //测试根据关键字查询新闻内容
    @Test
    public void testQueryByWord() throws SSException{
        List<News> list = new ArrayList<News>();
        list = newsService.queryByWord("鹿晗");
        System.out.println(list);
    }

    //测试根据Type查询新闻
    @Test
    public void testQueryByType() throws SSException{
        List<News> list = new ArrayList<News>();
        list = newsService.queryByType("娱乐");
        System.out.println(list);
    }


    //测试查询新闻列表
    @Test
    public void testListAll() throws SSException{
        System.out.print(newsService.listAll());
    }

}

g. 接下来便是开始写jsp页面以及NewsController
目录结构如下:找到web->webapp
这里写图片描述
为了安全性,我们把jsp页面放在WEB-INF目录的views下,这样就不会被浏览器直接访问到,然后从目录外面的start.jsp跳转进去
不过因为系统默认是index.jsp,所以我们需要在web.xml配置一下
这里写图片描述
哈哈还可以再跳转一下进入到新闻首页
这里写图片描述
对应的NewsController如图所示:

package com.pandawork.web.controller;

import com.pandawork.common.entity.News;
import com.pandawork.common.entity.Type;
import com.pandawork.core.common.exception.SSException;
import com.pandawork.core.common.log.LogClerk;
import com.pandawork.core.common.util.Assert;
import com.pandawork.web.spring.AbstractController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Collections;
import java.util.List;

/**
 * NewsController层
 * (添加跳转操作,添加新闻,删除新闻,浏览新闻页面,
 * 更新新闻页面,更新新闻返回浏览页面,关键字搜索,
 * 新闻列表)
 * Created by 侯淑婷 on 2017/8/7.
 */
@Controller
@RequestMapping("/news")
public class NewsController extends AbstractController {


    /**
     * 添加跳转操作
     * @return 返回
     */
    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public String toAddNews(Model model){
        try{
            List<Type> typeList = Collections.emptyList();
            typeList = typeService.listAll();
            model.addAttribute("typeList",typeList);
            return "add";
        }catch(SSException e){
            LogClerk.errLog.error(e);
            sendErrMsg(e.getMessage());
            return ADMIN_SYS_ERR_PAGE;
        }
    }


    /**
     * 添加新闻
     * @param news news
     * @return 返回
     */
    @RequestMapping(value = "/insert",method = RequestMethod.POST)
    public String addNews(News news){
        try{
            newsService.insertNews(news);
            return "redirect:/news/list";
        }catch(SSException e){
            LogClerk.errLog.error(e);
            sendErrMsg(e.getMessage());
            return ADMIN_SYS_ERR_PAGE;
        }

    }


    /**
     * 删除新闻
     * @param id id
     * @return 返回
     */
    @RequestMapping(value = "/delete/{id}",method = RequestMethod.GET)
    public String deleteNews(@PathVariable("id") int id){
        try{
            newsService.delById(id);
            System.out.println("删除成功");
            return "redirect:/news/list";//删除后还需重定向页面才可获取最新列表
        }catch(SSException e){
            LogClerk.errLog.error(e);
            sendErrMsg(e.getMessage());
            return ADMIN_SYS_ERR_PAGE;
        }
    }


    /**
     * 浏览新闻页面
     * @param id id
     * @param model model
     * @return 返回
     */
    @RequestMapping(value = "/select/{id}",method = RequestMethod.GET)
    public String selectNews(@PathVariable("id") int id,Model model) {
        try {
            News news = new News();
            news = newsService.selectById(id);
            model.addAttribute("news",news);
            return "select";
        }catch (SSException e){
            LogClerk.errLog.error(e);
            sendErrMsg(e.getMessage());
            return ADMIN_SYS_ERR_PAGE;
        }
    }

    /**
     * 更新新闻页面
     * @param id id
     * @param model model
     * @return 返回
     */
    @RequestMapping(value = "/edit/{id}",method = RequestMethod.GET)
    public String edit(@PathVariable("id") int id,Model model){
        try{
            News news = new News();
            news = newsService.selectById(id);
            model.addAttribute("news",news);
            return "edit";
        }catch(SSException e){
            LogClerk.errLog.error(e);
            sendErrMsg(e.getMessage());
            return ADMIN_SYS_ERR_PAGE;
        }

    }


    /**
     *更新新闻返回浏览页面
     * @param news news
     * @param id id
     * @param model model
     * @return 返回
     */
    @RequestMapping(value = "/update/{id}",method = RequestMethod.POST)
    public String updateNews(News news,@PathVariable("id")int id, Model model){
        try{
            if(Assert.isNull(news)){
                return null;
            }
            news.setId(id);
            model.addAttribute("news",news);
            newsService.updateNews(news);
            return "select";
        }catch(SSException e){
            LogClerk.errLog.error(e);
            sendErrMsg(e.getMessage());
            return ADMIN_SYS_ERR_PAGE;
        }
    }

    /**
     * 关键字搜索
     * @param keyWord keyWord
     * @param model model
     * @return 返回
     */
    @RequestMapping(value = "/search",method = RequestMethod.GET)
    public String queryByWord(@RequestParam String keyWord, Model model){
        try{
            List<News> list = Collections.emptyList();
            list = newsService.queryByWord(keyWord);
            model.addAttribute("list",list);
            return "search";
        }catch(SSException e){
            LogClerk.errLog.error(e);
            sendErrMsg(e.getMessage());
            return ADMIN_SYS_ERR_PAGE;
        }
    }


    /**
     * 新闻列表
     * @param model model
     * @return 返回
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public String newsList(Model model){
        try{
            List<News> list = Collections.emptyList();
            List<Type> typelist = Collections.emptyList();
            list = newsService.listAll();
            typelist = typeService.listAll();
            model.addAttribute("list",list);
            model.addAttribute("typelist",typelist);
            return "news_list";
        }catch(SSException e){
            LogClerk.errLog.error(e);
            sendErrMsg(e.getMessage());
            return ADMIN_SYS_ERR_PAGE;
        }
    }


}

在这里就献一下丑,仅展示一下新闻首页吧

<body>
<div>
    <%
        int num=0;
    %>
    <h1 align="center">新闻首页</h1>
    <table align="center" >
        <tr>
            <td align="center"><a href="${website}type/list">新闻类型:</a></td>
            <c:forEach items="${typelist}" var="type" varStatus="status">
                <td><a href="${website}type/catch/${type.typeName}">${type.typeName}</a></td>
                <%
                    ++num;
                    if(num == 10){
                        System.out.println();
                    }
                %>
            </c:forEach>
            <td align="center"><a href="${website}type/type_op">类型操作</a></td>
        </tr>
    </table>
    <form action="${website}news/search" method="get">
        <span><input type="text" name="keyWord" style="width: 360px"></span>
        <span><input type="submit" value="搜索新闻关键字"></span>
    </form>
    <br>
    <table border="1" align="center" width="500px" cellspacing="0" id="ahh">
        <tr>
            <th>新闻条目</th>
            <th>新闻标题</th>
            <td>类型</td>
            <th>发布时间</th>
            <th>修改</th>
            <th>删除</th>
        </tr>
        <c:forEach  items="${list}" var="news" varStatus="status">
        <tr bgcolor="#ffebcd">
            <td align="center">${status.index + 1}</td>
            <td><a href="${website}news/select/${news.id}">${news.newsTitle}</a></td>
            <td>${news.newsType}</td>
            <td>${news.date}</td>
            <td><a href="${website}news/edit/${news.id}">修改</a></td>
            <td><a href="${website}news/delete/${news.id}">删除</a></td>
        </tr>
        </c:forEach>
        <tr>
            <td colspan="6"><a href="${website}news/add">添加</a></td>
        </tr>
    </table>
</div>
</body>

这便是SSM项目的流程和代码了,这些方法都是通过的
这里写图片描述
这就是我写的新闻管理系统,由于时间较短,有点简陋,本来还想加一个用户登录和管理员的,这次就先写到这里吧,不喜勿喷,欢迎大家来吐槽^ @ ^

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值