当前位置: 代码迷 >> JavaScript >> 项目里用到的Jquery,json,struts2组合
  详细解决方案

项目里用到的Jquery,json,struts2组合

热度:319   发布时间:2012-10-08 19:54:56.0
项目里用到的Jquery,json,struts2结合
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
	<package name="voteComment" extends="json-default">
		<action name="saveVoteComment" class="voteCommentAction" method="saveVoteComment">
			<result type="json"/>
		</action>
		<action name="loadCourseComments" class="voteCommentAction" method="loadCourseComments">
			<result type="json"/>
		</action>
		<action name="loadCourseCommentsForPage" class="voteCommentAction" method="loadCourseComments">
			<result type="json"/>
		</action>
		<action name="goodVote" class="voteCommentAction" method="countGoodVoteNum">
			<result type="json"/>
		</action>
		<action name="badVote" class="voteCommentAction" method="countBadVoteNum">
			<result type="json"/>
		</action>
	</package>
</struts>




  
//用于处理置顶
jQuery.fn.topLink = function (settings) {
	settings = jQuery.extend({min:1, fadeSpeed:200, ieOffset:38}, settings);
	return this.each(function () {
        //listen for scroll
		var el = $(this);
		el.css("display", "none"); //in case the user forgot
		$(".overview").scroll(function () {
			if (jQuery.support.hrefNormalized) {
				el.css({"position":"absolute", "top":$(".scrollbar").height()+10,"right":settings.ieOffset});
			}
			if ($(".overview").height() > $(".scrollbar").height()) {
				el.fadeIn(settings.fadeSpeed);
				if($(".overview").css("top")=="0px"){
					el.fadeOut(settings.fadeSpeed);
				}
			} 
			else{
				el.fadeOut(settings.fadeSpeed);
			}
		});
	});
};
var commentCurrentPage = 0;
var commentTotal = 0;
var commentTotalPage = 0;
var courseId = 0;
var commentPageSize = 10;
var badVoteNum = 0;
var goodVoteNum = 0;
var commentCount = 0;
$(function () {
	
	//评论部分  开始
	$(".commentsDiv").hide();
	$(".showCommentA").live("click",function(){
		var course_Id = $(this).attr("id");
		openComment(course_Id,commentCurrentPage,commentPageSize);
	});
	$(".closeComment").live("click",function(){
		closeComment();
	});
	//左边 导航菜单
	$("#closeMenuDiv").click(function () {
		var courseId = $(".showCommentA").eq(0).attr("id");
		openComment(courseId,commentCurrentPage,commentPageSize);
	});
  //评论部分  结束
  
  //底部导航 开始
	$(".nav").height("4px").css("opacity", "0.4");
	$(".nav").hover(function (event) {
		if (event.pageY > 560) {
			$(this).animate({height:"44px", opacity:1}, 1000);
		}
	}, function (event) {
		if (event.pageY <= 605) {
			$(this).animate({height:"4px", opacity:"0.4"}, 1000);
		}
	});
 //底部导航 结束
 //置顶
	$("#top-link").topLink({min:1, fadeSpeed:500});
    //smoothscroll
	$("#top-link").click(function (e) {
		e.preventDefault();//==return false;
		$(".overview,.thumb").animate({top:0},10);
		$(this).fadeOut(200);
	});
	$('.overview').mousewheel(function(event,delta) {
		var temp = $(".thumb").css("top");
		if(temp == "0px"){
			$("#top-link").fadeOut(200);
		}
	});
	$(".thumb").click(function(){
		var temp = $(".thumb").css("top");
		if(temp == "0px"){
			$("#top-link").fadeOut(200);
		}
	});
	//点击好评
	$("#goodCommentDiv").live("click",function(){
		var parameters = new Object();
		parameters["courseId"] = courseId;
		parameters["userId"] = "3";
		$.post("voteComment/goodVote.action",parameters,function(data) {
			alert(data.msg);
			if(data.success){
				$("div[title=goodCommentNum]").html(data.goodVoteNum); 
			}
		},"json");
	});
	//点击差评
	$("#badCommentDiv").live("click",function(){
		var parameters = new Object();
		parameters["courseId"] = courseId;
		parameters["userId"] = "3";
		$.post("voteComment/badVote.action",parameters,function(data) {
			alert(data.msg);
			if(data.success){
				$("div[title=badCommentNum]").html(data.badVoteNum); 
			}
		},"json");
	});
	//点击 评论按钮,发表评论
	$(".cl_comment_btn").live("click",function(){
		var temp_comments = $(".cl_comment_textarea").val();
		if(temp_comments.trim() == ""){
			alert('评论内容不能为空!');
			return;
		}
		var parameters = new Object();
		parameters["courseId"] = courseId;
		parameters["userId"] = "3";
		parameters["comments"] = $(".cl_comment_textarea").val();
		$.post("voteComment/saveVoteComment.action",parameters,function(data) {
			if(data.success){
				$("#commentslist").empty();
				loadComments(courseId,1,commentPageSize);
				$(".cl_comment_textarea").val("");
			}
		},"json");
	});
});


