By GokiSoft.com| 09:56 08/08/2022|
Spring MVC

[Source Code] Quản lý tin tức Spring MVC - C2010G



B1) Tạo CSDL
create table category (
	id int primary key auto_increment,
	name varchar(50)
);

create table news (
	id int primary key auto_increment,
	id_category int,
	title varchar(250),
	content longtext,
	thumbnail varchar(500),
	created_at datetime,
	updated_at datetime
);

alter table news
add constraint fk_id_category foreign key(id_category) references category (id);

B2) Gen Tables (Entities & ORM)
B3) Phat trien chuc nang
- CRUD: news
	controller: NewsController
	> route:
		- news/index.html -> hien thi danh sach
		- news/create.html -> view add
		- news/store.html -> add du lieu vao database
		- news/edit.html -> view edit
		- news/update.html -> Luu thay doi
		- news/delete.html -> view confirm xoa du lieu
		- news/confirm-delete.html -> Xoa that
	




#NewsController.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gokisoft.controller;

import com.gokisoft.entities.Category;
import com.gokisoft.entities.News;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 *
 * @author Administrator
 */
@Controller
@RequestMapping(value = "/news")
public class NewsController {
    EntityManagerFactory factory = null;
    EntityManager manager = null;
    
    public NewsController() {
        factory = Persistence.createEntityManagerFactory("SpringMVCPU");
        manager = factory.createEntityManager();
    }
    
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(ModelMap modelMap) {
        Query q = manager.createNamedQuery("News.findAll", News.class);
        List<News> newsList = q.getResultList();
        
        modelMap.addAttribute("newsList", newsList);
        
        return "news/index";
    }
    
    @RequestMapping(value = "add", method = RequestMethod.GET)
    public String add(ModelMap modelMap) {
        Query q = manager.createNamedQuery("Category.findAll", Category.class);
        List<Category> categoryList = q.getResultList();
        
        modelMap.addAttribute("categoryList", categoryList);
        
        return "news/add";
    }
    
    @RequestMapping(value = "store", method = RequestMethod.POST)
    public String store(@RequestParam HashMap<String, String> formData) {
        String title = formData.get("title");
        String thumbnail = formData.get("thumbnail");
        int idCategory = Integer.parseInt(formData.get("id_category"));
        String content = formData.get("content");
        
        Category category = manager.find(Category.class, idCategory);
        
        News news = new News();
        news.setTitle(title);
        news.setContent(content);
        news.setThumbnail(thumbnail);
        news.setCreatedAt(new Date());
        news.setUpdatedAt(new Date());
        news.setIdCategory(category);
        
        manager.getTransaction().begin();
        manager.persist(news);
        manager.getTransaction().commit();
        
        return "redirect:index.html";
    }
    
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(@RequestParam HashMap<String, String> formData, ModelMap modelMap) {
        int id = Integer.parseInt(formData.get("id"));
        
        News news = manager.find(News.class, id);
        
        modelMap.addAttribute("news", news);
        
        Query q = manager.createNamedQuery("Category.findAll", Category.class);
        List<Category> categoryList = q.getResultList();
        
        modelMap.addAttribute("categoryList", categoryList);
        
        return "news/edit";
    }
    
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(@RequestParam HashMap<String, String> formData) {
        String title = formData.get("title");
        String thumbnail = formData.get("thumbnail");
        int idCategory = Integer.parseInt(formData.get("id_category"));
        String content = formData.get("content");
        int id = Integer.parseInt(formData.get("id"));
        
        Category category = manager.find(Category.class, idCategory);
        
        News news = manager.find(News.class, id);
        news.setTitle(title);
        news.setContent(content);
        news.setThumbnail(thumbnail);
        news.setUpdatedAt(new Date());
        news.setIdCategory(category);
        
        manager.getTransaction().begin();
        manager.persist(news);
        manager.getTransaction().commit();
        
        return "redirect:index.html";
    }
    
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String delete(@RequestParam HashMap<String, String> formData, ModelMap modelMap) {
        int id = Integer.parseInt(formData.get("id"));
        
        News news = manager.find(News.class, id);
        modelMap.addAttribute("news", news);
        
        return "news/delete";
    }
    
    @RequestMapping(value = "/confirm-delete", method = RequestMethod.POST)
    public String confirmDelete(@RequestParam HashMap<String, String> formData) {
        int id = Integer.parseInt(formData.get("id"));
        
        News news = manager.find(News.class, id);
        manager.getTransaction().begin();
        manager.remove(news);
        manager.getTransaction().commit();
        
        return "redirect:index.html";
    }
}


#add.jsp


