我是靠谱客的博主 飞快鲜花,最近开发中收集的这篇文章主要介绍项目:个人博客系统 Part3 Controller层编写,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

个人博客系统 Part3

 

Controller层分为两个模块:user模块和admin模块,分别对应博客的前台页面和后台管理页面。

 

一、user模块

由于Controller传递到前台的变量较多,且重复率很高,所以可以定义全局变量来保持部分常用变量的变量名固定。

编写一个AttributeConstant类,定义MAIN_PAGE/USER/PAGER/ARTICLE/ERROR等变量:

public class AttributeConstant {
public static final String ABOUT = "about";
public static final String MAIN_PAGE = "mainPage";
public static final String WEB_APP_DTO = "webAppDto";
public static final String ARTICLES = "articles";
public static final String ARTICLE ="article";
public static final String PAGER = "pager";
public static final String USER = "user";
public static final String USERS = "users";
public static final String CURRENT_USER = "currentUser";
public static final String RETURN_INFO = "info";
public static final Integer DAY_TIME = 1 * 60 * 60 * 24;
public static final String CATEGORIES = "categories";
public static final String CATEGORY = "category";
public static final String ERROR ="error";
}

 

包括主页Controller、文章列表、文章详情Controller、分类列表与详情、login;

1.ListController

文章列表ListController,需要调用自定义工具类Pager类来完成分页功能:

@Controller("/list")
public class ListController {
@Autowired
private ArticleService articleService;
@RequestMapping(method = RequestMethod.GET)
public String list(@RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex, ModelMap model, HttpServletRequest request) {
Pager pager = new Pager(pageIndex, 4, articleService.count());
model.addAttribute(AttributeConstant.MAIN_PAGE, "user/article/list.jsp");
model.addAttribute(AttributeConstant.ARTICLES, articleService.getPageArticles(pager));
model.addAttribute(AttributeConstant.PAGER, pager);
return "index";
}
}

其中index页面是公共页面,因为导航部分是所有页面都有的,所以可以共用:

<jsp:include page="common/nav.jsp"/>
<jsp:include page="${mainPage}"/>

 

2.ArticleController

显示文章详情页面,使用正则表达式[0-9]+匹配url,主要需要更新文章的点击量和获取上一篇、下一篇文章;

@Controller
public class ArticleController {
@Autowired
private ArticleService articleService;
//显示 详细文章
@RequestMapping("article/{articleId:[0-9]+}")
public String showArticle(@PathVariable("articleId")Integer articleId, ModelMap model){
ArticleDto articleDto = articleService.getArticle(articleId);
model.addAttribute(AttributeConstant.MAIN_PAGE, "user/article/item.jsp");
if(StringUtil.isNotEmpty(articleDto.getTitle())) {
//点击量+1
articleService.updateClicks(articleDto.getClicks() + 1, articleDto.getId());
//更新一下用于显示
articleDto.setClicks(articleDto.getClicks() + 1);
//获取上一篇文章
ArticleLiteDto preArticle = articleService.getPreArticle(articleDto.getId());
//获取下一篇文章
ArticleLiteDto nextArticle = articleService.getNextArticle(articleDto.getId());
model.addAttribute(AttributeConstant.ARTICLE, articleDto);
model.addAttribute("preArticle", preArticle);
model.addAttribute("nextArticle", nextArticle);
}else{
model.addAttribute(AttributeConstant.ERROR,"没有此文章");
}
return "index";
}
}

 

3.CategoryController

和Article类似,需要显示列表页面和详情页面,其中详情页面需要根据Category获取Articles:

@Controller
@RequestMapping()
public class CategoryController {
@Autowired
private CategoryService categoryService;
@Autowired
private ArticleService articleService;
//全部list
@RequestMapping("/category")
public String list(ModelMap model) {
List<CategoryDto> categories = categoryService.getCategories();
model.addAttribute(AttributeConstant.MAIN_PAGE, "user/category/categoryList.jsp");
model.addAttribute(AttributeConstant.CATEGORIES, categories);
return "index";
}
//详情
@RequestMapping("category/{categoryId:[0-9]+}")
public String detail(@PathVariable("categoryId") Integer categoryId, ModelMap model) {
Category category = categoryService.getCategory(categoryId);
model.addAttribute(AttributeConstant.MAIN_PAGE, "user/category/detail.jsp");
if (StringUtil.isNotEmpty(category.getName())) {
List<ArticleLiteDto> articles = articleService.getArticlesByCategory(categoryId);
if (articles.size() == 0) {
articles = null;
}
model.addAttribute(AttributeConstant.CATEGORY, category);
model.addAttribute(AttributeConstant.ARTICLES, articles);
} else {
model.addAttribute(AttributeConstant.ERROR, "找不到该分类");
}
return "index";
}
}
View Code

 