//关闭评论
function closeComment() {
	$(".scrollbar").show();
	$("#scrollbar1").unbind("mousewheel");
	$("#scrollbar1").bind("mousewheel",function(event,delta){$(this).tinyscrollbar();});
	
	var flag = $(".left").width();
	$("#closeMenuDiv").attr("class","arrowicon_toleft_b");
	$(".detaillist").width("721px");
	$(".center").width("721px");
	if (flag == 162) {
		$(".center").animate({left:"162px",marginLeft:"0px"}, "slow");
		$(".commentsDiv").fadeOut("slow").width("1px").css("margin-right", "0px");
	} else {
		$(".center").animate({left:"162px",marginLeft:"0px"}, "slow");
		$(".bookmark").fadeIn("slow");
		$(".commentsDiv").fadeOut("slow").width("1px").css("margin-right", "0px");
		$(".left").animate({width:"162px"}, "slow");
	}
}


//显示评论
function openComment(course_Id,commentCurrentPage1,pages_size){
	$(".cl_comment_textarea").val("");
	
	$(document).unbind("mousewheel");
	$(document).bind("mousewheel",function(event,delta){event.stopPropagation();});
	$("#scrollbar1").unbind("mousewheel");
	$("#scrollbar1").bind("mousewheel",function(event,delta){event.stopPropagation();});
	$(".scrollbar").hide();
	
	
	var closeFlag = $("#closeMenuDiv").attr("class");
	if (closeFlag == "arrowicon_toleft_b") {
	$("#scrollbar1").unbind("endlessScroll");
	$(".left").animate({width:"20px"}, "slow", function () {
		$(".bookmark").hide();
		$("#closeMenuDiv").attr("class","arrowicon_toright_b");
	}).css("z-index", "0");
	$(".detaillist").attr("style",$(".overview").attr("style")).width("645px");
	$(".commentsDiv").width("187px").css("right", "-218px").fadeIn("slow");
	$(".center").width("645px").animate({left:"0px",marginLeft:"20px"}, "slow");
//	$(".scrollbarClass").attr("id","");
//	$(".scrollbarClass").width("645px");
	
	
	if(courseId != course_Id){
		commentCurrentPage = 1;
		totalPage = 1;
		commentCurrentPage1 = 1;
		loadComments(course_Id,commentCurrentPage1,pages_size);
	}
		
	} else {
		closeComment();
	}
}

