Merge remote-tracking branch 'origin/master'

This commit is contained in:
2023-12-22 21:52:47 +08:00
28 changed files with 1065 additions and 76 deletions

View File

@@ -0,0 +1,30 @@
package com.lovenav.controller;
import com.alibaba.fastjson2.JSONObject;
import com.lovenav.dao.AuthDao;
import com.lovenav.entity.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
@RestController
@RequestMapping("/Auth")
public class AuthController {
@Autowired
AuthDao authDao;
@RequestMapping("/retAllAuth")
public String retAllAuth(){
List<Auth> auths = authDao.selectAllAuth();
HashMap<String, Object> result = new HashMap<>();
result.put("code", 200);
result.put("msg", "查询结果");
result.put("data",auths);
String jsonString = JSONObject.toJSONString(result);
return jsonString;
}
}

View File

@@ -0,0 +1,40 @@
package com.lovenav.controller;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.lovenav.entity.Banners;
import com.lovenav.service.BannersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/banners")
public class BannersController {
@Autowired
private BannersService bannersService;
// 跳转链接
@RequestMapping(method = RequestMethod.GET, value = "/jump_url")
public String jump(int id){
return bannersService.Jump_url(id);
}
// 添加banner
@RequestMapping(method = RequestMethod.POST, value = "/add_banner")
public String add(@RequestBody Banners banners){
return bannersService.Add_banner(banners);
}
// 删除banner
@RequestMapping(method = RequestMethod.GET, value = "/delete_url")
public String delete(int id){
return bannersService.Delete_banner(id);
}
// 首页显示banner
@RequestMapping(method = RequestMethod.GET, value = "/view_banner")
public String view(){
return bannersService.View_banner();
}
}

View File