4.LoginController

Login模块包括:访问login页面、提交login操作、生成验证码功能;

访问login页面包括从cookies读取username和password的缓存

//登录页面
@RequestMapping(value="/login",method = RequestMethod.GET)
public String showLogin(HttpServletRequest request, Model model) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
String username = "";
String password = "";
for (Cookie cookie : cookies) {
if ("username".equals(cookie.getName())) {
username = cookie.getValue();
model.addAttribute("username", username);
}
if ("password".equals(cookie.getName())) {
password = cookie.getValue();
model.addAttribute("password", password);
}
}
}
return "user/login/login";
}

 

login登录操作,判断用户名、密码、验证码;成功则转向manage后台管理页面,否则显示错误。

//登陆操作
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(String username, String password, @RequestParam(defaultValue = "no") String remember, String code, ModelMap model, HttpSession session, HttpServletResponse response) {
User user = new User();
user.setUsername(username);
user.setPassword(MyMD5.MD5(password));
UserDto currentUser = userService.login(user);
if (code.toUpperCase().equals(session.getAttribute("code"))) {
if (currentUser != null) {
if (remember.equals("yes")) {
//记住我操作

rememberMe(username, password, response);
}
session.setAttribute(AttributeConstant.CURRENT_USER, currentUser);
//跳转
return "redirect:/manage";
} else {
model.addAttribute("error", "用户名或密码错误");
}
} else {
model.addAttribute("error", "验证码错误");
}
return "user/login/login";
}

 

 

二、admin模块

admin模块就是典型的后台管理模块了,主要是各个部分的增删改查功能;

 

1.ManageUserController

用户模块包括用户列表的显示以及用户增删改查:

@Controller
@RequestMapping("manage/user")
public class ManageUserController {
@Autowired
private UserService userService;
//显示用户列表
@RequestMapping(method = RequestMethod.GET)
public String showUsers(ModelMap model, HttpSession session) {
model.addAttribute(AttributeConstant.USER, (UserDto) session.getAttribute(AttributeConstant.CURRENT_USER));
model.addAttribute(AttributeConstant.MAIN_PAGE, "admin/user/editor.vm");
model.addAttribute(AttributeConstant.USERS, userService.getUsers());
return "admin/index";
}
//添加用户
@RequestMapping(value = "create", method = RequestMethod.POST)
public String createAction(User user, ModelMap model, HttpSession session) {
model.addAttribute(AttributeConstant.USER, (UserDto) session.getAttribute(AttributeConstant.CURRENT_USER));
model.addAttribute(AttributeConstant.MAIN_PAGE, "admin/user/editor.vm");
if (StringUtil.isNotEmpty(user.getUsername()) && StringUtil.isNotEmpty(user.getPassword()) && StringUtil.isNotEmpty(user.getNickname()) && StringUtil.isNotEmpty(user.getEmail())) {
if (userService.userIsNotEmpty(user.getUsername())) {
user.setPassword(MyMD5.MD5(user.getPassword()));
user.setImagePath("/static/img/1.jpg");
userService.saveUser(user);
model.addAttribute(AttributeConstant.RETURN_INFO, "用户添加成功!");
} else {
model.addAttribute(AttributeConstant.ERROR, "用户已存在!");
}
} else {
model.addAttribute(AttributeConstant.ERROR, "有未填写用户信息!");
}
model.addAttribute(AttributeConstant.USERS, userService.getUsers());
return "admin/index";
}
//根据ID显示更新页面
@RequestMapping(value = "update/{userId:[0-9]+}", method = RequestMethod.GET)
public String showUpdate(@PathVariable("userId") Integer userId, ModelMap model, HttpSession session) {
model.addAttribute(AttributeConstant.USER, (UserDto) session.getAttribute(AttributeConstant.CURRENT_USER));
model.addAttribute(AttributeConstant.MAIN_PAGE, "admin/user/editor.vm");
User user = userService.getUser(userId);
if (StringUtil.isNotEmpty(user.getUsername())) {
model.addAttribute("editoruser", user);
} else {
model.addAttribute(AttributeConstant.ERROR, "用户修改失败!");
}
model.addAttribute(AttributeConstant.USERS, userService.getUsers());
return "admin/index";
}
//更新用户操作
@RequestMapping(value = "update", method = RequestMethod.POST)
public String updateAction(User user, ModelMap model, HttpSession session) {
UserDto userDto = (UserDto) session.getAttribute(AttributeConstant.CURRENT_USER);
model.addAttribute(AttributeConstant.USER, userDto);
model.addAttribute(AttributeConstant.MAIN_PAGE, "admin/user/editor.vm");
if (StringUtil.isNotEmpty(user.getUsername()) && StringUtil.isNotEmpty(user.getPassword()) && StringUtil.isNotEmpty(user.getNickname()) && StringUtil.isNotEmpty(user.getEmail())) {
//如果管理员没有编辑选择用户的密码,就不在对密码进行MD5加密
if (!user.getPassword().equals(userService.getUser(user.getId()).getPassword())) {
user.setPassword(MyMD5.MD5(user.getPassword()));
}
userService.updateUser(user);
model.addAttribute(AttributeConstant.RETURN_INFO, "修改用户成功!");
//判断更新用户 是否为 当前登陆用户 如果是 需要更新当前登陆用户的 显示信息.
if (user.getId() == userDto.getId()) {
UserDto currentUser = userService.login(user);
session.setAttribute(AttributeConstant.CURRENT_USER, currentUser);
model.addAttribute(AttributeConstant.USER, currentUser);
}
} else {
model.addAttribute(AttributeConstant.ERROR, "有未填写用户信息!");
}
model.addAttribute(AttributeConstant.USERS, userService.getUsers());
return "admin/index";
}
//根据ID删除用户
@RequestMapping(value = "delete/{userId:[0-9]+}")
public String deleteAction(ModelMap model, HttpSession session, @PathVariable("userId") Integer userId) {
model.addAttribute(AttributeConstant.USER, (UserDto) session.getAttribute(AttributeConstant.CURRENT_USER));
model.addAttribute(AttributeConstant.MAIN_PAGE, "admin/user/editor.vm");
User user = userService.getUser(userId);
if (StringUtil.isNotEmpty(user.getUsername())) {
userService.deleteUser(userId);
model.addAttribute(AttributeConstant.RETURN_INFO, "删除用户成功!");
} else {
model.addAttribute(AttributeConstant.ERROR, "找不到该用户");
}
model.addAttribute(AttributeConstant.USERS, userService.getUsers());
return "admin/index";
}
}
View Code

 

2.ManageArticleController

文章管理模块