//发送请求,加载评论
function loadComments(courseId1,currentPage1,pageSize1){
	var parameters = new Object();
	parameters["courseId"] = courseId1;
	parameters["commentCurrentPage"] = currentPage1;
	parameters["commentPageSize"] = pageSize1;
	$.post("voteComment/loadCourseComments.action",parameters,function(data) {
		showComments(data);
	},"json");
}
//将查询到的评论显示到页面上
function showComments(data){
	commentCurrentPage = data.commentCurrentPage;
	commentTotal = data.commentTotal;
	badVoteNum = data.badVoteNum;
	goodVoteNum = data.goodVoteNum;
	courseId = data.courseId;
	commentTotalPage = data.commentTotalPage;
	var list = data.commentList;
    $("div[title=goodCommentNum]").html(goodVoteNum); 
    $("div[title=badCommentNum]").html(badVoteNum); 
    $("#totalNum").html(commentTotal); 
 	var commentHtml =  "<div class='cl_comment_down'>";
 	var tem = "";			
 	if(list != null){
		for(var i = 0; i < list.length; i++){
			var commentTime = list[i].commentTime;
			var comment = list[i].comments
			var userPhoto = list[i].userHeadPhoto
			var userNickName = list[i].userNickName	
			var userRealName = list[i].userRealName
			var userId = list[i].userId;
			var commentDetail ="<div class='down_row down_row_first'><div class='cl_comment_userinfo'>"
	       							+"<div class='cl_comment_userphoto'><img src='../../images/photo/userphoto44.jpg' width='44' height='44' alt='"+userRealName+"' />"
	       							+"</div><div><h4>"+userNickName+"</h4><div class='datetime'>"+commentTime+"</div>"
	           						+"</div></div><p class='cl_commnet_content' style='height:100%; width:168px;'>"+comment+"</p></div>";
			tem +=commentDetail;
		}
	}
	var temp_commentsBar = $('#scrollbars_comments');
	temp_commentsBar.tinyscrollbarComment();
	var html = commentHtml+tem+"</div>";
	$("div#commentslist").html(html);
	temp_commentsBar.update(true);
	
	$('#commentslist').live('mousewheel',function(event,delta1) {
	    event.preventDefault();
	    clickAndWheelForPages(event,delta1);
	});
	$(".thumb_comments").live("click",function(event,delta1){
	 	event.preventDefault();
	    clickAndWheelForPages(event,delta1);
	});
}
var clickAndWheelForPages = function(event,delta1){
	var delta = delta1;
	   var code = event.keyCode;
	   commentCount = $(".cl_comment_down > div").size();
	   var temp_top=$("div.thumb_comments").css("top");
	   var temp_thum_height=$("div.thumb_comments").height();
	   var temp_track_height=$("div.track_comments").height();
	   temp_top=parseInt(temp_top.replace("px",""));
	   var temp_scrollHeight = $("div.overview_comments").attr("scrollHeight");
	   var temp_overview_top= $("div.overview_comments").css("top");
	   var temp_offsetHeight= $("div.viewport_comments").attr("offsetHeight");
	       temp_overview_top=-parseInt(temp_overview_top.replace("px",""));
	   var temp_thum = temp_top+temp_thum_height;
	   var temp_height = temp_offsetHeight+temp_top+temp_thum_height+temp_overview_top;
	   if (temp_thum >= temp_track_height*0.8 && temp_scrollHeight <= temp_height && commentCount < commentTotal)
		{
		//alert('新加载....');
		var t = Math.random();
		$.ajax({
			url:"voteComment/loadCourseCommentsForPage.action?t="+t,
			type:"POST",
			data:{"courseId":courseId,"commentCurrentPage":commentCurrentPage+1,"commentPageSize":commentPageSize},
			dataType:"json",
			global: false,
			success: showCommentForPages
		});	
	};
}
function showCommentForPages(data) {
		commentCurrentPage = data.commentCurrentPage;
		var list = data.commentList;
	    var tem = "";			
		if(list != null){
			for(var i = 0; i < list.length; i++){
				var commentTime = list[i].commentTime;
				var comment = list[i].comments
				var userPhoto = list[i].userHeadPhoto
				var userNickName = list[i].userNickName	
				var userRealName = list[i].userRealName
				var userId = list[i].userId;
				var commentDetail ="<div class='down_row down_row_first' ><div class='cl_comment_userinfo'>"
		       							+"<div class='cl_comment_userphoto'><img src='../../images/photo/userphoto44.jpg' width='44' height='44' alt='"+userRealName+"' />"
		       							+"</div><div><h4>"+userNickName+"</h4><div class='datetime'>"+commentTime+"</div>"
		           						+"</div></div><p class='cl_commnet_content' style='height:100%; width:168px;'>"+comment+"</p></div>";
				tem +=commentDetail;
			}
		}
		temp_commentsBar = $('#scrollbars_comments');
		temp_commentsBar.tinyscrollbarComment();
		$("div.cl_comment_down").append(tem);
		temp_commentsBar.update(true);
		commentCount = $(".cl_comment_down > div").size();
		return false;					
	};
//当前选中的左边菜单导航
function currentNav(id) {
	$(".nav_c li").each(function () {
		$(this).removeAttr("class");
		$(this).find("div").removeClass("arrowicon_toleft_w");
		if (id == $(this).attr("id")) {
			$(this).addClass("curmenu");
			$(this).find("div").addClass("arrowicon_toleft_w");
		}
	});
};





