开源项目学习-Favorites-Web

开源SpringBoot项目

  • 作者团队:纯洁的微笑
  • 作者个人网站:http://www.ityouknow.com/
  • 项目github:https://gitee.com/ityouknow/favorites-web?_from=gitee_search    (国内的github)

一、IDEA创建工程

  • springboot工程初始化
  • 初始化配置
  • 测试

1. IDEA初始化springboot

问题一:页面跳转

  • @RestController
  • @Controller
  • @ResponseBody

三者之间的灵活使用

问题二:webjars管理前端资源

  • 引入webjars-locator
  • 在页面中引入前端资源

Hibernate中定义的Entity类(无论是JPA实现,还是Hibernate Native实现),都必须有一个无参数的构造函数。

问题三:ajax中网页的跳转

  • window.location.href = "/index"     无法传递session  相当于重定向
  • window.open("/index",'_self')      用法注意

问题四:template下子目录下模板的放行

  • spring security

二、功能分析

1. 用户模块

1) 注册用户

  • 判断邮箱与用户名是否存在,若存在则返回"邮箱与用户名已存在信息",即注册不成功信息
  • 获取注册用户必需信息:邮箱、用户名、密码、创建时间(当前时间)、最新修改时间(当前时间)、个人图像(默认:img/favicon.png)
  • 添加默认收藏夹:f_count=0、f_public_count=10
  • 添加默认属性设置:c_default_model="simple"、c_defaut_collect_type="public"
1 查询用户邮箱是否存在
User registUser = userRepository.findByEmail(user.getEmail());
select * from user u where u.u_email = ?

2 查询用户名是否存在
User userNameUser = userRepository.findByUserName(user.getUserName());
select * from user u where u.u_name = ?

3 注册用户
userRepository.save(user);
insert into user u (u.u_name,u.u_email,u.u_profile_picture,u.u_introduction,u.u_create_time,u.u_last_modify_time,u.u_out_date,u.u_validata_code,u.u_background_picture) values(?,?,?,?,?,?,?,?,?,?)

4 默认收藏文件夹创建
Favorites favorites = favoritesService.saveFavorites(user.getId(), "未读列表");
insert into favorites(f_userId,f_name,f_count,f_create_time,f_last_modify_time,
f_public_name) values (?, ?, ?, ?, ?, ?)

5 默认属性配置的创建
configService.saveConfig(user.getId(),String.valueOf(favorites.getId()));
insert into config (c_user_id,c_default_favorties,c_default_collect_type,  c_default_model,c_create_time, c_last_modify_time) values (?, ?, ?, ?, ?, ?)

2) 登录功能

  • 使用用户名或者邮箱进行登录
  • 保存cookie信息
  • 返回的preUrl,第一登录时,preUrl="/"
  • 获取收藏的数量
  • 获取配置信息
  • 获取收藏夹信息
  • 获取关注信息
1. 查询用户名或邮箱是否存在
User loginUser = userRepository.findByUserNameOrEmail(user.getUserName(), user.getUserName());
select * from user u where u.u_name = ? or u.u_name = ?

2. 获取收藏数量信息
long size= collectRepository.countByUserIdAndIsDelete(getUserId(),IsDelete.NO);
select count(co.id) as count from collec co where co.co_userId=? and co.co_is_delete=?

3. 收藏夹信息
Favorites favorites = favoritesRepository.findById(Long.parseLong(config.getDefaultFavorties()));
select f.f_id as id, f.f_count as count, f.f_create_time as create_t, f.f_last_modify_time as last_mod, f.f_name as name, f.f_public_count as public, f.f_userId as user_id from favorites f where f.f_id=?

4. 属性配置信息
Config config = configRepository.findByUserId(getUserId());
select c.c_.id as id, c.c_create_time as create_t, c.c_default_collect_type as default, c.c_default_favorties as default_4_3 c.c_default_model as default_5_3, c.c_last_modify_time as last_mod, c.c_userId as user_id from config c where c.c_userId=?