@Controller
@RequestMapping("manage/article")
public class ManageArticleController {
@Autowired
private CategoryService categoryService;
@Autowired
private ArticleService articleService;
@Autowired
private WebAppService webAppService;
//显示创建页面
@RequestMapping(value = "create", method = RequestMethod.GET)
public String showCreatePage(ModelMap model, HttpSession session) {
model.addAttribute(AttributeConstant.MAIN_PAGE, "admin/article/editorArticle.vm");
model.addAttribute(AttributeConstant.USER, (UserDto) session.getAttribute(AttributeConstant.CURRENT_USER));
model.addAttribute(AttributeConstant.CATEGORIES, categoryService.getCategories());
return "admin/index";
}
//创建操作
@RequestMapping(value = "create", method = RequestMethod.POST)
public String createAction(Article article, ModelMap model, HttpSession session) {
String path;
article.setClicks(0);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
article.setPubDate(formatter.format(new Date()));
if (StringUtil.isNotEmpty(article.getTitle()) && StringUtil.isNotEmpty(article.getMarkDown()) && StringUtil.isNotEmpty(article.getRemark())) {
articleService.saveArticle(article);
path = "redirect:/manage/article";
} else {
model.addAttribute(AttributeConstant.ERROR, "有未填选项,请核对后重新发布文章!");
model.addAttribute(AttributeConstant.MAIN_PAGE, "admin/article/editorArticle.vm");
model.addAttribute(AttributeConstant.USER, (UserDto) session.getAttribute(AttributeConstant.CURRENT_USER));
model.addAttribute(AttributeConstant.CATEGORIES, categoryService.getCategories());
path = "admin/index";
}
return path;
}
//显示文章列表
@RequestMapping(method = RequestMethod.GET)
public String showListArticle(ModelMap model, @RequestParam(defaultValue = "1") Integer currentPage, HttpSession session) {
Pager pager = new Pager(currentPage, webAppService.getWebAppDtos().get(0).getAdminPageArticleSize(), articleService.count());
List<ArticleDto> articles = articleService.getPageArticles(pager);
model.addAttribute(AttributeConstant.ARTICLES, articles);
model.addAttribute(AttributeConstant.PAGER, pager);
model.addAttribute(AttributeConstant.USER, (UserDto) session.getAttribute(AttributeConstant.CURRENT_USER));
model.addAttribute(AttributeConstant.MAIN_PAGE, "admin/article/listArticle.vm");
return "admin/index";
}
//通过 ID 显示更新文章页面
@RequestMapping(value = "update/{articleId:[0-9]+}", method = RequestMethod.GET)
public String upDateArticle(ModelMap model, HttpSession session, @PathVariable("articleId") Integer articleId) {
model.addAttribute(AttributeConstant.USER, (UserDto) session.getAttribute(AttributeConstant.CURRENT_USER));
ArticleDto articleDto = articleService.getArticle(articleId);
if (StringUtil.isNotEmpty(articleDto.getTitle())) {
model.addAttribute(AttributeConstant.ARTICLE, articleDto);
model.addAttribute(AttributeConstant.MAIN_PAGE, "admin/article/editorArticle.vm");
model.addAttribute(AttributeConstant.CATEGORIES, categoryService.getCategories());
} else {
Pager pager = new Pager(1, 10, articleService.count());
List<ArticleDto> articles = articleService.getPageArticles(pager);
model.addAttribute(AttributeConstant.ERROR, "找不到该文章!");
model.addAttribute(AttributeConstant.MAIN_PAGE, "admin/article/listArticle.vm");
model.addAttribute(AttributeConstant.PAGER, pager);
model.addAttribute(AttributeConstant.ARTICLES, articles);
}
return "admin/index";
}
//通过ID更新文章 操作
@RequestMapping(value = "update/{articleId:[0-9]+}", method = RequestMethod.POST)
public String upDateArticleAction(Article article, @PathVariable("articleId") Integer articleId, ModelMap model, HttpSession session) {
String path;
if (StringUtil.isNotEmpty(article.getTitle()) && StringUtil.isNotEmpty(article.getMarkDown()) && StringUtil.isNotEmpty(article.getRemark())) {
article.setClicks(articleService.getArticle(articleId).getClicks());
article.setPubDate(articleService.getArticle(articleId).getPubDate());
articleService.updateArticle(article);
path = "redirect:/manage/article";
} else {
model.addAttribute(AttributeConstant.ERROR, "有未填选项,请核对后重新发布文章!");
model.addAttribute(AttributeConstant.MAIN_PAGE, "admin/article/editorArticle.vm");
model.addAttribute(AttributeConstant.USER, (UserDto) session.getAttribute(AttributeConstant.CURRENT_USER));
model.addAttribute(AttributeConstant.ARTICLE, articleService.getArticle(articleId));
model.addAttribute(AttributeConstant.CATEGORIES, categoryService.getCategories());
path = "admin/index";
}
return path;
}
//通过ID 删除文章
@RequestMapping("delete/{articleId:[0-9]+}")
public String deleteArticle(@PathVariable("articleId") Integer articleId, @RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage) {
String path = "redirect:/manage/article";
articleService.deleteArticle(articleId);
if (currentPage != 1) {
path = "redirect:/manage/article/?currentPage=" + currentPage;
}
return path;
}
//搜索 文章
@RequestMapping("search")
public String search(String content, ModelMap model, HttpSession session) {
Article article = new Article();
article.setTitle(content);
model.addAttribute(AttributeConstant.USER, (UserDto) session.getAttribute(AttributeConstant.CURRENT_USER));
List<ArticleDto> articleDtos = articleService.searchArticles(article);
Pager pager = new Pager(1, 10, articleService.searchArticles(article).size());
if (articleDtos.size() > 0) {
model.addAttribute(AttributeConstant.ARTICLES, articleDtos);
} else {
model.addAttribute(AttributeConstant.ARTICLES, null);
}
model.addAttribute(AttributeConstant.PAGER, pager);
model.addAttribute(AttributeConstant.MAIN_PAGE, "admin/article/listArticle.vm");
return "admin/index";
}
}
View Code

 

3.ManageCategoryController