$(function () {
//点击 热门课程
$("#one a").css("cursor", "pointer").click(function () {
$.post("index.jsp");
});
//初始化 热门课程 页面
initPopularCourseAjax();
});
var initPopularCourseAjax = function () {
$.post("initPopularCourseAction.action", function (data) {
var counts = data["fileCounts"];
var names = data["fileNames"];
$(".changepagedotter").empty();
if (counts > 0) {
for (var i = 0; i < counts; i++) {
$(".changepagedotter").append($("<a style='cursor:pointer;'  id='content"+i+"' name='" + names[i] + "'></a>"));
}
$(".changepagedotter a").eq(0).attr("class", "currentpage");
$(".changepagedotter a").live("click", function(e) {
    showPopularCourseAjax($(this).attr("name"),$(this).attr("id"));
});
$(document).keydown(function(event){
keyboardChangePage(event, 0);
});
$('.center').mousewheel(function(event,delta) {
keyboardChangePage(event, delta);
});
}
}, "json");
};
//按 键盘上的左、右、PgUp、pgDn以及鼠标中键滚动 执行翻页
var keyboardChangePage = function(event,delta1){
var fileName = '';
var id = '';
//delta为鼠标中键滚动变量,delta>0:表示up, delta<0:表示down
var delta = delta1;
var code = event.keyCode;
var currentPageName = $(".currentpage").attr("name");
var currentPageId = $(".currentpage").attr("id");
var firstId = $(".changepagedotter a:first").attr("id");
var lastId = $(".changepagedotter a:last").attr("id");
//键盘按 向右,PgDn 鼠标向下滚动
if(code == '39'|| code == '34' || delta < 0){
event.preventDefault();
if(lastId == currentPageId) {
return false;
}
$(".changepagedotter a").each(function(){
if(currentPageName ==$(this).attr("name")){
fileName = $(this).next("a").attr("name");
id = $(this).next("a").attr("id");
showPopularCourseAjax(fileName,id);
}
});
}
if(code == '37'|| code == '33' || delta > 0){
event.preventDefault();
if(firstId == currentPageId){
return false;
}
$(".changepagedotter a").each(function(){
if(currentPageName ==$(this).attr("name")){
fileName = $(this).prev("a").attr("name");
id = $(this).prev("a").attr("id");
showPopularCourseAjax(fileName,id);
}
});
}
};
//点击翻页或者鼠标移动到翻页按钮上 执行翻页
var showPopularCourseAjax = function (fileName,id) {
var parameters = new Object();
parameters["fileName"] = fileName;
$(".changepagedotter a").removeClass("currentpage");
$("#"+id).addClass("currentpage");
$.post("changePagePopularCourseAction.action", parameters, function (data) {
$(".center").html($(data["content"]).eq(1).html());
}, "json");
};




struts.xml
<package name="CourseJson" extends="json-default">
		<action name="listCourseAction" class="courseAction" method="list">
			<result type="json" />
		</action>
		<action name="addCourseAction" class="courseAction" method="addCourse">
			<result type="json" />
		</action>
		<!-- 处理翻页 -->
		<action name="changePagePopularCourseAction"
			class="popularCourseAction" method="changePage">
			<result type="json" />
		</action>
		<!-- 初始化首页 -->
		<action name="initPopularCourseAction"
			class="popularCourseAction" method="initPopularCourse">
			<result type="json" />
		</action>
</package>



Actione
VoteCommentAction.java
package com.able.action.votecomment;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.struts2.json.annotations.JSON;

import com.able.action.BaseAction;
import com.able.dto.votecomment.UserVoteDetailDto;
import com.able.dto.votecomment.VoteCommentDto;
import com.able.dto.votecomment.VoteDto;
import com.able.dto.votecomment.VoteStrategyDto;
import com.able.model.Course;
import com.able.model.User;
import com.able.model.VoteComment;
import com.able.service.ICourseService;
import com.able.service.IUserService;
import com.able.service.IUserVoteDetailService;
import com.able.service.IVoteCommentService;
import com.able.service.IVoteService;
import com.able.service.IVoteStrategyService;
import com.able.util.Constants;
import com.able.util.SearchCondition;
import com.able.util.UtilTools;