5. 获取关注者的用户名,用List存储
List followList = followRepository.findByUserId(getUserId());
select u.userName from Follow f ,User u  where f.userId=:userId and f.followId = u.id and f.status = 'FOLLOW'

2. home页面功能分析

1) 导航功能分析

 

------------------------------左边Favorites分析-------------------------------------

                url:href="/index" 

1. 获取收藏的相关信息
IndexCollectorView indexCollectorView = collectorService.getCollectors();


IndexCollectorView indexCollectorView = new IndexCollectorView();
try {
    // 收藏文章最多的用户
    long mostCollectUser = collectorRepository.getMostCollectUser();
    indexCollectorView.setMostCollectUser(userRepository.findById(mostCollectUser));
    
    // 被关注最多的用户    
    long mostFollowedUser = collectorRepository.getMostFollowedUser(mostCollectUser);
    indexCollectorView.setMostFollowedUser(userRepository.findById(mostFollowedUser));
    
    // 文章被赞最多的用户
    String notUserIds = mostCollectUser+","+mostFollowedUser;
    long mostPraisedUser = collectorRepository.getMostPraisedUser(notUserIds);
    indexCollectorView.setMostPraisedUser(userRepository.findById(mostPraisedUser));
    
    // 被评论最多的用户
    notUserIds += ","+mostPraisedUser;
    long mostCommentedUser = collectorRepository.getMostCommentedUser(notUserIds);
    indexCollectorView.setMostCommentedUser(userRepository.findById(mostCommentedUser));
    
    // 最受欢迎的用户
    notUserIds += ","+ mostCommentedUser;
    long mostPopularUser = collectorRepository.getMostPopularUser(notUserIds);
    indexCollectorView.setMostPopularUser(userRepository.findById(mostPopularUser));
    
    // 近一个月最活跃用户
    notUserIds += ","+ mostPopularUser;
    long mostActiveUser = collectorRepository.getMostActiveUser(notUserIds);
    indexCollectorView.setMostActiveUser(userRepository.findById(mostActiveUser));
}catch (Exception e){
    logger.info("错误",e);
}
return indexCollectorView;


sql:
// 收藏文章最多的用户
String querySql = "SELECT c.user_id ,COUNT(1) AS counts FROM collect c WHERE type='PUBLIC' AND is_delete='NO' GROUP BY c.user_id ORDER BY counts DESC LIMIT 1";


// 被关注最多的用户
String querySql = "SELECT follow_id,COUNT(1) AS counts FROM follow \n" +
        "WHERE status='FOLLOW' and follow_id != " + notUserId +
        " GROUP BY follow_id ORDER BY counts DESC LIMIT 1";

// 被赞的最多的用户
String querySql = "SELECT c.user_id,SUM(p.counts) as counts FROM collect c LEFT JOIN \n" +
        "(SELECT collect_id,COUNT(1) as counts FROM praise GROUP BY collect_id)p \n" +
        "ON c.id=p.collect_id WHERE c.type='PUBLIC' AND c.is_delete='NO' AND c.user_id NOT IN (" + notUserIds +") \n" +
        "GROUP BY c.user_id ORDER BY counts DESC LIMIT 1";

// 被评论最多的用户
String querySql="SELECT c.user_id,SUM(p.counts) as counts FROM collect c LEFT JOIN \n" +
        "(SELECT collect_id,COUNT(1) as counts FROM `comment` GROUP BY collect_id)p \n" +
        "ON c.id=p.collect_id WHERE c.type='PUBLIC' AND c.is_delete='NO' AND c.user_id NOT IN (" + notUserIds +") \n" +
        "GROUP BY c.user_id ORDER BY counts DESC LIMIT 1";

// 最受欢迎的用户
String querySql = "SELECT u.user_id,SUM(u.counts) as counts FROM\n" +
        "(SELECT c.user_id,COUNT(1) as counts FROM collect c LEFT JOIN notice n ON c.id=n.collect_id WHERE c.type='PUBLIC' AND c.is_delete='NO' GROUP BY c.user_id\n" +
        "UNION ALL\n" +
        "SELECT follow_id,COUNT(1) AS counts FROM follow GROUP BY follow_id)u\n" +
        "WHERE u.user_id NOT IN (" + notUserIds + ")\n" +
        "GROUP BY u.user_id ORDER BY counts DESC LIMIT 1";

