软件创新实验室网站设计
1.前后台(必做)
前台主要做展示交互
后台可以对完整进行管理设置
注:以下功能并未注明哪些事前台,哪些是后台,这个需要大家根据自己的经验合理分配![21
前端界面展示
后端页面展示
2.权限管理(必做)
网站权限设计中,分为普通用户,实验室成员,系统管理员三个角色。
普通用户:可以进入网站前台进行浏览,包括浏览成员博文,成员简介,实验室发展历史等,也可以发表评论,参与留言
实验室成员:除了以上权限外,实验室成员可以参与实验室内部的讨论,查看实验室内部的资源,登录后台发布博文等等
系统管理员:除了以上权限外,系统管理员可以对网站进行管理,如发布公告,管理用户等等
管理员密码和账号都为admin,且唯一
数据库设计
只做user和member(字段status值1代表实验室成员,2代表普通用户)
6.成员信息管理(必做)
后台可以对用户进行管理,比如授权
后台管理
留言管理
1.编写UserService
public interface UserService {
List<User> findAll();
User findByName(String name);
User findById(int id);
boolean insertUser(User user);
boolean updateUser(User user);
}
2.编写UserServiceImpl
@Service
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
@Override
public List<User> findAll() {
return userDao.findAll();
}
@Override
public User findByName(String name) {
return userDao.findByName(name);
}
@Override
public boolean insertUser(User user) {
return userDao.insertUser(user);
}
@Override
public boolean updateUser(User user) {
return userDao.updateUser(user);
}
@Override
public User findById(int id) {
return userDao.findById(id);
}
}
3.编写UserController
@Controller
public class UserController {
@Resource
private UserService userService;
@Resource
private MessageService messageService;
@Resource
private ArticleService articleService;
@Resource
private NoticeService noticeService;
@Resource
private HttpServletRequest request;
@RequestMapping(value = "/userRegistered",method = RequestMethod.POST)
@ResponseBody
private JsonResult userRegistered(){
String name=request.getParameter("name");
String password = request.getParameter("password");
if(userService.findByName(name)!=null){
return JsonResult.fail("注册失败,该用户名已被注册!请更换用户名重试!");
}
else{
User user=new User();
user.setName(name);
user.setPassword(password);
if(userService.insertUser(user)){
return JsonResult.ok().set("returnUrl", "/login");
}
}
return JsonResult.fail("注册失败,数据插入异常!");
}
@RequestMapping(value = "userLogin",method = RequestMethod.POST)
@ResponseBody
private JsonResult userLogin(){
String name=request.getParameter("name");
String password = request.getParameter("password");
User user=userService.findByName(name);
if(user!=null){
if(name.equals(user.getName())&&password.equals(user.getPassword())){
int id=user.getId();
return JsonResult.ok().set("userid", id);
}
return JsonResult.fail("登录失败,用户名与密码不匹配!");
}
return JsonResult.fail("登录失败,不存在该账号!");
}
@RequestMapping(value = "/reloadUserInfo",method = RequestMethod.POST)
@ResponseBody
private JsonResult reloadUserInfo(){
int id=0;
try {
id = Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
e.printStackTrace();
}
User user=userService.findById(id);
return JsonResult.ok().set("userInfo",user);
}
@RequestMapping(value = "updateUserInfo",method = RequestMethod.POST)
@ResponseBody
private JsonResult updateUserInfo(){
int id=0;
try {
id = Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
e.printStackTrace();
}
String hobby=request.getParameter("hobby");
User user=userService.findById(id);
user.setHobby(hobby);
if(userService.updateUser(user)){
return JsonResult.ok();
}
return JsonResult.fail("修改资料失败!数据修改错误!");
}
@RequestMapping("/userList")
@ResponseBody
private PageJson<User> useList(){
List<User> userList=userService.findAll();
PageJson<User> pageJson=new PageJson<>();
pageJson.setCode(0);
pageJson.setCount(userList.size());
pageJson.setData(userList);
pageJson.setMsg("OK");
return pageJson;
}
@RequestMapping(value = "/resetPassword",method = RequestMethod.POST)
@ResponseBody
private JsonResult resetPassword(){
int id=0;
try {
id = Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
e.printStackTrace();
}
User user=userService.findById(id);
user.setPassword("123456");
if(userService.updateUser(user)){
return JsonResult.ok();
}
return JsonResult.fail("修改用户密码失败!数据修改失败!");
}
@RequestMapping("/dataReload")
@ResponseBody
private JsonResult dataReload(){
int articleNum=articleService.findAllArticle().size();
int messageNum=messageService.findAll().size();
int userNum=userService.findAll().size();
int noticeNum=noticeService.findAll().size();
Map<String,Object> map=new HashMap<>();
map.put("articleNum",articleNum);
map.put("messageNum",messageNum);
map.put("userNum",userNum);
map.put("noticeNum",noticeNum);
return JsonResult.ok().set("data",map);
}
}
3.评论设计(必做)
可以展示多级评论(至少两级)
评论需要展示评论内容,评论时间,评论用户
用户可以对评论进行回复
注:评论功能可以参考各个网站/app的设计,要求和他们差不多
先构建一个树
package cn.zi10ng.blog.util;
import cn.zi10ng.blog.domain.CommentInfo;
import cn.zi10ng.blog.domain.Node;
import java.util.ArrayList;
import java.util.List;
public class TreeUtils {
/**
* 把评论信息的集合转化为一个树
*/
public Node buildTree(List<CommentInfo> commentInfo, long id){
Node tree = new Node();
List<Node> children = new ArrayList<>();
List<Node> nodeList = new ArrayList<>();
for (CommentInfo info : commentInfo) {
children.add(buildNode(info));
}
tree.setId(id);
tree.setChildren(children);
for (Node child : children) {
Node node = findNode(children, child.getParentId());
List<Node> nodes = new ArrayList<>();
if (node != null) {
if (node.getChildren() != null) {
nodes = node.getChildren();
nodes.add(child);
node.setChildren(nodes);
}else {
nodes.add(child);
node.setChildren(nodes);
}
nodeList.add(child);
}
}
for (Node node : nodeList) {
children.remove(node);
}
return tree;
}
private Node findNode(List<Node> nodes, long id){
for (Node node : nodes) {
if (node.getId() == id) {
return node;
}
}
return null;
}
private Node buildNode(CommentInfo info){
Node node = new Node();
node.setId(info.getId());
node.setParentId(info.getParentId());
node.setObject(info);
node.setChildren(null);
return node;
}
}
前端用vue组件套用模板调用
组件:
<template>
<div class="multistage">
<div v-if="children != null" class="comments">
<div class="comment" v-for="subArticleComment in children" :key="subArticleComment.object.id">
<a class="avatar">
<img :src="imgSrc" alt="头像">
</a>
<div class="content">
<a class="author">{{subArticleComment.object.name}}</a>
<div class="metadata">
<span class="date">{{subArticleComment.object.createByStr}}</span>
</div>
<div class="text">{{subArticleComment.object.content}} </div>
<div class="actions">
<a class="reply">回复</a>
</div>
</div>
<multistage :children="subArticleComment.children"/>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'multistage',
props: ['children'],
data () {
return {
imgSrc: 'https://picsum.photos/id/234/100/100'
}
}
}
</script>
<style scoped>
</style>
模板:
<div class="comment" v-for="articleComment in articleCommentTree.children" :key="articleComment.object.id">
<a class="avatar">
<img :src="imgSrc" alt="头像">
</a>
<div class="content">
<a class="author">{{articleComment.object.name}}</a>
<div class="metadata">
<span class="date">{{articleComment.object.createByStr}}</span>
</div>
<div class="text">{{articleComment.object.content}} </div>
<div class="actions">
<a class="reply">回复</a>
</div>
</div>
<multistage :children="articleComment.children"/>
</div>
测试
数据库
4.用户注册(必做)
用户注册时填写相关个人信息即可注册(刚注册时是普通用户)
同时需要绑定登录账号,比如邮箱、手机号等作为找回密码的依据(这里推荐邮箱注册,因为比较简单)
注意要进行验证操作(发送验证码,如果是邮箱就发邮件,手机号就发短信)
Springboot整合邮件发送的原理和实现
开发前准备
登录 QQ 邮箱,点击设置->账户,开启IMAP/SMTP服务,并生成授权码。
用户要在Internet上提供电子邮件功能,必须有专门的电子邮件服务器。这些邮件服务器就类似于现实生活中的邮局,它主要负责接收用户投递过来的邮件,并把邮件投递到邮件接收者的电子邮箱中。
邮件服务器就好像是互联网世界的邮局。按照功能划分,邮件服务器可以划分为两种类型:
SMTP邮件服务器:用户替用户发送邮件和接收外面发送给本地用户的邮件。 POP3/IMAP邮件服务器:用户帮助用户读取SMTP邮件服务器接收进来的邮件。
什么是JavaMailSender和JavaMailSenderImpl? JavaMailSender和JavaMailSenderImpl 是Spring官方提供的集成邮件服务的接口和实现类,以简单高效的设计著称,目前是Java后端发送邮件和集成邮件服务的主流工具。
如何通过JavaMailSenderImpl发送邮件? 非常简单,直接在业务类注入JavaMailSenderImpl并调用send方法发送邮件。其中简单邮件可以通过SimpleMailMessage来发送邮件,而复杂的邮件(例如添加附件)可以借助MimeMessageHelper来构建MimeMessage发送邮件。
进行用户注册同时发送一封激活邮件,邮件里面包含一条激活链接,点击链接把使用UUIDUtils生产发送给用户的邮箱验证码提交进行验证,从而修改用户的激活状态,最后返回登陆页面进行验证登录
Spring Boot 集成邮件发送主要分为以下三步:
-
加入依赖
pom.xml依赖spring-boot-starter-mail模块:
<!--javax.mail 邮件发送--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
2.配置邮件
在配置文件 application.properties
中配置邮件的相关参数,其中指定了邮件的协议、端口以及邮件账户和授权码等。具体内容如下:
#邮件配置
#SMTP服务器地址
spring.mail.host=smtp.qq.com
#登陆账号
spring.mail.username=2590742958@qq.com
#注意这里不是邮箱密码,而是SMTP授权密码
spring.mail.password=lvlpxkujplqbdh
spring.mail.default-encoding=UTF-8
#开启加密验证
spring.mail.properties.mail.smtp.ssl.enable=true
#以下项不用改动
spring.mail.properties.mail.smtp.starttls.enable: true
spring.mail.roperties.mail.smtp.starttls.required: true
3.编写MailService
public interface MailService {
/**
* 发送带附件的邮件
* @param to 收件人
* @param subject 主题
* @param content 内容
* @param filePath 附件路径
*/
void sendAttachmentMail(String to, String subject, String content, String filePath);
4.编写MainServiceImpl
public class MailServiceImpl implements MailService {
private final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);
//使用@Value注入application.properties中指定的用户名
@Value("${spring.mail.username}")
private String from;
@Autowired
//用于发送文件
private JavaMailSender mailSender;
@Override
public void sendAttachmentMail(String to, String subject, String content, String filePath) {
logger.info("发送带附件邮件开始:{},{},{},{}", to, subject, content, filePath);
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper;
try {
helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = file.getFilename();
helper.addAttachment(fileName, file);//添加附件,可多次调用该方法添加多个附件
mailSender.send(message);
logger.info("发送带附件邮件成功");
} catch (MessagingException e) {
logger.error("发送带附件邮件失败", e);
}
5.编写MainController
@Controller
public class MailContorller {
@Autowired
private MailService mailService;
@Autowired
private TemplateEngine templateEngine;
@Resource
private UserService userService;
//这一步是获取application.properties中设置的发件人邮箱地址
@Value("${spring.mail.username}")
private String Email;
@RequestMapping("/sendTemplate")
/** 指定模板发送邮件 */
public String sendTemplate(@RequestParam("Email") String Email, Model model) {
//具体的业务
User usermail= userService.retrieve(Email);
System.out.println(usermail);
if (usermail !=null){
//向Thymeleaf模板传值,并解析成字符串
//通过Context构造模版中变量需要的值
Context context = new Context();
context.setVariable("id", "001");
String emailContent = templateEngine.process("emailTemplate", context);
mailService.sendHtmlMail(Email,"密码找回验证", emailContent);
return "Login";
}
else if(StringUtils.isEmpty(Email)){
model.addAttribute("yuoxiang","邮箱信息不能为空");
return "Login";
}
else {
model.addAttribute("yuoxiang","邮箱错误或者与绑定账号不一致");
return "Login";
}
}
5.测试
加入用户注册测试
1.封装实体类
使用注解的方式快速创建User实体类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int UserID;
//账号
private String UserNumber;
//密码
private String Password;
//邮箱地址
private String Email;
/**
* 状态:0代表未激活,1代表激活
*/
private Integer status;
/**
* 利用UUID生成一段数字,发动到用户邮箱,当用户点击链接时
* 在做一个校验如果用户传来的code跟我们发生的code一致,更改状态为“1”来激活用户
*/
private String code;
}
2.创建生成UUID的工具类
UUID产生的目的是让分布式系统中的所有元素,都能有唯一的辨识信息,而不需要通过中央控制端来做辨识信息的指定。如此一来,每个人都可以创建不与其它人冲突的UUID。在这样的情况下,就不需考虑数据库创建时的名称重复问题。UUID 来作为数据库中字段是非常不错的选择,保证每次生成的UUID 是唯一的
import java.util.UUID;
/**
* @Description:使用UUIDUtils生产发送给用户的邮箱验证码
*/
public class UUIDUtils {
public static String getUUID(){
return UUID.randomUUID().toString().replace("-","");
}
}
3.创建UserDao接口
package com.kuang.Dao;
import com.kuang.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
//@Mapper : 表示本类是一个 MyBatis 的 Mapper
@Mapper
@Repository
public interface UsersDao {
//登录
public User login(@Param("UserNumber") String UserNumber, @Param("Password") String Password);
//找回密码
public User retrieve(@Param("Email") String Email);
/**
* 用户注册
* @param user
*/
void register(User user);
/**
* 根据激活码查询用户,之后再进行修改用户状态
* @param code
* @return
*/
User checkCode(String code);
/**
* 激活账户,修改用户状态为"1"
* @param user
*/
void updateUserStatus(User user);
}
4.创建映射文件UserMapper.xml
注意在mybatis中映射文件中的namespace是用于绑定Dao接口的,即面向接口编程,dao接口的方法对应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="com.kuang.Dao.UsersDao">
<resultMap type="com.kuang.pojo.User" id="User">
<id column="UserID" property="UserID"/>
<result column="UserID" property="UserID"/>
<result column="UserNumber" property="UserNumber"/>
<result column="Password" property="Password"/>
<result column="Email" property="Email"/>
<result column="code" property="code"/>
<result column="status" property="status"/>
</resultMap>
<select id="login" resultMap="User">
select * from user where UserNumber=#{UserNumber} and Password=#{Password} and status=1
</select>
<select id="retrieve" resultMap="User">
select * from user where Email=#{Email}
</select>
<!--注册用户-->
<insert id="register" parameterType="User" >
insert into user ( UserNumber, Password,Email,status,code)
values (#{UserNumber,jdbcType=VARCHAR}, #{Password,jdbcType=VARCHAR}, #{Email,jdbcType=VARCHAR},
#{status,jdbcType=INTEGER},#{code,jdbcType=INTEGER})
</insert>
<!--根据激活码code查询用户-->
<select id="checkCode" parameterType="String" resultType="User">
select * from user where code = #{code}
</select>
<!--激活账户,修改用户状态-->
<update id="updateUserStatus" parameterType="User">
update user set status=1,code=null where UserID=#{UserID}
</update>
</mapper>
5.创建UserService接口
package com.kuang.service;
import com.kuang.pojo.User;
public interface UserService {
//用户登录
public User login(String userName, String password);
//找回密码
public User retrieve(String email);
/**
* 用户注册
* @param user
*/
void register(User user);
/**
* 根据激活码code查询用户,之后再进行修改状态
* @param code
* @return
*/
User checkCode(String code);
/**
* 激活账户,修改用户状态
* @param user
*/
void updateUserStatus(User user);
}
6.创建UserServiceImpl实现类
package com.kuang.service.impl;
import com.kuang.Dao.UsersDao;
import com.kuang.pojo.User;
import com.kuang.service.MailService;
import com.kuang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UsersDao usersDao;
@Autowired
private MailService mailService;
/**
* 登录验证
*/
@Override
public User login(String userName, String password){
return usersDao.login(userName,password);
}
/**
* 忘记密码,邮件发送找回
*/
@Override
public User retrieve(String email){
return usersDao.retrieve(email);
}
/**
* 用户注册,同时发送一封激活邮件
* @param user
*/
@Override
public void register(User user) {
usersDao.register(user);
String code = user.getCode();
System.out.println("code:"+code);
String subject = "来自智能化驾校管理系统的激活邮件";
///checkCode?code=xxx即是我们点击邮件链接之后进行更改状态的
String context = "<h1>此邮件为官方激活邮件!请点击下面链接完成激活操作!</h1> <a href=\"http://localhost:8080/selectCode?code="+code+"\">激活请点击:"+code+"</a> ";
//发送激活邮件
mailService.sendHtmlMail (user.getEmail(),subject,context);
}
/**
* 根据激活码code进行查询用户,之后再进行修改状态
* @param code
* @return
*/
@Override
public User checkCode(String code) {
return usersDao.checkCode(code);
}
/**
* 激活账户,修改用户状态
* @param user
*/
@Override
public void updateUserStatus(User user) {
usersDao.updateUserStatus(user);
}
}
7.定义核心业务接口UserController控制类
package com.kuang.contorller;
import com.kuang.common.UUIDUtils;
import com.kuang.pojo.User;
import com.kuang.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
@Controller
public class LoginContorller {
@Resource
private UserService userService;
@RequestMapping("/main")
public String login(@RequestParam("UserNumber") String UserNumber,
@RequestParam("Password") String Password, Model model, HttpSession session) {
//具体的业务
User user= userService.login(UserNumber,Password);
if (user!=null){
session.setAttribute("loginUser",UserNumber);
return "redirect:/Main";
}else if(StringUtils.isEmpty(UserNumber) && StringUtils.isEmpty(Password)){
model.addAttribute("msg","账号或者密码不能为空");
return "Login";
}
else {
model.addAttribute("msg","账号或者密码错误");
return "Login";
}
}
/**
* 注册
* @param user
* @return
*/
@RequestMapping(value = "/registerUser")
public String register(User user){
user.setStatus(0);
String code = UUIDUtils.getUUID()+ UUIDUtils.getUUID();
user.setCode(code);
userService.register(user);
return "login";
}
/**
*校验邮箱中的code激活账户
* 首先根据激活码code查询用户,之后再把状态修改为"1"
*/
@RequestMapping(value = "/selectCode")
public String checkCode(String code){
User user = userService.checkCode(code);
System.out.println(user);
//如果用户不等于null,把用户状态修改status=1
if (user !=null){
user.setStatus(1);
//把code验证码清空,已经不需要了
user.setCode("");
System.out.println(user);
userService.updateUserStatus(user);
}
return "login";
}
/**
* 跳转到登录页面
* @return login
*/
@RequestMapping(value = "/loginPage")
public String login(){
return "login";
}
}
8.测试
7.博文模块(必做)
可以展示实验室实验室同学最近写的优秀博文
点击博文详情可以进行查看
博文可以进行点赞,收藏,评论等互动操作
用户可以编写博文并发布,如果未编写完成也可以保存在草稿箱内
用户可以对自己的博文进行管理(修改,删除,设置不可见等)
发表文章
博文管理
1,编写ArticleService
public interface ArticleService {
List<Article> findAllArticle();
List<Article> findByName(String name);
Article findById(int id);
boolean insertArticle(Article article);
boolean updateArticle(Article article);
boolean deleteArticle(int id);
}
2.编写ArticleServiceImpl
@Service
public class ArticleServiceImpl implements ArticleService {
@Resource
private ArticleDao articleDao;
@Override
public List<Article> findAllArticle() {
return articleDao.findAllArticle();
}
@Override
public List<Article> findByName(String name) {
return articleDao.findByName(name);
}
@Override
public Article findById(int id) {
return articleDao.findById(id);
}
@Override
public boolean insertArticle(Article article) {
return articleDao.insertArticle(article);
}
@Override
public boolean updateArticle(Article article) {
return articleDao.updateArticle(article);
}
@Override
public boolean deleteArticle(int id) {
return articleDao.deleteArticle(id);
}
}
3.编写ArticleController
@Controller
public class ArticleController {
@Resource
private ArticleService articleService;
@Resource
private HttpServletRequest request;
@RequestMapping(value = "/reloadArticle",method = RequestMethod.POST)
@ResponseBody
private JsonResult reloadArticle(){
String name=request.getParameter("name");
List<Article> articleList=articleService.findByName(name);
return JsonResult.ok().set("articleData",articleList);
}
@RequestMapping(value = "/publishArticle",method = RequestMethod.POST)
@ResponseBody
private JsonResult publishArticle(){
String name=request.getParameter("name");
String title=request.getParameter("title");
String articleInfo=request.getParameter("articleInfo");
String time=request.getParameter("time");
String photoUrl=request.getParameter("photoUrl");
//System.out.println(photoUrl);
Article article=new Article();
article.setName(name);
article.setTitle(title);
article.setArticleInfo(articleInfo);
article.setTime(time);
article.setPhotoUrl(photoUrl);
if(articleService.insertArticle(article)){
return JsonResult.ok();
}
return JsonResult.fail("文章发表失败!请重试!");
}
@RequestMapping(value = "/articleInfo",method = RequestMethod.POST)
@ResponseBody
private JsonResult articleInfo(){
int id=0;
try {
id = Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
e.printStackTrace();
}
Article article=articleService.findById(id);
List<Article> articleList=new ArrayList<>();
articleList.add(article);
return JsonResult.ok("articleInfo",article);
}
@RequestMapping(value = "/updateArticle",method = RequestMethod.POST)
@ResponseBody
private JsonResult updateArticle(){
int id=0;
try {
id = Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
e.printStackTrace();
}
String title=request.getParameter("title");
String articleInfo=request.getParameter("articleInfo");
String time=request.getParameter("time");
//System.out.println("title:"+title+"articleInfo:"+articleInfo+"time:"+time+"id:"+id);
Article article=articleService.findById(id);
article.setTitle(title);
article.setArticleInfo(articleInfo);
article.setTime(time);
if(articleService.updateArticle(article)){
return JsonResult.ok();
}
return JsonResult.fail("文章修改失败!请重试!");
}
@RequestMapping(value = "/deleteArticle",method = RequestMethod.POST)
@ResponseBody
private JsonResult deleteArticle(){
int id=0;
try {
id = Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
e.printStackTrace();
}
if(articleService.deleteArticle(id)){
return JsonResult.ok().set("msg","文章修改成功");
}
return JsonResult.fail("文章删除失败!请重试!");
}
@RequestMapping("/articleList")
@ResponseBody
private PageJson<Article> articleList(){
PageJson<Article> pageJson=new PageJson<>();
List<Article> articleList=articleService.findAllArticle();
pageJson.setCode(0);
pageJson.setCount(articleList.size());
pageJson.setMsg("OK");
pageJson.setData(articleList);
return pageJson;
}
//图片上传
@ResponseBody
@RequestMapping("uploadPhoto")
public Map upload(MultipartFile file, HttpServletRequest request){
String prefix="";
String dateStr="";
String photoUrl="";
//保存上传
OutputStream out = null;
InputStream fileInput=null;
try{
if(file!=null){
String originalName = file.getOriginalFilename();
prefix=originalName.substring(originalName.lastIndexOf(".")+1);
Date date = new Date();
String uuid = UUID.randomUUID()+"";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
dateStr = simpleDateFormat.format(date);
photoUrl=dateStr+uuid+"."+prefix;
String filepath = "D:\\IDEA_PROJECT\\finalproject\\src\\main\\resources\\static\\image\\"+photoUrl;
File files=new File(filepath);
//打印查看上传路径
//System.out.println(filepath);
if(!files.getParentFile().exists()){
files.getParentFile().mkdirs();
}
file.transferTo(files);
Map<String,Object> map2=new HashMap<>();
Map<String,Object> map=new HashMap<>();
map.put("code",0);
map.put("msg","");
map.put("data",map2);
map2.put("src",photoUrl);
return map;
}
}catch (Exception e){
}finally{
try {
if(out!=null){
out.close();
}
if(fileInput!=null){
fileInput.close();
}
} catch (IOException e) {
}
}
Map<String,Object> map=new HashMap<>();
map.put("code",1);
map.put("msg","");
return map;
}
/**
* 文件名后缀前添加一个时间戳
*/
private String getFileName(String fileName) {
int index = fileName.lastIndexOf(".");
final SimpleDateFormat sDateFormate = new SimpleDateFormat("yyyymmddHHmmss"); //设置时间格式
String nowTimeStr = sDateFormate.format(new Date()); // 当前时间
fileName = fileName.substring(0, index) + "_" + nowTimeStr + fileName.substring(index);
return fileName;
}
/**
* 获取当前系统路径
*/
private String getUploadPath() {
File path = null;
try {
path = new File(ResourceUtils.getURL("classpath:").getPath());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (!path.exists()) path = new File("");
File upload = new File(path.getAbsolutePath(), "static/image/");
if (!upload.exists()) upload.mkdirs();
return upload.getAbsolutePath();
}
}
8.公告模块(必做)
网站首页应该有公告显示
管理员可以在后台发布公告
公告应该可以有公告内容,发布人,发布时间等
添加新公告
公告展示
1.编写NoticeService
public interface NoticeService {
List<Notice> findAll();
Notice findById(int id);
boolean insertNotice(Notice notice);
boolean updateNotice(Notice notice);
boolean deleteNotice(int id);
}
2.编写NoticeServiceImpl
public class NoticeServiceImpl implements NoticeService {
@Resource
private NoticeDao noticeDao;
@Override
public List<Notice> findAll() {
return noticeDao.findAll();
}
@Override
public boolean insertNotice(Notice notice) {
return noticeDao.insertNotice(notice);
}
@Override
public boolean updateNotice(Notice notice) {
return noticeDao.updateNotice(notice);
}
@Override
public boolean deleteNotice(int id) {
return noticeDao.deleteNotice(id);
}
@Override
public Notice findById(int id) {
return noticeDao.findById(id);
}
}
3.编写NoticeController
public class NoticeController {
@Resource
private NoticeService noticeService;
@Resource
private HttpServletRequest request;
@RequestMapping("/reloadNotice")
@ResponseBody
private JsonResult reloadNotice(){
List<Notice> noticeList=noticeService.findAll();
return JsonResult.ok().set("noticeData", noticeList);
}
@RequestMapping("/noticeList")
@ResponseBody
private PageJson<Notice> noticeList(){
List<Notice> noticeList=noticeService.findAll();
PageJson<Notice> pageJson=new PageJson<>();
pageJson.setData(noticeList);
pageJson.setMsg("OK");
pageJson.setCount(noticeList.size());
pageJson.setCode(0);
return pageJson;
}
@RequestMapping(value = "/deleteNotice",method = RequestMethod.POST)
@ResponseBody
private JsonResult deleteNotice(){
int id=0;
try {
id = Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
e.printStackTrace();
}
System.out.println(id);
if(noticeService.deleteNotice(id)){
return JsonResult.ok();
}
return JsonResult.fail("删除公告信息失败!数据删除失败!");
}
@RequestMapping(value = "/updateNotice",method = RequestMethod.POST)
@ResponseBody
private JsonResult updateNotice(){
int id=0;
try {
id = Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
e.printStackTrace();
}
String value=request.getParameter("value");
String field=request.getParameter("field");
String time=request.getParameter("time");
Notice notice=noticeService.findById(id);
if(field.equals("title")){
notice.setTitle(value);
}
else {
notice.setNoticeInfo(value);
}
if(noticeService.updateNotice(notice)){
return JsonResult.ok();
}
return JsonResult.fail("修改公告信息失败!数据修改失败!");
}
@RequestMapping(value = "/addNotice",method = RequestMethod.POST)
@ResponseBody
private JsonResult addNotice(){
String title=request.getParameter("title");
String noticeInfo=request.getParameter("noticeInfo");
String time=request.getParameter("time");
Notice notice=new Notice();
notice.setTitle(title);
notice.setNoticeInfo(noticeInfo);
notice.setTime(time);
if(noticeService.insertNotice(notice)){
return JsonResult.ok();
}
return JsonResult.fail("添加公共信息失败!数据插入失败!");
}
}
10.个人信息模块(必做)
个人风采展示
比如个人介绍,曾任职的职位,技术方向,写的博文等等
注:这个需要自己去设计拓展合理的功能
个人信息修改
用户可以修改自己的账号信息
个人信息展示
可编辑资料(导入头像的url)
关于修改用户资料的UserController核心代码
@RequestMapping(value = "updateUserInfo",method = RequestMethod.POST)
@ResponseBody
private JsonResult updateUserInfo(){
int id=0;
try {
id = Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
e.printStackTrace();
}
String hobby=request.getParameter("hobby");
User user=userService.findById(id);
user.setHobby(hobby);
if(userService.updateUser(user)){
return JsonResult.ok();
}
return JsonResult.fail("修改资料失败!数据修改错误!");
}