public class VoteCommentAction extends BaseAction {
	private static final long serialVersionUID = 4290888239078443151L;
	private IVoteService voteService;
	private IVoteCommentService voteCommentService;
	private ICourseService courseService;
	private IUserService userService;
	private IVoteStrategyService voteStrategyService;
	private IUserVoteDetailService userVoteDetailService;
	private String msg;
	private boolean success;
	private List<VoteCommentDto> commentList;
	private int commentTotalPage;
	private int commentPageSize;
	private int commentCurrentPage;
	private int commentTotal;
	private long courseId;
	private long userId;
	private long voteId;
	private String comments;
	private long badVoteNum;
	private long goodVoteNum;
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	
	public String saveVoteComment(){
		User user = null;
		Course course = null;
		try{
			if(UtilTools.isNumber(""+userId)){
				user = userService.get(userId);
			}else{
				success = false;
				msg = "对不起,请先登录!";
				return SUCCESS;
			}
			if(UtilTools.isNumber(courseId+"")){
				course = courseService.get(Long.valueOf(courseId));
			}else{
				msg = "评论失败!";
				success = false;
				return SUCCESS;
			}
			VoteComment voteComment = new VoteComment();
			voteComment.setComments(comments);
			voteComment.setCourse(course);
			voteComment.setUser(user);
			voteComment.setIsDeleted("0");
			voteComment.setCreateTime(new Date());
			voteComment.setCommentTime(new Date());
			voteComment.setCreatePerson(user.getNickname());
			voteCommentService.save(voteComment);
			commentCurrentPage = 1;
			msg = "评论成功!";
			success = true;
		}catch (Exception e) {
			success = false;
			msg = "评论失败!";
			this.log.error(e);
		}
		return SUCCESS;
	}
	public String testMethod(){
		this.getResponse();
		success = true;
		return SUCCESS;
	}
	