// 近一个月最活跃的用户
String querySql = "SELECT u.user_id,SUM(u.counts) as counts FROM\n" +
        "(SELECT user_id,COUNT(1) as counts FROM collect WHERE create_time>" + lastMonth + " AND create_time<" + nowTime + " AND type='PUBLIC' AND is_delete='NO' GROUP BY user_id\n" +
        "UNION ALL\n" +
        "SELECT user_id,COUNT(1) as counts FROM `comment` WHERE create_time>" + lastMonth + " AND create_time<" + nowTime + " GROUP BY user_id\n" +
        "UNION ALL\n" +
        "SELECT user_id,COUNT(1) as counts FROM praise WHERE create_time>" + lastMonth + " AND create_time<" + nowTime + " GROUP BY user_id\n" +
        "UNION ALL\n" +
        "SELECT user_id,COUNT(1) as counts FROM follow WHERE create_time>" + lastMonth + " AND create_time<" + nowTime + " GROUP BY user_id)u\n" +
        "WHERE u.user_id NOT IN (" + notUserIds + ")\n" +
        "GROUP BY u.user_id ORDER BY counts DESC LIMIT 1";

------------------------------伸缩栏-----------------------------------

-------------------------------导航栏右边----------------------------

1. 瞅   href = "/lookAround"

1. 获取分页信息
Pageable pageable = PageRequest.of(page, size,Sort.by(Sort.Direction.DESC, "id"));

2. 传递type参数
model.addAttribute("type", "lookAround");

3. 探索发现日志
List collects 
=lookAroundService.queryCollectExplore(pageable,getUserId(),null);

4. 向前端传递各种信息
model.addAttribute("user",user);
model.addAttribute("collects", collects);
model.addAttribute("userId", getUserId());
model.addAttribute("size", collects.size());

5. 转到前端  lookAround/standard

2. 搜索

1. 搜索图标

2. 搜索url-----locationUrl('/search/'+key,"");

3. @RequestMapping(value="/search/{key}")

4. 向前端传递的参数
Pageable pageable = PageRequest.of(page, size,Sort.by(Direction.DESC,"id"));
List myCollects=collectService.searchMy(getUserId(),key ,pageable);
List otherCollects=collectService.searchOther(getUserId(), key, pageable);
model.addAttribute("myCollects", myCollects);
model.addAttribute("otherCollects", otherCollects);
model.addAttribute("userId", getUserId())

model.addAttribute("mysize", myCollects.size());
model.addAttribute("othersize", otherCollects.size());
model.addAttribute("key", key);

5. 跳转前端页面
return "collect/search";

3. 通知

开源项目学习-Favorites-Web_第1张图片

function showNotice(type){
	var temp = $(".label.label-danger").html();
	if(type == "letter"){
		temp = temp - $("#newLetterNoticeCount").val();
		$("#newLetterNotice").html("0 条新消息");
	}else if(type == "praise"){
		temp = temp - $("#newPraiseMeCounts").val();
		$("#praiseMeNewNotice").html("0 条新消息");
	}else if(type == "comment"){
		temp = temp - $("#newCommentMeCount").val();
		$("#commentMeNewNotice").html("0 条新消息");
	}else if(type == "at"){
		temp = temp - $("#newAtMeCount").val();
		$("#atMeNewNotice").html("0 条新消息");
	}
	if(temp==0){
		$(".label.label-danger").hide();
	}else{
		$(".label.label-danger").html(temp);
	}
	if(type == "letter"){
		locationUrl('/letter/letterMe','letterMe');
	}else if(type == "praise"){
		locationUrl('/notice/praiseMe','praiseMe');
	}else if(type == "comment"){
		locationUrl('/notice/commentMe','commentMe');
	}else if(type == "at"){
		locationUrl('/notice/atMe','atMe');
	}
}