<%-- 
    Document   : add
    Created on : Aug 3, 2022, 8:42:58 AM
    Author     : Administrator
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>View - Form Add News</title>
        <meta charset="utf-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"/>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    </head>
    <body>
        <div class="container">
            <h1 style="text-align: center">Add a news</h1>
            <div class="row">
                <div class="col-md-12">
                    <form method="post" action="store.html">
                        <div class="form-group">
                            <label>Title: </label>
                            <input required="true" type="text" name="title" class="form-control" placeholder="Enter title"/>
                        </div>
                        <div class="form-group">
                            <label>Thumbnail: </label>
                            <input required="true" type="text" name="thumbnail" class="form-control" placeholder="Enter thumbnail"/>
                        </div>
                        <div class="form-group">
                            <label>Category </label>
                            <select required="true" class="form-control" name="id_category">
                                <option value="">-- Select Category --</option>
                                <c:forEach items="${categoryList}" var="item">
                                    <option value="${item.id}">${item.name}</option>
                                </c:forEach>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Description: </label>
                            <textarea class="form-control" name="content" rows="5"></textarea>
                        </div>
                        <button class="btn btn-success">Add news</button>
                        <p style="margin-top: 20px">
                            <a href="index.html">Back to news list</a>
                        </p>
                    </form>
                </div>
            </div>
        </div>
    </body>
</html>


#delete.jsp


<%-- 
    Document   : add
    Created on : Aug 3, 2022, 8:42:58 AM
    Author     : Administrator
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Edit - Form Add News</title>
        <meta charset="utf-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"/>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    </head>
    <body>
        <div class="container">
            <h1 style="text-align: center">Add a news</h1>
            <div class="row">
                <div class="col-md-12">
                    <form method="post" action="confirm-delete.html">
                        <div class="form-group">
                            <label>Title: ${news.title}</label>
                            <input type="hidden" name="id" value="${news.id}"/>
                        </div>
                        <div class="form-group">
                            <label>Thumbnail: </label>
                            <img src="${news.thumbnail}" style="width: 200px"/>
                        </div>
                        <div class="form-group">
                            <label>Category: ${news.idCategory.name}</label>
                        </div>
                        <button class="btn btn-danger">Confirm to delete</button>
                        <p style="margin-top: 20px">
                            <a href="index.html">Back to news list</a>
                        </p>
                    </form>
                </div>
            </div>
        </div>
    </body>
</html>


#edit.jsp


<%-- 
    Document   : add
    Created on : Aug 3, 2022, 8:42:58 AM
    Author     : Administrator
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Edit - Form Add News</title>
        <meta charset="utf-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"/>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    </head>
    <body>
        <div class="container">
            <h1 style="text-align: center">Add a news</h1>
            <div class="row">
                <div class="col-md-12">
                    <form method="post" action="update.html">
                        <div class="form-group">
                            <label>Title: </label>
                            <input type="hidden" name="id" value="${news.id}"/>
                            <input required="true" type="text" name="title" class="form-control" placeholder="Enter title" value="${news.title}"/>
                        </div>
                        <div class="form-group">
                            <label>Thumbnail: </label>
                            <input required="true" type="text" name="thumbnail" class="form-control" placeholder="Enter thumbnail" value="${news.thumbnail}"/>
                        </div>
                        <div class="form-group">
                            <label>Category </label>
                            <select required="true" class="form-control" name="id_category">
                                <option value="">-- Select Category --</option>
                                <c:forEach items="${categoryList}" var="item">
                                    <c:if test="${item.id == news.idCategory.id}">
                                        <option value="${item.id}" selected="true">${item.name}</option>
                                    </c:if>
                                    <c:if test="${item.id != news.idCategory.id}">
                                        <option value="${item.id}" selected="true">${item.name}</option>
                                    </c:if>
                                </c:forEach>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Description: </label>
                            <textarea class="form-control" name="content" rows="5">${news.content}</textarea>
                        </div>
                        <button class="btn btn-success">Update</button>
                        <p style="margin-top: 20px">
                            <a href="index.html">Back to news list</a>
                        </p>
                    </form>
                </div>
            </div>
        </div>
    </body>
</html>


#index.jsp


<%-- 
    Document   : index
    Created on : Aug 3, 2022, 8:42:49 AM
    Author     : Administrator
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>News List</title>
        <meta charset="utf-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"/>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    </head>
    <body>
        <div class="container">
            <h1 style="text-align: center">News List</h1>
            <a href="add.html"><button class="btn btn-success" style="margin-bottom: 20px">Add a news</button></a>
            <table class="table table-hovered">
                <thead>
                    <tr>
                        <th style="width: 50px">STT</th>
                        <th style="width: 120px">Thumbnail</th>
                        <th>Title</th>
                        <th>Category</th>
                        <th>Updated At</th>
                        <th style="width: 50px"></th>
                        <th style="width: 50px"></th>
                    </tr>
                </thead>
                <tbody>
                    <c:forEach items="${newsList}" var="item" varStatus="loop">
                        <tr>
                            <td>${loop.index + 1}</td>
                            <td><img src="${item.thumbnail}" style="width: 120px"/></td>
                            <td>${item.title}</td>
                            <td>${item.idCategory.name}</td>
                            <td>${item.updatedAt}</td>
                            <td>
                                <a href="edit.html?id=${item.id}"><button class="btn btn-warning">Edit</button></a>
                            </td>
                            <td>
                                <a href="delete.html?id=${item.id}"><button class="btn btn-danger">Delete</button></a>
                            </td>
                        </tr>
                    </c:forEach>
                </tbody>
            </table>
        </div>
    </body>
</html>


Tags:

Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)