@@ -21,15 +21,15 @@ public class CommentController {
@Autowired
private CommentService commentService;
// 评论功能
@RequestMapping(method = RequestMethod.POST, value = "/reply_comment")
@RequestMapping(method = RequestMethod.POST, value = "/comment")
public String Reply1(@RequestBody Comment comment){
return commentService.Reply1(comment);
}
// 回复功能
@RequestMapping(method = RequestMethod.POST, value = "/comment")
public String Reply2(@RequestBody Comment comment){
return commentService.Reply2(comment);
@RequestMapping(method = RequestMethod.POST, value = "/reply_comment")
public String Reply2(@RequestBody Comment comment,int id){
return commentService.Reply2(comment,id);
}
// 删除功能
@RequestMapping(method = RequestMethod.GET, value = "/delete_comment")
@@ -40,4 +40,16 @@ public class CommentController {
public String addLikeCount(int id){
return commentService.AddLikeCount(id);
}
// 显示评论
@RequestMapping(method = RequestMethod.GET, value = "/view_comment")
public String View_comment(){
return commentService.View_comment();
}
// 显示回复
@RequestMapping(method = RequestMethod.GET, value = "/view_reply")
public String View_reply(int id){
return commentService.View_Reply(id);
}
}

View File

@@ -0,0 +1,27 @@
package com.lovenav.controller;
import com.alibaba.fastjson.JSON;
import com.lovenav.utils.QRCodeUtil;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class QRCodeController {
private QRCodeUtil qrCodeUtil;
@RequestMapping(method = RequestMethod.GET, value = "/qrc")
public String QRCode(String url){
String text = url;
String logoPath ="src/main/resources/static/logo/NAV.png";
String destPath = "src/main/resources/static/qr";
try {
String url2 = qrCodeUtil.encode(text, logoPath, destPath, true);
String base64 = qrCodeUtil.getBase64(url2);
return JSON.toJSONString(base64);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

View File

@@ -13,6 +13,7 @@ import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@@ -42,6 +43,7 @@ public class SearchController {
redisService.addSearchHistoryByUserId(userId, searchKey);
redisService.incrementScoreByUserId(searchKey);
redisService.incrementScore(searchKey);
//返回网站数据
@@ -67,15 +69,41 @@ public class SearchController {
@RequestMapping("/getSearchHistoryByUserId")
public String getSearchHistoryByUserId(String userId)
{
String res = "123";
return res;
List<String> stringList = redisService.getSearchHistoryByUserId(userId);
HashMap<String, Object> result = new HashMap<>();
result.put("code", 200);
result.put("msg", "查询成功");
result.put("data",stringList);
String jsonString = JSONObject.toJSONString(result);
return jsonString;
}
/**
* 删除个人历史数据
*/
@RequestMapping("/delSearchHistoryByUserId")
public String delSearchHistoryByUserId(String userId, String searchKey){
String res = "123";
return res;
Long f = redisService.delSearchHistoryByUserId(userId,searchKey);
HashMap<String, Object> result = new HashMap<>();
result.put("code", 200);
result.put("msg", "删除结果");
result.put("data",f);
String jsonString = JSONObject.toJSONString(result);
return jsonString;
}
/**
* 根据searchKey搜索其相关最热的前十名 (如果searchKey为null空则返回redis存储的前十最热词条)
*/
@RequestMapping("/getHotList")
public String getHotList(String searchKey){
List<String> stringList = redisService.getHotList(searchKey);
HashMap<String, Object> result = new HashMap<>();
result.put("code", 200);
result.put("msg", "查询结果");
result.put("data",stringList);
String jsonString = JSONObject.toJSONString(result);
return jsonString;
}
}

View File

@@ -1,5 +1,7 @@
package com.lovenav.controller;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
@@ -10,15 +12,20 @@ import com.lovenav.entity.UrlList;
import com.lovenav.service.UrlCateListService;
import com.lovenav.service.UrlListService;
import com.lovenav.vo.CateAndUrl;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.io.*;
@RestController
@RequestMapping("/UrlAndCate")
public class UrlAndCateController {
@@ -43,6 +50,7 @@ public class UrlAndCateController {
try {
JsonNode rootNode = objectMapper.readTree(data2);
disposeBookmarkFunction1(rootNode,"top",email);
countCateContainUrlNumber(email);
HashMap<String, Object> result = new HashMap<>();
result.put("code", 200);
result.put("msg", "查询成功");
@@ -80,9 +88,9 @@ public class UrlAndCateController {
//处理成JSON
@RequestMapping("/disposeBookmarkToJson")
public String disposeBookmarkToJson(Integer userId)
public String disposeBookmarkToJson(String userId)
{
List<UrlCateList> urlCateLists = urlCateListService.selectUrListByUserId(userId);
List<UrlCateList> urlCateLists = urlCateListService.selectUrListByUserId(Integer.valueOf(userId));
List<UrlList> urlLists = urlListService.selectUrList();
List<CateAndUrl> cateAndUrlList = new ArrayList<>();
@@ -185,4 +193,90 @@ public class UrlAndCateController {
String jsonString = JSONObject.toJSONString(result);
return jsonString;
}
public String countCateContainUrlNumber(String email){
HashMap<String, Object> result = new HashMap<>();
result.put("code", 200);
result.put("msg", "查询成功");
result.put("data",urlCateListService.countCateContainUrlNumber(email));
String jsonString = JSONObject.toJSONString(result);
return jsonString;
}
//处理成JSON
// @RequestMapping("/disposeJsonToExcel")
// public String disposeJsonToExcel(String userId)
// {
//
// HashMap<String, Object> result = new HashMap<>();
// result.put("code", 200);
// result.put("msg", "查询成功");
// result.put("data",urlCateListService.getUrl(userId));
// String jsonString = JSONObject.toJSONString(result);
// return jsonString;
// }
/**
* json 转 excel
* @param jsonArray
* @return
* @throws IOException
*/
public HSSFWorkbook jsonToExcel(JSONArray jsonArray) throws IOException {
Set<String> keys = new HashSet<>();
// 创建HSSFWorkbook对象
HSSFWorkbook wb = new HSSFWorkbook();
// 创建HSSFSheet对象
HSSFSheet sheet = wb.createSheet("sheet0");
List<JSONObject> jsonObjects = jsonArray.toList(JSONObject.class);
// 创建HSSFRow对象
HSSFRow row ;
for (int i=0;i<jsonObjects.size();i++){
String temp = jsonObjects.get(i).keySet().toString();
String target = temp.substring(1,temp.length()-1);
keys.add(target);
}
for( int i =0 ;i<jsonObjects.size(); i++)
{
row = sheet.createRow(i);
HSSFCell cell = row.createCell(0);
String temp = jsonObjects.get(i).keySet().toString();
String target = temp.substring(1,temp.length()-1);
String target1 = temp.substring(2,temp.length()-2);
cell.setCellValue(target1);
cell = row.createCell(1);
cell.setCellValue(jsonObjects.get(i).get(target).toString().substring(2,temp.length()-2));
}
return wb;
}
@RequestMapping ("/dataDownload/excel")
@ResponseBody
public String exportExcel(String userId, HttpServletResponse response) {
try {
//此处为你的json数组
HSSFWorkbook sheets = jsonToExcel(urlCateListService.getUrl(userId));
// 配置文件下载
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
// 下载文件能正常显示中文
response.setHeader("Content-Disposition", "attachment;filename=data.xls");
OutputStream os = response.getOutputStream();
sheets.write(os);
sheets.close();
os.close();
return null;
} catch (Exception e) {
e.printStackTrace();
HashMap<String, Object> result = new HashMap<>();
result.put("code", 500);
result.put("msg", "下载失败");
return JSON.toJSONString(result);
}
}
}

View File

@@ -1,9 +1,13 @@
package com.lovenav.dao;
import com.lovenav.entity.Auth;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
@Mapper
public interface AuthDao {
int deleteByPrimaryKey(Integer id);
@@ -16,4 +20,6 @@ public interface AuthDao {
int updateByPrimaryKeySelective(Auth record);
int updateByPrimaryKey(Auth record);
List<Auth> selectAllAuth();
}

View File

@@ -1,9 +1,13 @@
package com.lovenav.dao;
import com.lovenav.entity.Banners;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
@Mapper
public interface BannersDao {
int deleteByPrimaryKey(Integer id);
@@ -16,4 +20,6 @@ public interface BannersDao {
int updateByPrimaryKeySelective(Banners record);
int updateByPrimaryKey(Banners record);
List<Banners> selectByAllBanners();
}

View File

@@ -2,7 +2,7 @@ package com.lovenav.dao;
import com.lovenav.entity.CollectIconList;
import org.springframework.stereotype.Repository;
//dao
@Repository
public interface CollectIconListDao {
int deleteByPrimaryKey(Long id);

View File

@@ -22,5 +22,7 @@ public interface CommentDao {
int updateByPrimaryKey(Comment record);
List<Integer> selectByRootId(Integer rootid);
List<Comment> selectByAllComment();
List<Comment> selectByAllReply(int id);
}

View File

@@ -2,6 +2,9 @@ package com.lovenav.entity;
import java.io.Serializable;
import java.util.Date;
import com.alibaba.fastjson2.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
/**
@@ -9,6 +12,57 @@ import lombok.Data;
*/
@Data
public class Banners implements Serializable {
public Banners(){
this.bannerStatus = 0;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public Integer getWeigh() {
return weigh;
}
public void setWeigh(Integer weigh) {
this.weigh = weigh;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Byte getBannerStatus() {
return bannerStatus;
}
public void setBannerStatus(Byte bannerStatus) {
this.bannerStatus = bannerStatus;
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
/**
* id
*/

View File

@@ -4,6 +4,7 @@ import java.io.Serializable;
import lombok.Data;
/**
* Entity
* 图标表
* ln_collect_icon_list
*/
@@ -12,14 +13,71 @@ public class CollectIconList implements Serializable {
private Long id;
/**
* 网址
* 网址id
*/
private String urlMd5;
private String url_id;
/**
* 图片地址
*/
private String iconUrl;
private String icon_url;
/**
* 二维码地址
*/
private String qr_url;
/**
* 状态
*/
private Integer status;
private static final long serialVersionUID = 1L;
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
CollectIconList other = (CollectIconList) that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
&& (this.getUrl_id() == null ? other.getUrl_id() == null : this.getUrl_id().equals(other.getUrl_id()))
&& (this.getIcon_url() == null ? other.getIcon_url() == null : this.getIcon_url().equals(other.getIcon_url()))
&& (this.getQr_url() == null ? other.getQr_url() == null : this.getQr_url().equals(other.getQr_url()))
&& (this.getStatus() == null ? other.getStatus() == null : this.getStatus().equals(other.getStatus()));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
result = prime * result + ((getUrl_id() == null) ? 0 : getUrl_id().hashCode());
result = prime * result + ((getIcon_url() == null) ? 0 : getIcon_url().hashCode());
result = prime * result + ((getQr_url() == null) ? 0 : getQr_url().hashCode());
result = prime * result + ((getStatus() == null) ? 0 : getStatus().hashCode());
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", url_id=").append(url_id);
sb.append(", icon_url=").append(icon_url);
sb.append(", qr_url=").append(qr_url);
sb.append(", status=").append(status);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}

View File

@@ -0,0 +1,14 @@
package com.lovenav.service;
import com.lovenav.entity.Banners;
public interface BannersService {
// 跳转链接
String Jump_url(int id);
// 添加banner
String Add_banner(Banners banners);
// 删除banner
String Delete_banner(int id);
// 展示banner
String View_banner();
}

View File

@@ -10,7 +10,11 @@ public interface CommentService {
// 评论
String Reply1(Comment comment);
// 回复
String Reply2(Comment comment);
String Reply2(Comment comment,int id);
// 删除
String Delete(int id);
// 显示评论
String View_comment();
// 显示回复
String View_Reply(int id);
}

View File

@@ -1,5 +1,6 @@
package com.lovenav.service;
import com.alibaba.fastjson2.JSONArray;
import com.lovenav.entity.UrlCateList;
import java.util.List;
@@ -9,4 +10,8 @@ public interface UrlCateListService {
public int selectAndInsertUrlCate(String email , String cateName , String parent);
public List<UrlCateList> selectUrListByUserId(Integer userId);
public String countCateContainUrlNumber(String userId);
public JSONArray getUrl(String userId);
}

View File

@@ -0,0 +1,67 @@
package com.lovenav.service.serviceImpl;
import com.alibaba.fastjson.JSON;
import com.lovenav.dao.BannersDao;
import com.lovenav.entity.Banners;
import com.lovenav.service.BannersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.HashMap;
@Service
public class BannersServiceImpl implements BannersService {
@Autowired
private BannersDao bannersDao;
// 跳转链接
@Override
public String Jump_url(int id){
Banners banners = bannersDao.selectByPrimaryKey(id);
HashMap<String, Object> hashMap = new HashMap<>();
if(banners != null){
hashMap.put("url",banners.getUrl());
}else{
hashMap.put("code",500);
hashMap.put("msg","找不到指定链接");
}
return JSON.toJSONString(hashMap);
}
// 添加banner
@Override
public String Add_banner(Banners banners) {
int result = bannersDao.insert(banners);
HashMap<String, Object> hashMap = new HashMap<>();
if(result>0){
return JSON.toJSONString(banners);
}else{
hashMap.put("code",500);
hashMap.put("msg","添加banner失败");
return JSON.toJSONString(hashMap);
}
}
// 删除banner
@Override
public String Delete_banner(int id){
int result = bannersDao.deleteByPrimaryKey(id);
HashMap<String, Object> hashMap = new HashMap<>();
if(result>0){
hashMap.put("code",200);
hashMap.put("msg","删除成功");
return JSON.toJSONString(hashMap);
}else{
hashMap.put("code",500);
hashMap.put("msg","删除失败");
return JSON.toJSONString(hashMap);
}
}
// 展示banner
@Override
public String View_banner(){
List<Banners> list = bannersDao.selectByAllBanners();
return JSON.toJSONString(list);
}
}

View File

@@ -3,6 +3,7 @@ package com.lovenav.service.serviceImpl;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.lovenav.dao.CommentDao;
import com.lovenav.dao.UserDao;
import com.lovenav.entity.Comment;
import com.lovenav.service.CommentService;
import org.apache.ibatis.jdbc.Null;
@@ -13,10 +14,12 @@ import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
@Service("commentService")
@Service
public class CommentServiceImpl implements CommentService {
@Autowired
private CommentDao commentDao;
@Autowired
private UserDao userDao;
// 评论功能
@Override
public String Reply1(Comment comment){
@@ -32,18 +35,11 @@ public class CommentServiceImpl implements CommentService {
}
// 回复功能
@Override
public String Reply2(Comment comment){
List<Integer> list = commentDao.selectByRootId(comment.getRootCommentId());
if(list.size()<5){
commentDao.insert(comment);
return JSON.toJSONString(comment);
}else{
HashMap<String, Object> result = new HashMap<>();
result.put("code", 500);
result.put("msg", "回复超过上限");
String jsonString = JSONObject.toJSONString(result);
return JSON.toJSONString(result);
}
public String Reply2(Comment comment,int id){
String name = (userDao.selectByPrimaryKey(id)).getNickname();
HashMap<Comment,String> hashMap = new HashMap<>();
hashMap.put(comment, name);
return JSON.toJSONString(hashMap);
}
// 删除
@Override
@@ -67,7 +63,19 @@ public class CommentServiceImpl implements CommentService {
comment.setLikeCount(comment.getLikeCount()+1);
commentDao.updateByPrimaryKeySelective(comment);
HashMap<String, Long> hashMap = new HashMap<>();
hashMap.put("点赞成功:",comment.getLikeCount());
hashMap.put("点赞成功",comment.getLikeCount());
return JSON.toJSONString(hashMap);
}
// 显示评论
public String View_comment(){
List<Comment> list = commentDao.selectByAllComment();
return JSON.toJSONString(list);
}
// 显示回复
public String View_Reply(int id){
List<Comment> list = commentDao.selectByAllReply(id);
return JSON.toJSONString(list);
}
}

View File

@@ -1,16 +1,19 @@
package com.lovenav.service.serviceImpl;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.lovenav.dao.UrlCateListDao;
import com.lovenav.dao.UrlListDao;
import com.lovenav.dao.UserDao;
import com.lovenav.entity.UrlCateList;
import com.lovenav.entity.UrlList;
import com.lovenav.entity.User;
import com.lovenav.service.UrlCateListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import java.util.*;
@Transactional
@Service("urlCateListService")
@@ -20,7 +23,8 @@ public class UrlCateListServiceImpl implements UrlCateListService {
@Autowired
UrlCateListDao urlCateListDao;
@Autowired
UrlListDao urlListDao;
@Autowired
UserDao userDao;
public int selectAndInsertUrlCate(String email , String cateName , String parent )
@@ -53,4 +57,75 @@ public class UrlCateListServiceImpl implements UrlCateListService {
public List<UrlCateList> selectUrListByUserId(Integer userId){
return urlCateListDao.selectUrListByUserId(userId);
}
public String countCateContainUrlNumber(String email){
User user = userDao.selectByEmail(email);
int userId = user.getId();
List<UrlCateList> urlCateLists =urlCateListDao.selectUrListByUserId(userId);
List<UrlList> urlLists = urlListDao.selectUrList();
HashMap<String,Integer> CateNumber = new HashMap<>();
for(UrlCateList urlCateList :urlCateLists)
{
CateNumber.put(urlCateList.getName(),0);
}
for(UrlList urlList : urlLists){
Long id = Long.valueOf(urlList.getCateId());
while(id!= 0)
{
for(UrlCateList urlCateList :urlCateLists)
{
if(id == Long.valueOf(urlCateList.getId())){
int cateNum = CateNumber.get(urlCateList.getName())+1;
CateNumber.put(urlCateList.getName(),cateNum);
id=Long.valueOf(urlCateList.getRootCateId());
break;
}
}
}
}
Iterator iterator = CateNumber.entrySet().iterator();
while(iterator.hasNext()) {
Map.Entry<String, Integer> entry=(Map.Entry<String, Integer>) iterator.next();
for(int i = 0; i<urlCateLists.size();i++)
{
UrlCateList urlCateList = urlCateLists.get(i);
if(urlCateList.getName().equals(entry.getKey()))
{
urlCateList.setUrlNumber(Long.valueOf(entry.getValue()));
urlCateListDao.updateByPrimaryKeySelective(urlCateList);
break;
}
}
}
return CateNumber.toString();
}
public JSONArray getUrl(String userId)
{
List<UrlCateList> urlCateLists =urlCateListDao.selectUrListByUserId(Integer.valueOf(userId));
List<UrlList> urlLists = urlListDao.selectUrList();
JSONArray jsonArray = new JSONArray();
for(UrlCateList urlCateList : urlCateLists)
{
int parentId = urlCateList.getId();
for(UrlList urlList : urlLists)
{
if(urlList.getCateId() == parentId)
{
JSONObject jsonObject = new JSONObject();
jsonObject.put(urlList.getName(),urlList.getUrl());
jsonArray.add(jsonObject);
break;
}
}
}
return jsonArray;
}
}

View File

@@ -0,0 +1,374 @@
package com.lovenav.utils;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.tomcat.util.codec.binary.Base64;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Random;
public class QRCodeUtil {
private static final String CHARSET = "utf-8";
private static final String FORMAT_NAME = "JPG";
// 二维码尺寸
private static final int QRCODE_SIZE = 300;
// LOGO宽度
private static final int WIDTH = 60;
// LOGO高度
private static final int HEIGHT = 60;
private static BufferedImage createImage(String content, String imgPath,
boolean needCompress) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000
: 0xFFFFFFFF);
}
}
if (imgPath == null || "".equals(imgPath)) {
return image;
}
// 插入图片
QRCodeUtil.insertImage(image, imgPath, needCompress);
return image;
}
/**
* 插入LOGO
*
* @param source
* 二维码图片
* @param imgPath
* LOGO图片地址
* @param needCompress
* 是否压缩
* @throws Exception
*/
private static void insertImage(BufferedImage source, String imgPath,
boolean needCompress) throws Exception {
File file = new File(imgPath);
if (!file.exists()) {
System.err.println(""+imgPath+" 该文件不存在!");
return;
}
Image src = ImageIO.read(new File(imgPath));
int width = src.getWidth(null);
int height = src.getHeight(null);
if (needCompress) { // 压缩LOGO
if (width > WIDTH) {
width = WIDTH;
}
if (height > HEIGHT) {
height = HEIGHT;
}
Image image = src.getScaledInstance(width, height,
Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
src = image;
}
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (QRCODE_SIZE - width) / 2;
int y = (QRCODE_SIZE - height) / 2;
graph.drawImage(src, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}
/**
* 生成二维码(内嵌LOGO)
*
* @param content
* 内容
* @param imgPath
* LOGO地址
* @param destPath
* 存放目录
* @param needCompress
* 是否压缩LOGO
* @throws Exception
*/
public static String encode(String content, String imgPath, String destPath,
boolean needCompress) throws Exception {
BufferedImage image = QRCodeUtil.createImage(content, imgPath,
needCompress);
mkdirs(destPath);
String file = new Random().nextInt(99999999)+".jpg";
ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));
return destPath+"/"+file;
}
/**
* 当文件夹不存在时mkdirs会自动创建多层目录区别于mkdir(mkdir如果父目录不存在则会抛出异常)
* @param destPath 存放目录
*/
public static void mkdirs(String destPath) {
File file =new File(destPath);
//当文件夹不存在时mkdirs会自动创建多层目录区别于mkdir(mkdir如果父目录不存在则会抛出异常)
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}
/**
* 生成二维码(内嵌LOGO)
*
* @param content
* 内容
* @param imgPath
* LOGO地址
* @param destPath
* 存储地址
* @throws Exception
*/
public static void encode(String content, String imgPath, String destPath)
throws Exception {
QRCodeUtil.encode(content, imgPath, destPath, false);
}
/**
* 生成二维码
*
* @param content
* 内容
* @param destPath
* 存储地址
* @param needCompress
* 是否压缩LOGO
* @throws Exception
*/
public static void encode(String content, String destPath,
boolean needCompress) throws Exception {
QRCodeUtil.encode(content, null, destPath, needCompress);
}
/**
* 生成二维码
*
* @param content
* 内容
* @param destPath
* 存储地址
* @throws Exception
*/
public static void encode(String content, String destPath) throws Exception {
QRCodeUtil.encode(content, null, destPath, false);
}
/**
* 生成二维码(内嵌LOGO)
*
* @param content
* 内容
* @param imgPath
* LOGO地址
* @param output
* 输出流
* @param needCompress
* 是否压缩LOGO
* @throws Exception
*/
public static void encode(String content, String imgPath,
OutputStream output, boolean needCompress) throws Exception {
BufferedImage image = QRCodeUtil.createImage(content, imgPath,
needCompress);
ImageIO.write(image, FORMAT_NAME, output);
}
/**
* 生成二维码
*
* @param content
* 内容
* @param output
* 输出流
* @throws Exception
*/
public static void encode(String content, OutputStream output)
throws Exception {
QRCodeUtil.encode(content, null, output, false);
}
/**
* 解析二维码
*
* @param file
* 二维码图片
* @return
* @throws Exception
*/
public static String decode(File file) throws Exception {
BufferedImage image;
image = ImageIO.read(file);
if (image == null) {
return null;
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(
image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
return resultStr;
}
/**
* 解析二维码
*
* @param path
* 二维码图片地址
* @return
* @throws Exception
*/
public static String decode(String path) throws Exception {
return QRCodeUtil.decode(new File(path));
}
/**
*
* @param content
* @param imgPath
* @param destPath
* @param localUrl 当前环境的域名或者ip地址
* @param needCompress
* @return
* @throws Exception
*/
public static String encode(String content, String imgPath, String destPath,String localUrl,
boolean needCompress) throws Exception {
BufferedImage image = QRCodeUtil.createImage(content, imgPath,
needCompress);
mkdirs(destPath);
String file = new Random().nextInt(99999999)+".jpg";
ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));
return localUrl+file;
}
public static String encodeDZ(String content, String imgPath, String destPath,String localUrl,int length,int width,
boolean needCompress) throws Exception {
BufferedImage image = QRCodeUtil.createImageDZ(content, imgPath,length,width,
needCompress);
mkdirs(destPath);
String file = new Random().nextInt(99999999)+".jpg";
ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));
return localUrl+file;
}
private static BufferedImage createImageDZ(String content, String imgPath,int newlength,int newWidth,
boolean needCompress) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, newlength, newWidth, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000
: 0xFFFFFFFF);
}
}
if (imgPath == null || "".equals(imgPath)) {
return image;
}
// 插入图片
QRCodeUtil.insertImage(image, imgPath, needCompress);
return image;
}
public static void main(String[] args) throws Exception {
String text = "https://www.baidu.com"; //这里设置自定义网站url
String logoPath ="src/main/resources/static/logo/NAV.png";
String destPath = "src/main/resources/static/qr";
String url=QRCodeUtil.encode(text, logoPath, destPath, true);
System.out.println(url);
/* String file="D:\\11.jpg";
String info=QRCodeUtil.decode(file);
System.out.println(info);*/
}
/**
* 将图片url转换成base64流
* @param url
* @return
*/
public String getBase64(String url){
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); //设置字符集编码类型
hints.put(EncodeHintType.MARGIN, 1); //设置白边
BitMatrix bitMatrix = null;
try {
bitMatrix = multiFormatWriter.encode(url, BarcodeFormat.QR_CODE, 300, 300,hints);
BufferedImage image = toBufferedImage(bitMatrix);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//输出二维码图片流
try {
ImageIO.write(image, "jpg",outputStream);
String base = new Base64().encodeAsString(outputStream.toByteArray());
// new Base64().encode(outputStream.toByteArray());
return base;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (WriterException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return null;
}
public static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);//0xFF000000黑0xFFFFFFFF白
}
}
return image;
}
}

View File

@@ -17,7 +17,7 @@ public class RandomValidateCode {
private Random random = new Random();
private String randString = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生的字符串
private int width = 80;// 图片宽度
private int height = 26;// 图片高度
private int height = 36;// 图片高度
private int lineSize = 40;// 干扰线数量
private int stringNum = 4;// 随机产生的字符数量
@@ -25,7 +25,7 @@ public class RandomValidateCode {
* 获得字体
*/
private Font getFont() {
return new Font("Fixedsys", Font.CENTER_BASELINE, 18);
return new Font("Fixedsys", Font.CENTER_BASELINE, 20);
}
/**