4. 浏览记录

onclick="locationUrl('/lookRecord/standard/my/0','lookRecord');"

@RequestMapping(value="/lookRecord/standard/{type}/{userId}")
public String getLookRecordStandard(Model model,@RequestParam(value = "page", defaultValue = "0") Integer page,
						 @RequestParam(value = "size", defaultValue = "15") Integer size,
						 @PathVariable("type") String type,@PathVariable("userId") long userId) {

	System.out.println("来执行这一段lookRecord/standard");
	Pageable pageable = PageRequest.of(page, size,Sort.by(Direction.DESC,"id"));
	model.addAttribute("type", "lookRecord");
	Favorites favorites = new Favorites();

	List collects = null;
	User user = userRepository.findById(userId);
	model.addAttribute("otherPeople", user);
	collects =lookRecordService.getLookRecords(this.getUserId(),pageable);

	model.addAttribute("collects", collects);
	model.addAttribute("favorites", favorites);
	model.addAttribute("userId", getUserId());
	model.addAttribute("size", collects.size());
	logger.info("LookRecord end :"+ getUserId());
	return "lookRecord/standard";
}
5. 回收站
onclick="locationUrl('/standard/garbage/0','garbage');"

@RequestMapping(value="/standard/{type}/{userId}")
@LoggerManage(description="文章列表standard")
public String standard(Model model,@RequestParam(value = "page", defaultValue = "0") Integer page,
		@RequestParam(value = "size", defaultValue = "15") Integer size,@PathVariable("type") String type,@PathVariable("userId") long userId) {
//		Sort sort = new Sort(Direction.DESC, "id");
	Pageable pageable = PageRequest.of(page, size,Sort.by(Direction.DESC,"id"));
	model.addAttribute("type", type);
	Favorites favorites = new Favorites();
	if(!"my".equals(type)&&!"explore".equals(type) && !"garbage".equals(type)){
		try {
			favorites = favoritesRepository.findById(Long.parseLong(type));
			favorites.setPublicCount(collectRepository.countByFavoritesIdAndTypeAndIsDelete(favorites.getId(), CollectType.PUBLIC,IsDelete.NO));
		} catch (Exception e) {
			logger.error("获取收藏夹异常:",e);
		}
	}
	List collects = null;
	if(0 != userId && 0 != userId && userId != getUserId()){
		User user = userRepository.findById(userId);
		model.addAttribute("otherPeople", user);
		collects =collectService.getCollects("otherpublic",userId, pageable,favorites.getId(),null);
	}else{
		collects =collectService.getCollects(type,getUserId(), pageable,null,null);
	}
	model.addAttribute("collects", collects);
	model.addAttribute("favorites", favorites);
	model.addAttribute("userId", getUserId());
	model.addAttribute("size", collects.size());
	logger.info("standard end :"+ getUserId());
	return "collect/standard";
}

6. 设置

开源项目学习-Favorites-Web_第2张图片

$(function() {
	loadFavorites();
	loadConfig();
	loadFollows();
	myrefresh();
	$("#passwordError").hide();
	$("#nicknameError").hide();
	$("#noticeNum").hide();
});

function loadConfig(){
	$.ajax({
		async: true,
		type: 'POST',
		dataType: 'json',
		url: '/user/getConfig',
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			console.log(XMLHttpRequest);
			console.log(textStatus);
			console.log(errorThrown);
		},
		success: function(config){
			console.log("进来了吗")
			console.log(config)
			gconfig=config;
			$("#defaultCollectType").html("");
			$("#defaultModel").html("");
			$("#defaultFavorites").html("");
			initConfigDatas(config);
			//设置默认选中收藏夹
			obj = document.getElementById("layoutFavoritesName");
			for(let i=0;i默认收藏夹(" +obj[i].text +")");
			  }
			}
		}
	});
}


function initConfigDatas(config){
	$("#defaultCollectType").append("默认"+config.collectTypeName+"收藏(点击切换)")
	$("#defaultModel").append("收藏时显示" +config.modelName+"模式");
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(前后端分离开源项目系列)