Java tutorial
/* * Copyright 2014-2024 the https://github.com/xiaoxing598/itganhuo. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * This project consists of JAVA private school online learning community group Friends co-creator [QQ group 329232140]. * JAVA???[QQ329232140]; * See the list of IT dry technology sharing network [http://www.itganhuo.cn/teams]. * ????IT[http://www.itganhuo.cn/teams]; * The author does not guarantee the quality of the project and its stability, reliability, and security does not bear any responsibility. * ????????. */ package cn.itganhuo.app.web.controller; import cn.itganhuo.app.common.page.Pagination; import cn.itganhuo.app.common.pool.ConfigPool; import cn.itganhuo.app.common.pool.ConstantPool; import cn.itganhuo.app.common.utils.DateUtil; import cn.itganhuo.app.common.utils.StringUtil; import cn.itganhuo.app.entity.*; import cn.itganhuo.app.exception.InternalException; import cn.itganhuo.app.service.*; import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authz.annotation.RequiresAuthentication; import org.apache.shiro.crypto.hash.SimpleHash; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.Model; 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.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * <h2></h2> * <dl> * <dt>??</dt> * <dd>??</dd> * <dt></dt> * <dd>?????????</dd> * </dl> * * @author -?-? * @version 0.0.2-SNAPSHOT */ @Controller @RequestMapping("/user") public class UserController { private static final Logger log = LogManager.getLogger(UserController.class.getName()); @Autowired private UserService userService; @Autowired private MailService mailService; @Autowired private ArticleService articleService; @Autowired private CommentService commentService; @Autowired private TemplateService templateService; @Autowired private LabelService labelService; /** * ? * * @return ? * @version 0.0.1-SNAPSHOT * @author -? */ @RequestMapping(value = "/signin", method = RequestMethod.GET) public String refurlSignin() { Subject current_user = SecurityUtils.getSubject(); current_user.logout(); return "user/signin"; } /** * ? * * @return ? * @version 0.0.1-SNAPSHOT * @author -? */ @RequestMapping(value = "/register", method = RequestMethod.GET) public String refurlRegister() { return "user/register"; } /** * <h2>?</h2> * <dl> * <dt>??</dt> * <dd> * <ol> * <li>?????</li> * <li>????</li> * <li>??????????</li> * </ol> * </dd> * <dt></dt> * <dd>??????</dd> * </dl> * * @param user ? * @param request HTTP * @return ??? * @version 0.0.1-SNAPSHOT * @author -?-? */ @Transactional @RequestMapping(value = "/register", method = RequestMethod.POST) public @ResponseBody RespMsg register(User user, @RequestParam String securityCode, HttpServletRequest request, HttpServletResponse response) { RespMsg respMsg = new RespMsg(); //???shiro????? String captcha = (String) request.getSession() .getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); if (captcha == null || !captcha.equalsIgnoreCase(securityCode)) { respMsg.setMessage(ConfigPool.getString("respMsg.common.SecurityCodeError")); respMsg.setStatus("1005"); return respMsg; } else { userService.userRegister(user, request, response); respMsg.setAppendInfo(user.getAccount()); } return respMsg; } /** * shiro? * * @param request * @return ?? * @version 0.0.1-SNAPSHOT * @author -? */ @RequestMapping(value = "/signin", method = RequestMethod.POST) @ResponseBody public RespMsg signin(User user, @RequestParam String securityCode, HttpServletRequest request) { RespMsg respMsg = new RespMsg(); //???shiro?? String captcha = (String) request.getSession() .getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); if (captcha != null && captcha.equalsIgnoreCase(securityCode)) { respMsg = userService.login(user, request); } else { respMsg.setMessage(ConfigPool.getString("respMsg.common.SecurityCodeError")); respMsg.setStatus("1005"); } return respMsg; } /** * QQ? * * @return ?? * @version 0.0.1-SNAPSHOT * @author -? */ @RequestMapping(value = "/qqSignin", method = RequestMethod.POST) @ResponseBody public RespMsg qqSignin(User user, @RequestParam String securityCode, @RequestParam int type, @RequestParam String openId, @RequestParam String accessToken, HttpServletRequest request, HttpServletResponse response) { RespMsg respMsg = new RespMsg(); user.setOpenid(openId); user.setPassword(openId); user.setAccessToken(accessToken); if (2 == type) { //???shiro?? String captcha = (String) request.getSession() .getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); if (captcha == null && !captcha.equalsIgnoreCase(securityCode)) { respMsg.setMessage(ConfigPool.getString("respMsg.common.SecurityCodeError")); respMsg.setStatus("1005"); return respMsg; } } respMsg = userService.qqSignin(type, user, request, response); if ("0000".equals(respMsg.getStatus())) { User loginUser = new User(); loginUser.setAccount(user.getAccount()); loginUser.setPassword(user.getOpenid()); respMsg.setAppendInfo(user.getAccount()); respMsg = userService.login(loginUser, request); } return respMsg; } /** * ? * * @return ?? * @version 0.0.1-SNAPSHOT * @author -? */ @RequestMapping(value = "/{account}", method = RequestMethod.GET) public ModelAndView center() { ModelAndView mav = userService.center(); return mav; } /** * -? * * @return ?-? * @version 0.0.1-SNAPSHOT * @author -? */ @RequestMapping(value = "/articles", method = RequestMethod.GET) public ModelAndView refurlArticles(@RequestParam(defaultValue = "1") String now_page, HttpServletRequest request) { ModelAndView mav = new ModelAndView(); Subject current_user = SecurityUtils.getSubject(); if (current_user != null) { User user = (User) current_user.getSession().getAttribute(ConstantPool.USER_SHIRO_SESSION_ID); if (user != null) { mav.addObject("user", user); int rows = 20; Map<String, Object> param = new HashMap<String, Object>(); param.put("userId", user.getId()); param.put("offrow", (StringUtil.getInt(now_page, 1) - 1) * rows); param.put("rows", rows); List<Article> articles = articleService.getArticleByUserId(param); int total = articleService.countArticleRows(param); Pagination pagination = new Pagination(StringUtil.getInt(now_page, 1), rows, 5, total, request.getContextPath().concat("/articles"), "0000"); mav.addObject("pagination", pagination); mav.addObject("articles", articles); mav.setViewName("user/articles"); } else { mav.setViewName("user/signin"); } } else { mav.setViewName("user/signin"); } return mav; } /** * ??session??? * * @param model * @return ?? * @version 0.0.1-SNAPSHOT * @author ?-? */ @RequiresAuthentication @RequestMapping(value = "/update", method = RequestMethod.GET) public String refurlUpdate(Model model) { Subject current_user = SecurityUtils.getSubject(); User user = (User) current_user.getSession().getAttribute(ConstantPool.USER_SHIRO_SESSION_ID); if (user != null) { User u = userService.loadByAccount(user.getAccount()); model.addAttribute("user", u); return "user/update"; } return "redirect:/user/center"; } /** * ? ??? * * @param user ? * @return * @version 0.0.1-SNAPSHOT * @author ?-? */ @RequiresAuthentication @Transactional @RequestMapping(value = "/update", method = RequestMethod.POST) public String update(User user) { // ? user.setPassword(null); user.setSalt(null); user.setPostDate(null); user.setCredits(null); // ??? if (StringUtil.hasText(user.getEmail())) { user.setIsValidateEmail(0); } else { user.setIsValidateEmail(null); } if (this.userService.updateInfoByAccount(user) != 0) { return "redirect:/user/center"; } else return "redirect:/user/update"; } /** * ???? session??? * * @param model * @param session * @return ?? * @version 0.0.1-SNAPSHOT * @author ? */ @RequiresAuthentication @RequestMapping(value = "/updatePassword", method = RequestMethod.GET) public String updatePassword(Model model, HttpSession session) { User user = null; Subject current_user = SecurityUtils.getSubject(); user = (User) current_user.getSession().getAttribute(ConstantPool.USER_SHIRO_SESSION_ID); if (user == null || user.getId() <= 0) { user = userService.loadByAccount(current_user.getPrincipal().toString()); } model.addAttribute("user", user); return "user/updatePassword"; } /** * ???? * * @param request * @param response * @return 1000??? * @version 0.0.1-SNAPSHOT * @author ? */ @RequiresAuthentication @RequestMapping(value = "/checkpassword", method = RequestMethod.POST) @ResponseBody public RespMsg checkPassword(HttpServletRequest request, HttpServletResponse response) { RespMsg respMsg = new RespMsg(); String originalanpassword = request.getParameter("originalanpassword"); String account = request.getParameter("account"); if (account != null && !"".equals(account)) { User user = userService.loadByAccount(account); String algorithmName = "SHA-512"; String salt1 = user.getAccount(); String salt2 = user.getSalt(); int hashIterations = 2; SimpleHash hash = new SimpleHash(algorithmName, originalanpassword, salt1 + salt2, hashIterations); if (!hash.toBase64().equals(user.getPassword())) { respMsg.setStatus("1000"); respMsg.setMessage(ConfigPool.getString("respMsg.user.EnterNewPasswordAndOldPasswordSame")); } } return respMsg; } /** * <h2>?</h2> * <dl> * <dt>??</dt> * <dd></dd> * <dt></dt> * <dd></dd> * </dl> * * @param user ? * @return ??? * @version 0.0.1-SNAPSHOT * @author -? */ @RequiresAuthentication @Transactional @RequestMapping(value = "/updatePassword", method = RequestMethod.POST) public String updatePassword(User user) { if (this.userService.updatePasswordByAccount(user)) { Template template = templateService.loadById(1); if (template != null) { String tmp_str = template.getContent(); if (StringUtil.hasText(tmp_str)) { tmp_str = tmp_str.replaceFirst("##account##", user.getAccount()); } template.setContent(tmp_str); mailService.sendMail(user.getEmail(), template); } else throw new InternalException("Corresponding template does not exist."); } else { throw new InternalException("Password change fails."); } return "redirect:/user/center"; } /** * ??? * * @return ??? * @version 0.0.1-SNAPSHOT * @author ?-? */ @RequiresAuthentication @RequestMapping(value = "/upload", method = RequestMethod.GET) public String refurlUpload(Model model, HttpServletRequest request) { model.addAttribute("path", "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath()); return "user/upload"; } /** * ???photo * * @param request * @return * @author -? * @version 0.0.1-SNAPSHOT */ @RequiresAuthentication @RequestMapping(value = "/uploadImg", method = RequestMethod.POST) @ResponseBody public String uploadImg(HttpServletRequest request) { String msg = "fail"; User user = null; Subject current_user = SecurityUtils.getSubject(); user = (User) current_user.getSession().getAttribute(ConstantPool.USER_SHIRO_SESSION_ID); if (user == null || user.getId() <= 0) { user = userService.loadByAccount(current_user.getPrincipal().toString()); } String path = request.getSession().getServletContext().getRealPath("/static/upload/") + "/photos/" + user.getId() + ".jpg"; File file = new File(path); try { if (file.exists()) file.delete(); else file.createNewFile(); FileUtils.copyInputStreamToFile(request.getInputStream(), file); msg = "success"; log.debug(user.getAccount() + "Path modified image=" + path); } catch (IOException e) { throw new InternalException(log, "file path=" + path, e); } log.debug(msg + "," + user.getAccount()); return msg + "," + user.getAccount(); } /** * ? * <ol> * <li>???</li> * </ol> * * @return ??? * @version 0.0.1-SNAPSHOT * @author -? */ @RequiresAuthentication @RequestMapping(value = "/share", method = RequestMethod.GET) public String refurlShare() { Subject current_user = SecurityUtils.getSubject(); User user = (User) current_user.getSession().getAttribute(ConstantPool.USER_SHIRO_SESSION_ID); if (user != null) { return "user/share"; } return "redirect:/user/signin"; } /** * ? * <ol> * <li>???</li> * </ol> * * @return * @version 0.0.1-SNAPSHOT * @author -? */ @RequiresAuthentication @Transactional @RequestMapping(value = "/share", method = RequestMethod.POST) public @ResponseBody RespMsg share(Article article, @RequestParam String label) { RespMsg respMsg = new RespMsg(); if (article != null && StringUtil.hasText(article.getTitle()) && StringUtil.hasText(article.getContent())) { // ??? Subject current_user = SecurityUtils.getSubject(); User um = (User) current_user.getSession().getAttribute(ConstantPool.USER_SHIRO_SESSION_ID); respMsg.setAppendInfo(um.getAccount()); // ?? article.setUserId(um.getId()); // ? articleService.addArticle(article); // ? if (StringUtil.hasText(label)) { String labels[] = label.split(","); if (labels != null && labels.length > 0) { // ?55??? int lng = (labels.length > 5) ? 5 : labels.length; // ???? for (int i = 0; i < lng; i++) { int label_id = 0; // ?????. Label l = new Label(); l.setName(labels[i].trim()); List<Label> list = labelService.getLabelByCondition(l); if (list.size() > 0) { label_id = list.get(0).getId(); } else { // ??? Label l2 = new Label(); l2.setUserId(um.getId()); l2.setName(labels[i].trim()); l2.setPostDate(DateUtil.getNowDateTimeStr(null)); labelService.saveLabel(l2); label_id = l2.getId(); } // ?? ArticleLabel asm = new ArticleLabel(); asm.setArticleId(article.getId()); asm.setLabelId(label_id); asm.setUserId(um.getId()); articleService.saveArticleLabel(asm); } } else { log.warn("The article label format is not correct."); respMsg.setStatus("2001"); respMsg.setMessage(ConfigPool.getString("respMsg.article.ArticlesLabelsCanotEmpty")); } } else { log.warn("The article label can't be empty."); respMsg.setStatus("2000"); respMsg.setMessage(ConfigPool.getString("respMsg.article.ArticlesLabelsCanotEmpty")); } } else { log.warn("Article is a null value."); respMsg.setStatus("1000"); respMsg.setMessage(ConfigPool.getString("respMsg.article.ArticlesCanotEmpty")); } return respMsg; } /** * ? * * @param comment_model * @return * @version 0.0.2-SNAPSHOT * @author -?-? */ @RequiresAuthentication @Transactional @RequestMapping(value = "/comment", method = RequestMethod.POST) public String comment(Comment comment_model, @RequestParam String article_user_id) { if (StringUtil.hasText(comment_model.getContent())) { Subject current_user = SecurityUtils.getSubject(); User user_model = (User) current_user.getSession().getAttribute(ConstantPool.USER_SHIRO_SESSION_ID); if (user_model != null && user_model.getId() > 0 && !article_user_id.equals(String.valueOf(user_model.getId()))) { comment_model.setUserId(user_model.getId()); comment_model.setType(1); commentService.addComment(comment_model); return "redirect:/article/" + comment_model.getObjId(); } } return "redirect:/articles"; } /** * ?json? * * @return json? * @version 0.0.2-SNAPSHOT * @author -? */ @RequestMapping(value = "/findLabel") @ResponseBody public List<AutoComplete> findLabel(@RequestParam String term) { List<AutoComplete> auto = new ArrayList<AutoComplete>(); if (StringUtil.hasText(term)) { try { term = URLDecoder.decode(term, "UTF-8"); Label label = new Label(); label.setName(term); List<Label> list = labelService.getLabelByCondition(label); auto = this.label2AutoComplete(list); } catch (UnsupportedEncodingException e) { throw new InternalException(log, e); } } else { log.warn("Query parameters are not allowed to empty."); } return auto; } /** * ????? * * @param labels ?? * @return ?AutoComplete? * @version 0.0.2-SNAPSHOT * @author -? */ private List<AutoComplete> label2AutoComplete(List<Label> labels) { List<AutoComplete> autoCompletes = new ArrayList<AutoComplete>(); if (labels != null && labels.size() > 0) { for (int i = 0; i < labels.size(); i++) { Label label = labels.get(i); AutoComplete ac = new AutoComplete(); ac.setId(label.getId()); ac.setLabel(label.getName()); ac.setValue(label.getName()); autoCompletes.add(ac); } } return autoCompletes; } /** * ?<br> * ????? * * @return ??? * @version 0.0.1-SNAPSHOT * @author -? */ @RequiresAuthentication @RequestMapping(value = "/emailskip/{account}") public String emailApprove(Model model) { // 1?? Template template = templateService.loadByName("certifiedMail"); String str = template.getContent(); // 2???? Subject current_user = SecurityUtils.getSubject(); User user_model = (User) current_user.getSession().getAttribute(ConstantPool.USER_SHIRO_SESSION_ID); String url = templateService.generateAuthURL(user_model.getAccount()); // 3??? str = str.replaceAll("#account#", user_model.getAccount()); str = str.replaceAll("#url#", url); template.setContent(str); // 4??? mailService.sendMail(user_model.getEmail(), template); return "user/emailskip"; } /** * ??? * * @param model ?? * @return */ @RequestMapping(value = "/dynamicArticles", method = RequestMethod.GET) public String refurlDynamicArticles(Model model, @RequestParam(defaultValue = "1") String now_page, HttpServletRequest request) { Subject current_user = SecurityUtils.getSubject(); User user_model = (User) current_user.getSession().getAttribute(ConstantPool.USER_SHIRO_SESSION_ID); if (user_model != null) { int rows = 20; Map<String, Object> param = new HashMap<String, Object>(); param.put("userId", user_model.getId()); param.put("offrow", (StringUtil.getInt(now_page, 1) - 1) * rows); param.put("rows", rows); // ??5 List<Article> dynamicArticles = articleService.getDynamicArticleByUserId(param); int total = articleService.countDynamicArticleRows(param); Pagination pagination = new Pagination(StringUtil.getInt(now_page, 1), rows, 5, total, request.getContextPath().concat("/dynamicArticles"), now_page); model.addAttribute("pagination", pagination); model.addAttribute("articles", dynamicArticles); model.addAttribute("user", user_model); return "user/dynamic_articles"; } else { return "redirect:/user/signin"; } } /** * ???<br> * * @return */ @RequestMapping(value = "/bind", method = RequestMethod.GET) public String refurlInfoBind() { return "user/bind"; } }