基于javaweb+mysql的springboot在线游戏商城系统(java+springboot+mybatis+mysql+maven+layui+thymeleaf+html)
运行环境
Java≥8、MySQL≥5.7
开发工具
eclipse/idea/myeclipse/sts等均可配置运行
适用
课程设计,大作业,毕业设计,项目练习,学习演示等
功能说明
基于javaweb+mysql的SpringBoot在线游戏商城系统(java+springboot+mybatis+mysql+maven+layui+thymeleaf+html)
一、项目简述功能包括: 用户管理,游戏商品管理,在线购买,上传,售卖记录,商品审核等等。
二、项目运行环境配置:
Jdk1.8 + Tomcat8.5 + mysql + Eclispe(IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持)
项目技术:
JSP +Spring + SpringBoot + MyBatis + html+ css + JavaScript + JQuery + Ajax + layui+ maven等等
* */
@GetMapping("/user/alertmessage")
public String alertmessage(){
return "/user/message/alertmessage";
}
/**
* 跳转到产品清单界面
* */
@GetMapping("/product-listing")
public String toproductlisting() {
return "/common/product-listing";
}
/**
* 跳转到产品清单搜索界面
* */
@GetMapping("/product-search")
public String toProductSearchs(String keys, ModelMap modelMap) {
if(keys==null){
return "/error/404";
}
modelMap.put("keys",keys);
return "/common/product-search";
}
/**用户个人中心默认展示图*/
@GetMapping("/home/console")
public String homeconsole(){
return "/admin/home/console";
}
/**
* 管理员首页默认展示图
* */
@GetMapping("/echars/console")
public String echars(){
return "/admin/echars/console";
}
@GetMapping("/app/message/index")
String userid=(String) session.getAttribute("userid");
UserInfo userInfo = new UserInfo().setUserid(userid).setUimage(uimgUrl);
userInfoService.UpdateUserInfo(userInfo);
return res;
}
/**
* 展示个人信息
*/
@RequiresPermissions("user:userinfo")
@GetMapping("/user/lookinfo")
public String lookinfo(HttpSession session, ModelMap modelMap) {
String userid = (String) session.getAttribute("userid");
UserInfo userInfo = userInfoService.LookUserinfo(userid);
modelMap.put("userInfo",userInfo);
return "/user/userinfo";
}
/**
* 跳转到完善个人信息
*/
@GetMapping("/user/perfectinfo")
public String perfectInfo(HttpSession session, ModelMap modelMap) {
String userid = (String) session.getAttribute("userid");
UserInfo userInfo = userInfoService.LookUserinfo(userid);
modelMap.put("perfectInfo",userInfo);
return "/user/perfectinfo";
}
/**
* 修改个人信息
* 1.前端传入用户昵称(username)、用户邮箱(email)、性别(sex)、游戏(server
* 2.前端传入变更后的字段,未变更的不传入后台
* 3.判断更改的用户名是否已存在
* 4.修改个人信息
*/
@ResponseBody
@PostMapping("/user/updateinfo")
public ResultVo updateInfo(@RequestBody UserInfo userInfo, HttpSession session) {
String username = userInfo.getUsername();
String sessionname = (String) session.getAttribute("username");
String userid = (String) session.getAttribute("userid");
Login login = new Login();
//如果传入用户名不为空
if (!StringUtils.isEmpty(username)){
return new ResultVo(true, StatusCode.OK,"取消成功");
}
return new ResultVo(false,StatusCode.ERROR,"取消失败");
}
return new ResultVo(false,StatusCode.ACCESSERROR,"禁止操作");
}
}
/**
* 收藏列表界面取消收藏
* 1.前端传入收藏id(id)
* 2.判断是否本人取消收藏
* 3.进行取消收藏操作
*/
@ResponseBody
@PutMapping("/collect/delete/{id}")
public ResultVo deletecollect(@PathVariable("id") String id,HttpSession session){
String couserid = (String) session.getAttribute("userid");
Collect collect = new Collect().setId(id).setCouserid(couserid);
Collect collect1 = collectService.queryCollectStatus(collect);
/**判断是否为本人操作*/
if (collect1.getCouserid().equals(couserid)){
collect.setColloperate(2);
Integer i = collectService.updateCollect(collect);
if (i == 1){
return new ResultVo(true, StatusCode.OK,"取消成功");
}
return new ResultVo(false,StatusCode.ERROR,"取消失败");
}
return new ResultVo(false,StatusCode.ACCESSERROR,"禁止操作");
}
/**
* 分页查看用户所有收藏内容
* 前端传入页码、分页数量
* 查询分页数据
*/
@ResponseBody
@GetMapping("/user/collect/queryall")
public LayuiPageVo usercollect(int limit, int page, HttpSession session) {
String couserid = (String) session.getAttribute("userid");
List<Collect> collectList = collectService.queryAllCollect((page - 1) * limit, limit, couserid);
Integer dataNumber = collectService.queryCollectCount(couserid);
return new LayuiPageVo("",0,dataNumber,collectList);
}
}
package com.controller;
*/
@Controller
public class AdminController {
@Autowired
private UserRoleService userRoleService;
@Autowired
private LoginService loginService;
@Autowired
private UserInfoService userInfoService;
@Autowired
private CommodityService commodityService;
@Autowired
private NoticesService noticesService;
/**
* 管理员跳转登录
*/
@GetMapping("/admin")
public String admintologin() {
return "admin/login/login";
}
/**
* 管理员登录
* 1.判断输入账号的类型
* 2.判断是否为管理员或者超级管理员
* 3.登录
* */
@ResponseBody
@PostMapping("/admin/login")
public ResultVo adminlogin(@RequestBody Login login, HttpSession session){
System.out.println("测试是否进入!!!");
String account=login.getUsername();
String password=login.getPassword();
String vercode=login.getVercode();
UsernamePasswordToken token;
if(!ValidateCode.code.equalsIgnoreCase(vercode)){
return new ResultVo(false,StatusCode.ERROR,"请输入正确的验证码");
}
//判断输入的账号是否手机号
if (!JustPhone.justPhone(account)) {
//输入的是用户名
String username = account;
//盐加密
@Override
public void run() {
phonecodemap1.remove(phoneNum);
timer.cancel();
}
}, 5 * 60 * 1000);
*/
//执行定时任务
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
phonecodemap1.remove(mobilephone);
((ScheduledThreadPoolExecutor) executorService).remove(this::run);
}
},1 * 10 * 1000,1 * 10 * 1000, TimeUnit.HOURS);
return new ResultVo(true,StatusCode.SMS,"验证码发送成功");
}else if(result == 2){
return new ResultVo(false,StatusCode.ERROR,"请输入正确格式的手机号");
}
return new ResultVo(false,StatusCode.REMOTEERROR,"验证码发送失败");
}
/**注册
* 1.前端传入用户名(username)、密码(password)、邮箱(email)、手机号(mobilephone)、验证码(vercode)
* 2.查询账号是否已经注册
* 3.查询用户名是否已存在
* 4.判断验证码是否有效或正确
* 5.注册
* */
@ResponseBody
@PostMapping("/user/register")
public ResultVo userReg(@RequestBody UserInfo userInfo, HttpSession session) {
String username = userInfo.getUsername();
String password = userInfo.getPassword();
String mobilephone = userInfo.getMobilephone();
String vercode = userInfo.getVercode();
Login login = new Login().setMobilephone(mobilephone);
//查询账号是否已经注册
Login userIsExist = loginService.userLogin(login);
if (!StringUtils.isEmpty(userIsExist)){//用户账号已经存在
return new ResultVo(false, StatusCode.ERROR,"该用户已经注册过了");
}
login.setUsername(username).setMobilephone(null);
Login userNameIsExist = loginService.userLogin(login);
if (!StringUtils.isEmpty(userNameIsExist)){//用户名已经存在
return new ResultVo(false, StatusCode.ERROR,"用户名已存在,请换一个吧");
}
String rel = phonecodemap1.get(mobilephone);
if (StringUtils.isEmpty(rel)) {//验证码到期 或者 没发送短信验证码
return new ResultVo(false,StatusCode.ERROR,"请重新获取验证码");
}
//if (rel.equalsIgnoreCase(vercode)) {
* 管理员登录
* 1.判断输入账号的类型
* 2.判断是否为管理员或者超级管理员
* 3.登录
* */
@ResponseBody
@PostMapping("/admin/login")
public ResultVo adminlogin(@RequestBody Login login, HttpSession session){
System.out.println("测试是否进入!!!");
String account=login.getUsername();
String password=login.getPassword();
String vercode=login.getVercode();
UsernamePasswordToken token;
if(!ValidateCode.code.equalsIgnoreCase(vercode)){
return new ResultVo(false,StatusCode.ERROR,"请输入正确的验证码");
}
//判断输入的账号是否手机号
if (!JustPhone.justPhone(account)) {
//输入的是用户名
String username = account;
//盐加密
token=new UsernamePasswordToken(username, new Md5Hash(password,"Game-shops").toString());
}else {
//输入的是手机号
String mobilephone = account;
login.setMobilephone(mobilephone);
//将封装的login中username变为null
login.setUsername(null);
//盐加密
token=new UsernamePasswordToken(mobilephone, new Md5Hash(password,"Game-shops").toString());
}
Subject subject= SecurityUtils.getSubject();
try {
subject.login(token);
//盐加密
String passwords = new Md5Hash(password, "Game-shops").toString();
login.setPassword(passwords);
Login login1 = loginService.userLogin(login);
//查询登录者的权限
Integer roleId = userRoleService.LookUserRoleId(login1.getUserid());
if (roleId == 2 || roleId == 3){
session.setAttribute("admin",login1.getUsername());
session.setAttribute("username",login1.getUsername());
return new ResultVo(true,StatusCode.OK,"登录成功");
}
return new ResultVo(true,StatusCode.ACCESSERROR,"权限不足");
}catch (UnknownAccountException e){
return new ResultVo(true,StatusCode.LOGINERROR,"用户名不存在");
}catch (IncorrectCredentialsException e){
/**
* 后台分页查看公告列表
* 1.前端传入页码、分页数量
* 2.查询分页数据
*/
@ResponseBody
@GetMapping("/news/queryall")
public LayuiPageVo queryAllNews(int limit, int page) {
List<News> newsList = newsService.queryAllNews((page - 1) * limit, limit);
Integer dataNumber = newsService.LookNewsCount();
return new LayuiPageVo("",0,dataNumber,newsList);
}
/**
* 首页公告分页数据
* */
@GetMapping("/news/index/number")
@ResponseBody
public PageVo newsNumber(){
Integer dataNumber = newsService.LookNewsCount();
return new PageVo(StatusCode.OK,"查询成功",dataNumber);
}
/**
* 首页网站公告
* 1.前端传入页码、分页数量
* 2.查询分页数据
* */
@GetMapping("/news/index/{page}")
@ResponseBody
public ResultVo newsIndex(@PathVariable("page") Integer page){
List<News> newsList = newsService.queryAllNews((page - 1) * 9, 9);
return new ResultVo(true,StatusCode.OK,"查询成功",newsList);
}
}
package com.controller;
/**
* <p>
* 评论和回复控制器
* </p>
*
*/
@Controller
public class CommentReplyController {
@Autowired
private CommodityService commodityService;
@Autowired
private CommentService commentService;
@Autowired
private ReplyService replyService;
@Autowired
private UserInfoService userInfoService;
@Autowired
private NoticesService noticesService;
/**
* 查询商品下的评论和回复
* */
@ResponseBody
Integer integer = loginService.updateLogin(login);
Integer integer1 = userInfoService.UpdateUserInfo(userInfo);
if (integer == 1 && integer1 == 1) {
return new ResultVo(true, StatusCode.OK, "更换手机号成功");
}
return new ResultVo(false, StatusCode.SERVERERROR, "系统错误,更换失败");
}
return new ResultVo(false,StatusCode.ERROR,"验证码错误");
}
}
package com.controller;
/**
* <p>
* 评论和回复控制器
* </p>
*
*/
@Controller
public class CommentReplyController {
@Autowired
private CommodityService commodityService;
@Autowired
private CommentService commentService;
@Autowired
private ReplyService replyService;
@Autowired
private UserInfoService userInfoService;
@Autowired
private NoticesService noticesService;
* 最低价(minmoney)、最高价(maxmoney)、价格升序降序(sequencetype:1.升序 2.降序)
* 后端根据session查出服务器信息(server)
*/
@Test
@GetMapping()
public void productlisting() {
String category = "全部";
String area = "全部";
String userid = "1582184795951594874";
BigDecimal minmoney = new BigDecimal(1.00);
BigDecimal maxmoney = new BigDecimal(1000.00);
Integer page = 1;
Integer price = 0;
UserInfo userInfo = userInfoService.LookUserinfo(userid);
String server = userInfo.getServer();
List<Commodity> commodityList = commodityService.queryAllCommodityByCategory((page - 1) * 10, 10, area, server, category, minmoney, maxmoney);
Integer dataNumber = commodityService.queryAllCommodityByCategoryCount(area, server, category, minmoney, maxmoney);
Integer pages = PageLength.getPages(dataNumber, 10);
System.out.println("排序前的商品为:");
for (Commodity commodity : commodityList) {
System.out.println(commodity);
}
Collections.sort(commodityList, new Comparator<Commodity>() {//此处创建了一个匿名内部类
int i;
// /**升序*/
// @Override
// public int compare(Commodity o1, Commodity o2) {
// if (o1.getThinkmoney().compareTo(o2.getThinkmoney()) > -1) {
// System.out.println("===o1大于等于o2===");
// i = 1;
// } else if (o1.getThinkmoney().compareTo(o2.getThinkmoney()) < 1) {
// i = -1;
// System.out.println("===o1小于等于o2===");
// }
// return i;
// }
/**降序*/
@Override
public int compare(Commodity o1, Commodity o2) {
if (o1.getThinkmoney().compareTo(o2.getThinkmoney()) > -1) {
System.out.println("===o1大于等于o2===");
@PathVariable("price") Integer price, HttpSession session) {
String server=null;
if(!area.equals("全部")) {
String userid = (String) session.getAttribute("userid");
UserInfo userInfo = userInfoService.LookUserinfo(userid);
server = userInfo.getServer();
}
List<Commodity> commodityList = commodityService.queryAllCommodityByCategory((page - 1) * 16, 16, area, server, category, minmoney, maxmoney);
for (Commodity commodity : commodityList) {
/**查询商品对应的其它图片*/
List<String> imagesList = commimagesService.LookGoodImages(commodity.getCommid());
commodity.setOtherimg(imagesList);
}
/**自定义排序*/
if (price != 0){
if (price == 1){
/**升序*/
Collections.sort(commodityList, new Comparator<Commodity>() {//此处创建了一个匿名内部类
int i;
@Override
public int compare(Commodity o1, Commodity o2) {
if (o1.getThinkmoney().compareTo(o2.getThinkmoney()) > -1) {
System.out.println("===o1大于等于o2===");
i = 1;
} else if (o1.getThinkmoney().compareTo(o2.getThinkmoney()) < 1) {
i = -1;
System.out.println("===o1小于等于o2===");
}
return i;
}
});
}else if (price == 2){
/**降序*/
Collections.sort(commodityList, new Comparator<Commodity>() {//此处创建了一个匿名内部类
int i;
@Override
public int compare(Commodity o1, Commodity o2) {
if (o1.getThinkmoney().compareTo(o2.getThinkmoney()) > -1) {
System.out.println("===o1大于等于o2===");
i = -1;
} else if (o1.getThinkmoney().compareTo(o2.getThinkmoney()) < 1) {
System.out.println("===o1小于等于o2===");
i = 1;
}
return i;
}
package com.controller;
/**
* <p>
* 收藏控制器
* </p>
*
*/
@Controller
public class CollectController {
@Autowired
private CollectService collectService;
/**
* 商品详情界面:收藏商品or取消收藏
* 前端传入收藏操作(colloperate:1收藏,2取消收藏),获取session中用户id信息,判断是否登录
* (1). 收藏商品
* 1.前端传入商品id(commid)、商品名(commname)、商品描述(commdesc)、商品用户id(cmuserid)
* 商品用户名(username)、商品所在游戏(server)
* 2.session中获取收藏用户id(couserid)
* 3.进行收藏操作
* (2). 取消收藏
* 1.前端传入商品id(commid)
* 2.判断是否本人取消收藏
* 3.进行取消收藏操作
*/
@ResponseBody
@PostMapping("/collect/operate")
public ResultVo insertcollect(@RequestBody Collect collect, HttpSession session){
String couserid = (String) session.getAttribute("userid");
((ScheduledThreadPoolExecutor) executorService).remove(this::run);
}
},1 * 10 * 1000,1 * 10 * 1000, TimeUnit.HOURS);
return new ResultVo(true,StatusCode.SMS,"验证码发送成功");
}else if(result == 2){
return new ResultVo(false,StatusCode.ERROR,"请输入正确格式的手机号");
}
return new ResultVo(false,StatusCode.REMOTEERROR,"验证码发送失败");
}
/**注册
* 1.前端传入用户名(username)、密码(password)、邮箱(email)、手机号(mobilephone)、验证码(vercode)
* 2.查询账号是否已经注册
* 3.查询用户名是否已存在
* 4.判断验证码是否有效或正确
* 5.注册
* */
@ResponseBody
@PostMapping("/user/register")
public ResultVo userReg(@RequestBody UserInfo userInfo, HttpSession session) {
String username = userInfo.getUsername();
String password = userInfo.getPassword();
String mobilephone = userInfo.getMobilephone();
String vercode = userInfo.getVercode();
Login login = new Login().setMobilephone(mobilephone);
//查询账号是否已经注册
Login userIsExist = loginService.userLogin(login);
if (!StringUtils.isEmpty(userIsExist)){//用户账号已经存在
return new ResultVo(false, StatusCode.ERROR,"该用户已经注册过了");
}
login.setUsername(username).setMobilephone(null);
Login userNameIsExist = loginService.userLogin(login);
if (!StringUtils.isEmpty(userNameIsExist)){//用户名已经存在
return new ResultVo(false, StatusCode.ERROR,"用户名已存在,请换一个吧");
}
String rel = phonecodemap1.get(mobilephone);
if (StringUtils.isEmpty(rel)) {//验证码到期 或者 没发送短信验证码
return new ResultVo(false,StatusCode.ERROR,"请重新获取验证码");
}
//if (rel.equalsIgnoreCase(vercode)) {
if (vercode.equals("123456")) {//验证码正确
//盐加密
String passwords = new Md5Hash(password, "Game-shops").toString();
}else if (userstatus == 1){
Integer i = loginService.updateLogin(new Login().setUserid(userid).setUserstatus(userstatus));
Integer j = userInfoService.UpdateUserInfo(new UserInfo().setUserid(userid).setUserstatus(userstatus));
if (i ==1 && j == 1){
/**发出解封的系统通知*/
Notices notices = new Notices().setId(KeyUtil.genUniqueKey()).setUserid(userid).setTpname("系统通知")
.setWhys("您在该网站的账号已被解封,希望您保持良好的行为。");
noticesService.insertNotices(notices);
return new ResultVo(true, StatusCode.OK, "解封成功");
}
return new ResultVo(true, StatusCode.ERROR, "解封失败");
}
return new ResultVo(false,StatusCode.ACCESSERROR,"违规操作");
}
/**
* 管理员商品列表
* */
@GetMapping("/admin/product")
public String adminproduct(){
return "/admin/product/productlist";
}
/**
* 分页管理员查看各类商品信息
*前端传入页码、分页数量
*前端传入商品信息状态码(commstatus)-->全部:100,违规:0,已审核:1,待审核:3 已完成:4
* 因为是管理员查询,将userid设置为空
*/
@GetMapping("/admin/commodity/{commstatus}")
@ResponseBody
public LayuiPageVo userCommodity(@PathVariable("commstatus") Integer commstatus, int limit, int page) {
if(commstatus==100){
List<Commodity> commodityList = commodityService.queryAllCommodity((page - 1) * limit, limit, null, null);
Integer dataNumber = commodityService.queryCommodityCount(null, null);
return new LayuiPageVo("",0,dataNumber,commodityList);
}else{
List<Commodity> commodityList = commodityService.queryAllCommodity((page - 1) * limit, limit, null, commstatus);
Integer dataNumber = commodityService.queryCommodityCount(null, commstatus);
return new LayuiPageVo("",0,dataNumber,commodityList);
}
}
/**
* 管理员对商品的操作
* 前端传入商品id(commid)
* 前端传入操作的商品状态(commstatus)-->违规:0 通过审核:1
* */
@ResponseBody
@PutMapping("/admin/changecommstatus/{commid}/{commstatus}")
@ResponseBody
@GetMapping("/index/product/{category}")
public ResultVo indexCommodity(@PathVariable("category") String category) {
List<Commodity> commodityList = commodityService.queryCommodityByCategory(category);
for (Commodity commodity : commodityList) {
/**查询商品对应的其它图片*/
List<String> imagesList = commimagesService.LookGoodImages(commodity.getCommid());
commodity.setOtherimg(imagesList);
}
return new ResultVo(true,StatusCode.OK,"查询成功",commodityList);
}
/**
* 查询最新发布的8条商品
* */
@ResponseBody
@GetMapping("/product/latest")
public ResultVo latestCommodity() {
String category = "全部";
List<Commodity> commodityList = commodityService.queryCommodityByCategory(category);
for (Commodity commodity : commodityList) {
/**查询商品对应的其它图片*/
List<String> imagesList = commimagesService.LookGoodImages(commodity.getCommid());
commodity.setOtherimg(imagesList);
}
return new ResultVo(true,StatusCode.OK,"查询成功",commodityList);
}
/**
* 产品清单分页数据
* 前端传入商品类别(category)、区域(area)
* 最低价(minmoney)、最高价(maxmoney)
* 后端根据session查出个人本校信息(server)
* */
@GetMapping("/list-number/{category}/{area}/{minmoney}/{maxmoney}")
@ResponseBody
public PageVo productListNumber(@PathVariable("category") String category, @PathVariable("area") String area,
@PathVariable("minmoney") BigDecimal minmoney, @PathVariable("maxmoney") BigDecimal maxmoney,
HttpSession session) {
String server=null;
@Controller
public class CommodityController {
@Autowired
private CommodityService commodityService;
@Autowired
private CommimagesService commimagesService;
@Autowired
private LoginService loginService;
@Autowired
private UserInfoService userInfoService;
@Autowired
private SoldrecordService soldrecordService;
@Autowired
private CollectService collectService;
@Autowired
private NoticesService noticesService;
/**
* 跳转到发布商品
*/
@GetMapping("/user/relgoods")
public String torelgoods(HttpSession session){
/*String userid = (String)session.getAttribute("userid");
if(userid==null){
return "redirect:/:";
}*/
return "/user/product/relgoods";
}
/**
* 跳转到修改商品
* --不能修改已删除、已完成的商品
* 1、查询商品详情
* 2、查询商品得其他图
*/
@GetMapping("/user/editgoods/{commid}")
public String toeditgoods(@PathVariable("commid")String commid, HttpSession session, ModelMap modelMap){
/*String userid = (String)session.getAttribute("userid");
if(userid==null){
return "redirect:/:";
}*/
Commodity commodity=commodityService.LookCommodity(new Commodity().setCommid(commid));
if(commodity.getCommstatus().equals(2) || commodity.getCommstatus().equals(4)){
return "/error/404";//商品已被删除或已完成交易
@GetMapping("/about")
public String about(){
return "/common/about";
}
/**
* 后台管理首页
* */
@GetMapping("/admin/index")
public String adminindex(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {
String admin = (String) session.getAttribute("admin");
/**拦截器:如果不是管理员,则进行重定向*/
if (StringUtils.isEmpty(admin)){
response.sendRedirect(request.getContextPath() + "/");//重定向
}
return "/admin/index";
}
/**
* 用户登录注册
* */
@GetMapping("/login")
public String login(){
return "/user/logreg";
}
/**
* 用户忘记密码
* */
@GetMapping("/forget")
public String forget(){
return "user/forget";
}
/**
* 个人中心
* */
@GetMapping("/user/center")
public String usercenter(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {
String userid = (String) session.getAttribute("userid");
/**拦截器:如果不是用户角色登录,则进行重定向*/
if (StringUtils.isEmpty(userid)){
response.sendRedirect(request.getContextPath() + "/");//重定向
}
@Controller
public class ChatCtrl {
@Autowired
FriendsService friendsService;
@Autowired
UserInfoService mineService;
@Autowired
ChatmsgService chatmsgService;
/**
* 上传聊天图片
* **/
@PostMapping(value = "/chat/upimg")
@ResponseBody
public JSONObject upimg(@RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
JSONObject res = new JSONObject();
JSONObject resUrl = new JSONObject();
String filename = UUID.randomUUID().toString().replaceAll("-", "");
String ext = FilenameUtils.getExtension(file.getOriginalFilename());//获得文件扩展名
String filenames = filename + "." + ext;
file.transferTo(new File("D://file/" + filenames));
resUrl.put("src", "/pic/" + filenames);
res.put("msg", "");
res.put("code", 0);
res.put("data", resUrl);
return res;
}
/**
* 上传聊天文件
* **/
/**
* <p>
* 登录注册 控制器
* </p>
*
*/
@Controller
public class LoginController {
@Autowired
private LoginService loginService;
@Autowired
private UserInfoService userInfoService;
@Autowired
private UserRoleService userRoleService;
/**手机号和注册验证码map集合*/
private static Map<String, String> phonecodemap1 = new HashMap<>();
/**手机号和重置密码验证码map集合*/
private static Map<String, String> phonecodemap2 = new HashMap<>();
/**
*图片验证码
* */
@RequestMapping(value = "/images", method = {RequestMethod.GET, RequestMethod.POST})
public void images(HttpServletResponse response) throws IOException {
response.setContentType("image/jpeg");
//禁止图像缓存。
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
ValidateCode vCode = new ValidateCode(820, 200, 5, 80);
vCode.write(response.getOutputStream());
}
/**注册时发送短信验证码
* 1.判断是否为注册类型验证码
* 2.判断手机号格式是否正确
* 3.判断手机号是否已经注册过
* 4.发送注册验证码并存入map集合
* */
@ResponseBody
/**插入评论*/
Integer i = commentService.insertComment(comment);
if (i == 1){
/**发出评论通知消息*/
Commodity commodity = commodityService.LookCommodity(new Commodity().setCommid(comment.getCommid()));
Notices notices = new Notices().setId(KeyUtil.genUniqueKey()).setUserid(comment.getSpuserid()).setTpname("评论")
.setWhys("您的商品 <a href=/product-detail/"+comment.getCommid()+" style=\"color:#08bf91\" target=\"_blank\" >"+commodity.getCommname()+"</a> 被评论了,快去看看吧。");
noticesService.insertNotices(notices);
return new ResultVo(true, StatusCode.OK,"评论成功");
}
return new ResultVo(false,StatusCode.ERROR,"评论失败");
}
/**
* 评论回复
* 1.前端传入:商品id(commid)、评论id(cid)、被回复用户id(cuserid)、商品发布者id(spuserid)、评论内容(recontent)
* 2.session获取:回复者id(ruserid)
* 3.过滤评论回复内容后,插入评论回复
*/
@ResponseBody
@PostMapping("/reply/insert")
public ResultVo insertreply(@RequestBody Reply reply,HttpSession session) {
String ruserid = (String) session.getAttribute("userid");
String recontent = reply.getRecontent();
if (StringUtils.isEmpty(ruserid)) {
return new ResultVo(false,StatusCode.ACCESSERROR,"请登录后再评论");
}
recontent = recontent.replace("<", "<");
recontent = recontent.replace(">", ">");
recontent = recontent.replace("'", "\"");
reply.setRid(KeyUtil.genUniqueKey()).setRuserid(ruserid).setRecontent(recontent);
/**插入回复*/
Integer i = replyService.insetReply(reply);
if (i == 1){
/**发出评论回复通知消息*/
Commodity commodity = commodityService.LookCommodity(new Commodity().setCommid(reply.getCommid()));
Notices notices = new Notices().setId(KeyUtil.genUniqueKey()).setUserid(reply.getCuserid()).setTpname("评论回复")
.setWhys("有小伙伴在 <a href=/product-detail/"+reply.getCommid()+" style=\"color:#08bf91\" target=\"_blank\" >"+commodity.getCommname()+"</a> 下回复了您的评论,快去看看吧。");
noticesService.insertNotices(notices);
return new ResultVo(true, StatusCode.OK,"回复成功");
}
return new ResultVo(false,StatusCode.ERROR,"回复失败");
}
* 连接建立成功调用的方法
*
* session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(@PathParam(value = "userno") String param, Session WebSocketsession, EndpointConfig config) {
userno = param;//接收到发送消息的人员编号
this.WebSocketsession = WebSocketsession;
webSocketSet.put(param, this);//加入map中
addOnlineCount(); //在线数加1 System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
mineService.UpdateUserInfo(new UserInfo().setUserid(userno).setStatus("online")); //更新用户的状态为在线
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
if (!userno.equals("")) {
webSocketSet.remove(userno); //从set中删除
subOnlineCount(); //在线数减1 System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
mineService.UpdateUserInfo(new UserInfo().setUserid(userno).setStatus("offline")); //更新用户的状态为离线
}
}
/**
//给指定的人发消息
* @param session 可选的参数
*/
@SuppressWarnings("unused")
@OnMessage
public void onMessage(String mine, Session session) {
System.out.println("DJLDebug:onMessage给指定的人发消息");
JSONObject jsonObject = JSONObject.parseObject(mine);
String msgtype=jsonObject.getString("type");
if(msgtype.equals("friend")){
sendToUser(jsonObject.toJavaObject(UserInfo.class));
}else if(msgtype.equals("group")){
return "/error/404";
}
}
/**
* 搜索商品分页数据
* 前端传入搜索的商品名(commname)
* */
@GetMapping("/product/search/number/{commname}")
@ResponseBody
public PageVo searchCommodityNumber(@PathVariable("commname") String commname){
Integer dataNumber = commodityService.queryCommodityByNameCount(commname);
return new PageVo(StatusCode.OK,"查询成功",dataNumber);
}
/**
* 搜索商品
* 前端传入当前页数(nowPaging)、搜索的商品名(commname)
* */
@GetMapping("/product/search/{nowPaging}/{commname}")
@ResponseBody
public ResultVo searchCommodity(@PathVariable("nowPaging") Integer page, @PathVariable("commname") String commname){
List<Commodity> commodityList = commodityService.queryCommodityByName((page - 1) * 20, 20, commname);
if(!StringUtils.isEmpty(commodityList)){//如果有对应商品
for (Commodity commodity : commodityList) {
/**查询商品对应的其它图片*/
List<String> imagesList = commimagesService.LookGoodImages(commodity.getCommid());
commodity.setOtherimg(imagesList);
}
return new ResultVo(true,StatusCode.OK,"查询成功",commodityList);
}else{
return new ResultVo(true,StatusCode.ERROR,"没有相关商品");
}
}
/**
* 首页分类展示商品 --> 按照分类查询商品
* 前端传入商品类别(category)
* */
noticesService.insertNotices(notices);
}
return new ResultVo(true,StatusCode.OK,"操作成功");
}
return new ResultVo(false,StatusCode.ERROR,"操作失败");
}
}
package com.controller.User;
/**
/**
* <p>
* 个人中心 控制器
* </p>
*
*/
@Controller
public class UserController {
@Autowired
private LoginService loginService;
@Autowired
private UserInfoService userInfoService;
/**手机号和更换手机号验证码map集合*/
private static Map<String, String> phonecodemap = new HashMap<>();
/**
* 修改密码
* 1.前端传入旧密码(oldpwd)、新密码(newpwd)
* 2.判断输入旧密码和系统旧密码是否相等
* 4.修改密码
*/
@PostMapping(value="/relgoods/images")
@ResponseBody
public JSONObject relgoodsimages(@RequestParam(value = "file", required = false) MultipartFile[] file) throws IOException {
JSONObject res = new JSONObject();
JSONObject resUrl = new JSONObject();
List<String> imageurls=new ArrayList<>();
for (MultipartFile files:file){
String filename = UUID.randomUUID().toString().replaceAll("-", "");
String ext = FilenameUtils.getExtension(files.getOriginalFilename());
String filenames = filename + "." + ext;
String pathname = "D:/file/" + filenames;
files.transferTo(new File(pathname));
imageurls.add("/pic/"+filenames);
res.put("msg", "");
res.put("code", 0);
}
resUrl.put("src", imageurls);
res.put("data", resUrl);
return res;
}
/**
* 商品详情
* 根据商品id(commid)查询商品信息、用户昵称及头像
* 用户可以查看正常的商品
* 商品发布者和管理员可以查看
* */
@GetMapping("/product-detail/{commid}")
public String product_detail(@PathVariable("commid") String commid, ModelMap modelMap,HttpSession session){
String couserid = (String) session.getAttribute("userid");
System.out.println("commid = "+commid);
System.out.println("commodity = " + commodityService.LookCommodity(new Commodity().setCommid(commid).setCommstatus(1)).getImage());
Commodity commodity = commodityService.LookCommodity(new Commodity().setCommid(commid).setCommstatus(1));
int i = 0;
if (commodity.getCommstatus().equals(1)){//如果商品正常
i=1;
}else if (!StringUtils.isEmpty(couserid)){//如果用户已登录
Login login = loginService.userLogin(new Login().setUserid(couserid));
/**商品为违规状态时:本人和管理员可查看*/
if (commodity.getCommstatus().equals(0) && (commodity.getUserid().equals(couserid) || (login.getRoleid().equals(2) || login.getRoleid().equals(3)))){
i=1;
/**商品为待审核状态时:本人和管理员可查看*/
}else if (commodity.getCommstatus().equals(3) && (commodity.getUserid().equals(couserid) || (login.getRoleid().equals(2) || login.getRoleid().equals(3)))){
i=1;
/**商品为已售出状态时:本人和管理员可查看*/
}else if (commodity.getCommstatus().equals(4) && (commodity.getUserid().equals(couserid) || (login.getRoleid().equals(2) || login.getRoleid().equals(3)))){
JSONObject res = new JSONObject();
JSONObject resUrl = new JSONObject();
String filename = UUID.randomUUID().toString().replaceAll("-", "");
String ext = FilenameUtils.getExtension(file.getOriginalFilename());//获得文件扩展名
String filenames = filename + "." + ext;
file.transferTo(new File("D://file/" + filenames));
resUrl.put("src", "/pic/" + filenames);
res.put("msg", "");
res.put("code", 0);
res.put("data", resUrl);
return res;
}
/**
* 上传聊天文件
* **/
@PostMapping(value = "/chat/upfile")
@ResponseBody
public JSONObject upfile(@RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
JSONObject res = new JSONObject();
JSONObject resUrl = new JSONObject();
String filename = UUID.randomUUID().toString().replaceAll("-", "");
String ext = FilenameUtils.getExtension(file.getOriginalFilename());//获得文件扩展名
String filenames = filename + "." + ext;
file.transferTo(new File("D:\\campusshops\\file\\" + filenames));
resUrl.put("src", "/pic/" + filenames);
resUrl.put("name",file.getOriginalFilename());
res.put("msg", "");
res.put("code", 0);
res.put("data", resUrl);
return res;
}
/**
* 添加好友跳转到个人中心聊天
* */
@PutMapping("/addfrend/{fuserid}")
@ResponseBody
public ResultVo addfrend(@PathVariable("fuserid") String fuserid,HttpSession session){
String userid = (String)session.getAttribute("userid");
if(userid.equals(fuserid)){
//不能对自己的商品感兴趣
return new ResultVo(false, StatusCode.ERROR,"不能对自己的商品感兴趣");
}
Friends friends=new Friends().setUserid(userid).setFuserid(fuserid);
Integer integer = friendsService.JustTwoUserIsFriend(friends);
if(integer==null){
//如果不存在好友关系插入好友关系
friendsService.insertFriend(friends);
friendsService.insertFriend(new Friends().setFuserid(userid).setUserid(fuserid));
}
return new ResultVo(false, StatusCode.OK,"正在跳转到聊天界面");
/**
* @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
* 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
* @ServerEndpoint 可以把当前类变成websocket服务类
*/
@Controller
@ServerEndpoint(value = "/websocket/{userno}")
public class ChatWebSocket {
// 这里使用静态,让 service 属于类
private static ChatmsgService chatMsgService;
private static UserInfoService mineService;
// 注入的时候,给类的 service 注入
@Autowired
public void setChatService(ChatmsgService chatService,UserInfoService mineService) {
ChatWebSocket.chatMsgService = chatService;
ChatWebSocket.mineService=mineService;
}
//注入通知类
@Autowired
private NoticesService noticesService;
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
private static ConcurrentHashMap<String, ChatWebSocket> webSocketSet = new ConcurrentHashMap<String, ChatWebSocket>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session WebSocketsession;
//当前发消息的人员编号
private String userno = "";
/**
* 连接建立成功调用的方法
*
* session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据