分类管理模块

@Controller
@RequestMapping("/manage/category")
public class ManageCategoryController {
@Autowired
private CategoryService categoryService;
//显示分类编辑页面
@RequestMapping(method = RequestMethod.GET)
public String showCategoriesPage(ModelMap model, HttpSession session) {
model.addAttribute(AttributeConstant.USER, (UserDto) session.getAttribute(AttributeConstant.CURRENT_USER));
model.addAttribute(AttributeConstant.CATEGORIES, categoryService.getCategories());
model.addAttribute(AttributeConstant.MAIN_PAGE, "admin/category/editor.vm");
return "admin/index";
}
//创建分类
@RequestMapping(value = "/create", method = RequestMethod.POST)
public String createAction(String categoryName, ModelMap model, HttpSession session) {
model.addAttribute(AttributeConstant.USER, (UserDto) session.getAttribute(AttributeConstant.CURRENT_USER));
model.addAttribute(AttributeConstant.MAIN_PAGE, "admin/category/editor.vm");
if (StringUtil.isNotEmpty(categoryName)) {
Category category = new Category();
category.setName(categoryName);
categoryService.saveCategory(category);
} else {
model.addAttribute(AttributeConstant.ERROR, "分类名称未填写!");
}
model.addAttribute(AttributeConstant.CATEGORIES, categoryService.getCategories());
return "admin/index";
}
//显示 更新分类页面
@RequestMapping(value = "/update/{categoryId:[0-9]+}", method = RequestMethod.GET)
public String upDatePage(@PathVariable("categoryId") Integer categoryId, ModelMap model, HttpSession session) {
model.addAttribute(AttributeConstant.USER, (UserDto) session.getAttribute(AttributeConstant.CURRENT_USER));
model.addAttribute(AttributeConstant.MAIN_PAGE, "admin/category/editor.vm");
Category category = categoryService.getCategory(categoryId);
if (StringUtil.isNotEmpty(category.getName())) {
model.addAttribute(AttributeConstant.CATEGORY, categoryService.getCategory(categoryId));
}else{
model.addAttribute(AttributeConstant.ERROR,"找不到该分类!");
}
model.addAttribute(AttributeConstant.CATEGORIES, categoryService.getCategories());
return "admin/index";
}
//更新分类
@RequestMapping(value = "/update",method = RequestMethod.POST)
public String upDateAction(String categoryName,Integer categoryId,ModelMap model, HttpSession session){
model.addAttribute(AttributeConstant.USER, (UserDto) session.getAttribute(AttributeConstant.CURRENT_USER));
model.addAttribute(AttributeConstant.MAIN_PAGE, "admin/category/editor.vm");
Category category = new Category();
category.setName(categoryName);
category.setId(categoryId);
categoryService.updateCategory(category);
model.addAttribute(AttributeConstant.CATEGORIES, categoryService.getCategories());
model.addAttribute(AttributeConstant.RETURN_INFO,"修改成功!");
model.addAttribute(AttributeConstant.CATEGORY,category);
return "admin/index";
}
//删除分类
@RequestMapping(value = "/delete/{categoryId:[0-9]+}")
public String deleteAction(@PathVariable("categoryId")Integer categoryId,ModelMap model,HttpSession session){
model.addAttribute(AttributeConstant.USER, (UserDto) session.getAttribute(AttributeConstant.CURRENT_USER));
model.addAttribute(AttributeConstant.MAIN_PAGE, "admin/category/editor.vm");
Category category = categoryService.getCategory(categoryId);
if(StringUtil.isNotEmpty(category.getName())){
categoryService.deleteCategory(categoryId);
model.addAttribute(AttributeConstant.RETURN_INFO,"删除成功!");
}else{
model.addAttribute(AttributeConstant.ERROR,"找不到该分类");
}
model.addAttribute(AttributeConstant.CATEGORIES,categoryService.getCategories());
return "admin/index";
}
}
View Code

 

后台管理的页面借用了AdminLTE模板,就不多介绍了。

以上就基本完成了个人博客系统的所有功能。

转载于:https://www.cnblogs.com/buwenyuwu/p/7147372.html

最后

以上就是飞快鲜花为你收集整理的项目:个人博客系统 Part3 Controller层编写的全部内容,希望文章能够帮你解决项目:个人博客系统 Part3 Controller层编写所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(27)

评论列表共有 0 条评论

立即
投稿
返回
顶部