	public String loadCourseComments(){
		SearchCondition search = null;
		if(courseId > 0){
			try{
				commentTotal = voteCommentService.findAllCommentCountsByCourseId(courseId);
				search = new SearchCondition();
				search.setPropSortBy("commentTime");
				search.setLimit(commentPageSize);
				search.setStart((commentCurrentPage-1)*search.getLimit());
				search.setSortMode(Constants.DESC);
				badVoteNum = voteService.findTotalBadVoteByCourseId(courseId);
				goodVoteNum = voteService.findTotalGoodVoteByCourseId(courseId);
				commentList = voteCommentService.findAllCommentsByCourseIdForPage(courseId, search);
				if(commentTotal % commentPageSize > 0){
					commentTotalPage = commentTotal/commentPageSize + 1;
				}else{
					commentTotalPage = commentTotal/commentPageSize;
				}
			}catch(Exception e){
				success = false;
				this.log.error(e);
			}
		}
		return SUCCESS;
		
	}
	public String countGoodVoteNum(){
		if(courseId > 0 ){
			VoteStrategyDto strategyDto = voteStrategyService.findVoteStrategyByCourseId(courseId);
			VoteDto voteDto = voteService.findVoteByCourseId(courseId);
		//	String votePerssion = strategyDto.getVotePermissions();
			String voteRule = strategyDto.getVoteCountRules();
			List<UserVoteDetailDto> userListDetail = userVoteDetailService.findVoteDetailByCourseIdAndUserId(courseId, userId);
			//如果该课程还没有投票,则创建一个投票,并保存
			if(voteDto.getVoteId()== null || "0".equals(voteDto.getVoteId())){
				voteDto.setCourseId(courseId);
				Long voteDtoId = voteService.saveVote(voteDto);
				voteDto.setVoteId(voteDtoId);
			}
			Integer votedNum = 0;
			//投票规则:如果一个用户针对一门课程只能投一次票
			if("0".equals(voteRule)){
				if(userListDetail != null && userListDetail.size() > 0){
					for(UserVoteDetailDto dto : userListDetail){
						votedNum += dto.getVoteCount();
					}
				}
				//如果该用户还没有投票
				if(votedNum == 0){
					UserVoteDetailDto dto = new UserVoteDetailDto();
					dto.setCourseId(courseId);
					dto.setUserId(userId);
					dto.setVoteId(voteDto.getVoteId());
					dto.setVoteCount(1);
					long modelId = userVoteDetailService.saveUserVoteDetail(dto);
					//如果已经有人投票,则更新投票
					if(voteDto != null){
						voteDto.setGoodVote(voteDto.getGoodVote()+1);
						voteDto.getUserVoteDetailId().add(modelId);
						voteService.updateVote(voteDto);
					}//如果还没有投票,则创建投票对象并保存
					else{
						voteDto = new VoteDto();
						voteDto.setGoodVote(1);
						voteDto.setBadVote(0);
						voteDto.getUserVoteDetailId().add(modelId);
						voteDto.setCourseId(courseId);
						voteDto.setVoteId(voteDto.getVoteId());
						voteDto.setVoteStategyId(strategyDto.getVoteStrategyId());
						voteService.saveVote(voteDto);
					}
					goodVoteNum = goodVoteNum + 1;
					success = true;
					msg = "投票成功!";
				}else{
					success = false;
					msg = "对不起,你已经投过票了!";
				}
			}
			
			//投票规则:每个用户每天投票次数不超过1次
			if("1".equals(voteRule)){
				if(userListDetail != null){
					for(UserVoteDetailDto dto : userListDetail){
						Date d = null;
						try {
							d = sdf.parse(dto.getUpdateTime());
						} catch (ParseException e) {
							e.printStackTrace();
							log.error(e);
						}
						if(sdf.format(new Date()).equals(sdf.format(d))){
							votedNum += dto.getVoteCount();
						}else{
							votedNum = 0;
						}
					}
				}
				//如果该用户今天还没有投票
				if(votedNum < 1 || votedNum == null){
					UserVoteDetailDto dto = new UserVoteDetailDto();
					dto.setCourseId(courseId);
					dto.setUserId(userId);
					dto.setVoteId(voteDto.getVoteId());
					dto.setVoteCount(1);
					long modelId = userVoteDetailService.saveUserVoteDetail(dto);
					//如果已经有人投票,则更新投票
					if(voteDto != null){
						voteDto.setGoodVote(voteDto.getGoodVote()+1);
						voteDto.getUserVoteDetailId().add(modelId);
						voteService.updateVote(voteDto);
					}//如果还没有投票,则创建投票对象并保存
					else{
						voteDto = new VoteDto();
						voteDto.setGoodVote(1);
						voteDto.setBadVote(0);
						voteDto.getUserVoteDetailId().add(modelId);
						voteDto.setCourseId(courseId);
						voteDto.setVoteId(voteDto.getVoteId());
						voteDto.setVoteStategyId(strategyDto.getVoteStrategyId());
						voteService.saveVote(voteDto);
					}
					goodVoteNum = goodVoteNum + 1;
					success = true;
					msg = "投票成功!";
				}else{
					success = false;
					msg = "对不起,你今天已经投票,请明天再投!";
				}
			}
		}
		return SUCCESS;
	}
	
	
	public String countBadVoteNum(){
		if(courseId > 0 ){
			VoteStrategyDto strategyDto = voteStrategyService.findVoteStrategyByCourseId(courseId);
			VoteDto voteDto = voteService.findVoteByCourseId(courseId);
		//	String votePerssion = strategyDto.getVotePermissions();
			String voteRule = strategyDto.getVoteCountRules();
			List<UserVoteDetailDto> userListDetail = userVoteDetailService.findVoteDetailByCourseIdAndUserId(courseId, userId);
			//如果该课程还没有投票,则创建一个投票,并保存
			if(voteDto.getVoteId()== null || "0".equals(voteDto.getVoteId())){
				voteDto.setCourseId(courseId);
				Long voteDtoId = voteService.saveVote(voteDto);
				voteDto.setVoteId(voteDtoId);
			}
			Integer votedNum = 0;
			//投票规则:如果一个用户针对一门课程只能投一次票
			if("0".equals(voteRule)){
				if(userListDetail != null && userListDetail.size() > 0){
					for(UserVoteDetailDto dto : userListDetail){
						votedNum += dto.getVoteCount();
					}
				}
				//如果该用户还没有投票
				if(votedNum == 0){
					UserVoteDetailDto dto = new UserVoteDetailDto();
					dto.setCourseId(courseId);
					dto.setUserId(userId);
					dto.setVoteId(voteDto.getVoteId());
					dto.setVoteCount(1);
					long modelId = userVoteDetailService.saveUserVoteDetail(dto);
					//如果已经有人投票,则更新投票
					if(voteDto != null){
						voteDto.setBadVote(voteDto.getBadVote()+1);
						voteDto.getUserVoteDetailId().add(modelId);
						voteService.updateVote(voteDto);
					}//如果还没有投票,则创建投票对象并保存
					else{
						voteDto = new VoteDto();
						voteDto.setGoodVote(1);
						voteDto.setBadVote(0);
						voteDto.getUserVoteDetailId().add(modelId);
						voteDto.setCourseId(courseId);
						voteDto.setVoteId(voteDto.getVoteId());
						voteDto.setVoteStategyId(strategyDto.getVoteStrategyId());
						voteService.saveVote(voteDto);
					}
					badVoteNum = badVoteNum + 1;
					success = true;
					msg = "投票成功!";
				}else{
					success = false;
					msg = "对不起,你已经投过票了!";
				}
			}
			
			//投票规则:每个用户每天投票次数不超过1次
			if("1".equals(voteRule)){
				if(userListDetail != null){
					for(UserVoteDetailDto dto : userListDetail){
						Date d = null;
						try {
							d = sdf.parse(dto.getUpdateTime());
						} catch (ParseException e) {
							e.printStackTrace();
							log.error(e);
						}
						if(sdf.format(new Date()).equals(sdf.format(d))){
							votedNum += dto.getVoteCount();
						}else{
							votedNum = 0;
						}
					}
				}
				//如果该用户今天还没有投票
				if(votedNum < 1 || votedNum == null){
					UserVoteDetailDto dto = new UserVoteDetailDto();
					dto.setCourseId(courseId);
					dto.setUserId(userId);
					dto.setVoteId(voteDto.getVoteId());
					dto.setVoteCount(1);
					long modelId = userVoteDetailService.saveUserVoteDetail(dto);
					//如果已经有人投票,则更新投票
					if(voteDto != null){
						voteDto.setGoodVote(voteDto.getGoodVote()+1);
						voteDto.getUserVoteDetailId().add(modelId);
						voteService.updateVote(voteDto);
					}//如果还没有投票,则创建投票对象并保存
					else{
						voteDto = new VoteDto();
						voteDto.setGoodVote(0);
						voteDto.setBadVote(1);
						voteDto.getUserVoteDetailId().add(modelId);
						voteDto.setCourseId(courseId);
						voteDto.setVoteId(voteDto.getVoteId());
						voteDto.setVoteStategyId(strategyDto.getVoteStrategyId());
						voteService.saveVote(voteDto);
					}
					badVoteNum = badVoteNum + 1;
					success = true;
					msg = "投票成功!";
				}else{
					success = false;
					msg = "对不起,你今天已经投票,请明天再投!";
				}
			}
		}
		return SUCCESS;
	}
	@JSON(serialize=false)
	public IVoteCommentService getVoteCommentService() {
		return voteCommentService;
	}

	public void setVoteCommentService(IVoteCommentService voteCommentService) {
		this.voteCommentService = voteCommentService;
	}
	@JSON(serialize=false)
	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	@JSON(serialize=false)
	public ICourseService getCourseService() {
		return courseService;
	}

	public void setCourseService(ICourseService courseService) {
		this.courseService = courseService;
	}
	@JSON(serialize=false)
	public IVoteService getVoteService() {
		return voteService;
	}
	public void setVoteService(IVoteService voteService) {
		this.voteService = voteService;
	}
	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public List<VoteCommentDto> getCommentList() {
		return commentList;
	}

	public void setCommentList(List<VoteCommentDto> dtos) {
		this.commentList = dtos;
	}



	public long getCourseId() {
		return courseId;
	}

	public void setCourseId(long courseId) {
		this.courseId = courseId;
	}

	public long getUserId() {
		return userId;
	}

	public void setUserId(long userId) {
		this.userId = userId;
	}

	public String getComments() {
		return comments;
	}

	public void setComments(String comments) {
		this.comments = comments;
	}

	public int getCommentTotalPage() {
		return commentTotalPage;
	}
	public void setCommentTotalPage(int commentTotalPage) {
		this.commentTotalPage = commentTotalPage;
	}
	public int getCommentPageSize() {
		return commentPageSize;
	}
	public void setCommentPageSize(int commentPageSize) {
		this.commentPageSize = commentPageSize;
	}
	public int getCommentCurrentPage() {
		return commentCurrentPage;
	}
	public void setCommentCurrentPage(int commentCurrentPage) {
		this.commentCurrentPage = commentCurrentPage;
	}
	public int getCommentTotal() {
		return commentTotal;
	}
	public void setCommentTotal(int commentTotal) {
		this.commentTotal = commentTotal;
	}
	public long getBadVoteNum() {
		return badVoteNum;
	}
	public void setBadVoteNum(long badVoteNum) {
		this.badVoteNum = badVoteNum;
	}
	public long getGoodVoteNum() {
		return goodVoteNum;
	}
	public void setGoodVoteNum(long goodVoteNum) {
		this.goodVoteNum = goodVoteNum;
	}
	@JSON(serialize=false)
	public IVoteStrategyService getVoteStrategyService() {
		return voteStrategyService;
	}
	public void setVoteStrategyService(IVoteStrategyService voteStrategyService) {
		this.voteStrategyService = voteStrategyService;
	}
	@JSON(serialize=false)
	public IUserVoteDetailService getUserVoteDetailService() {
		return userVoteDetailService;
	}
	public void setUserVoteDetailService(
			IUserVoteDetailService userVoteDetailService) {
		this.userVoteDetailService = userVoteDetailService;
	}
	public long getVoteId() {
		return voteId;
	}
	public void setVoteId(long voteId) {
		this.voteId = voteId;
	}
	public static long getSerialVersionUID() {
		return serialVersionUID;
	}
	
}



PopularAction
package com.able.action.course;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.able.action.BaseAction;
import com.able.util.Constants;
import com.able.util.json.JSONException;
import com.able.util.json.JSONObject;

public class PopularCourseAction extends BaseAction {
	private static final long serialVersionUID = 1558906223631093472L;
	//接收热门文件夹名称
	private String FloderPath;
	//热门文件名称
	private String fileName;

	/**
	 * 初始化 热门课程 显示第一页及设置翻页按钮
	 * @return
	 */
	public String initPopularCourse(){
		this.getResponse().setCharacterEncoding("UTF-8");
		File[] files = getAllFiles();
		int filesCount = files.length;
		List<String> fileNames = new ArrayList<String>();
		JSONObject json = new JSONObject();
		PrintWriter pw = null;
		try {
			if(files != null){
				json.put("fileCounts", filesCount);
				for(int i = 0; i < files.length; i++){
					fileNames.add(files[i].getName());
				}
				Collections.sort(fileNames);
				json.put("fileNames", fileNames);
			}
			pw = this.getResponse().getWriter();
		} catch (JSONException e) {
			log.error(e);
		} catch (IOException e) {
			log.error(e);
		}finally{
			if(pw != null){
				pw.write(json.toString());
				pw.flush();
				pw.close();
			}
		}
		return SUCCESS;
	}
	/**
	 * 处理 热门课程 页面之间的切换
	 * @return
	 */
	public String changePage() {
		this.getResponse().setCharacterEncoding("UTF-8");
		File[] files = getAllFiles();
		StringBuffer sb = new StringBuffer();
		JSONObject json = new JSONObject();
		PrintWriter pw = null;
		BufferedReader reader = null;
		try {
			for (int i = 0; i < files.length; i++) {
				File f = files[i];
				if (fileName.equals(f.getName())) {
					reader = new BufferedReader(new InputStreamReader(
							new FileInputStream(f), "UTF-8"));
					String s = reader.readLine();
					while (s != null) {
						sb.append(s);
						s = reader.readLine();
					}
				}
			}
			json.put("content", sb.toString());
			pw = this.getResponse().getWriter();
		} catch (IOException e) {
			log.error(e);
		} catch (JSONException e) {
			log.error(e);
		}finally{
			if(pw != null){
				pw.write(json.toString());
				pw.flush();
				pw.close();
			}
		}
		return SUCCESS;
	}
	//取得所有 热门课程 页面文件
	@SuppressWarnings("deprecation")
	private File[] getAllFiles(){
		FloderPath = this.getRequest().getRealPath(Constants.POPULAR_COURSE_PATH);
		File fileFolder = new File(FloderPath);
		//过滤出所有以content开头的文件
		File[] files = fileFolder.listFiles(new FileFilter(){
			public boolean accept(File pathname) {
				if(pathname != null){
					if(pathname.isFile() && pathname.getName().startsWith("content")){
						return true;
					}
				}
				return false;
			}
		});
		return files;
	}
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
}
	



  相关解决方案