`
eric.zhang
  • 浏览: 127315 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

项目里用到的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;
	}
}
	



分享到:
评论
1 楼 calosteward 2014-12-12  
赞一个。
谢谢分享了~非常有用。
——————————————————————
java barcode reader
java barcode creator

相关推荐

    Json JQuery Struts2

    例如,研究Struts2的JSON插件是如何将Java对象转换为JSON,JQuery的Ajax实现细节,以及如何通过自定义拦截器扩展Struts2的功能。 5. 工具支持:在开发过程中,开发者可能需要用到诸如IDEA、Eclipse这样的集成开发...

    json2+jsonplugin struts2整合ajax时,使用json时需要的jar包

    在这个过程中,我们通常会用到`json2.js`库来处理JSON数据在JavaScript端的解析和序列化,以及Struts2的`jsonplugin`来支持JSON响应。 首先,让我们详细了解一下`json2.js`。这个JavaScript库是由Douglas Crockford...

    Struts2使用Annotation返回Json

    通过这种方式,Struts2结合注解和JSON插件,可以让开发人员更方便地处理JSON数据的返回,从而简化了Web应用的开发流程。同时,这种方式也使得代码更具有可读性和可维护性。记住,一定要确保Struts2的核心库和JSON...

    常用jar包struts2、spring、hibernate、jquery、json

    Struts2、Spring、Hibernate、jQuery 和 JSON 是Java Web开发中的关键组件,它们各自扮演着不同的角色,构建出高效、可维护的Web应用程序。 Struts2是一个基于MVC(Model-View-Controller)设计模式的Java Web框架...

    struts整合json用到Jar.zip

    1. **JSON插件安装**:在Struts2中,通常需要引入一个名为`struts2-json-plugin-x.x.x.jar`的插件,这个文件可能就是压缩包中的主要内容。该插件提供了JSON结果类型,使得Action可以直接返回JSON格式的数据。 2. **...

    struts2 jquery xml

    Struts2 jQuery XML 是一个基于Java的Web开发框架的组合,它将Apache Struts2的MVC架构与jQuery库结合,提供了丰富的用户界面组件和更流畅的AJAX交互。Struts2是一个强大的、灵活的MVC框架,而jQuery则简化了...

    Struts2返回JSON对象.doc

    在Struts2框架中,返回JSON对象是一种常见的数据传输方式,特别是在前后端分离的开发模式下。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。以下将...

    struts2+json+jquery局部刷新实现注册验证

    struts2+json+jquery局部刷新实现注册验证,包括前台的用户名、密码、手机、身份证、邮箱(包含发邮件技术)、邮箱验证码、验证码的验证,用到的是json+jquery,后台则是用struts2+java类

    struts2+jquery之form插件实现异步上传

    Struts2和jQuery是Web开发中的两个重要框架,它们结合使用可以实现许多强大的功能,其中包括异步文件上传。在这个主题中,我们将详细讨论如何利用Struts2和jQuery的form插件来实现这一功能。 首先,Struts2是一个...

    ssi+json+jquery 案例

    1. 示例代码:展示如何在Struts2和Spring3框架下集成SSI、JSON和jQuery的实例。 2. jar包:可能包括Struts2、Spring3和iBatis2的依赖库,以及其他可能用到的辅助库。 3. HTML文件:展示如何在页面中使用SSI技术。 4....

    Struts2+ajax+json异步上传图片回显

    在这个场景中,“Struts2+ajax+json异步上传图片回显”是指利用Struts2框架,通过Ajax技术实现图片的异步上传,并通过JSON进行数据交互,最终实现在页面上即时回显上传的图片。 首先,让我们理解每个组件的作用: ...

    struts2所用到的jar文件

    标题提到的"struts2所用到的jar文件"是Struts2框架运行所必需的库文件,包含了框架的核心组件和其他依赖库。下面我们将详细探讨这些jar文件及其在Struts2中的作用。 1. **Struts2核心组件**: - `struts2-core.jar...

    struts2所需jar包

    - `struts2-dojo-plugin.jar` 或 `struts2-jquery-plugin.jar`:这些是UI库插件,用于增强Web页面的用户体验,例如Dojo或jQuery UI。 4. **依赖的IoC容器**: - `struts2-java5-plugin.jar`:如果项目使用Java 5...

    struts2的全部jar包,包含struts中所有用到的jar包

    - `struts2-dojo-plugin.jar`/`struts2-jquery-plugin.jar`:集成JavaScript库的插件,如Dojo或jQuery。 每个jar包都包含了特定的功能,通过它们的组合,开发者可以构建出功能完善的Struts2应用程序。在实际开发中...

    struts2+hibernate 简单网上书店

    在实现过程中,我们可能需要用到jQuery库来处理Ajax请求,以及在Struts2 Action中处理这些请求并返回相应的JSON数据。 为了实现上述功能,我们需要对以下几个核心组件有深入理解: 1. Struts2拦截器(Interceptors...

    json 解析所依赖的jar包

    在Java环境中,解析和生成JSON通常需要依赖于特定的库,比如Apache Struts2框架在处理JSON响应时就可能会用到相关的jar包。 Struts2是一个非常流行的MVC(Model-View-Controller)框架,用于构建企业级的Java web...

    网络硬盘(Struts 2+Hibernate+Spring实现)

    在这个项目中,我们采用了一种经典的Java Web开发框架——Struts 2,结合ORM框架Hibernate以及依赖注入框架Spring,实现了功能完善的网络硬盘系统。以下是关于这三个技术在实现网络硬盘中的应用及其知识点的详细说明...

    json核心jar包.rar

    为了在Struts2项目中使用这个json核心jar包,你需要将它们添加到项目的类路径中,通常是WEB-INF/lib目录下。然后在struts.xml配置文件中启用JSON插件,配置相应的Action以返回JSON结果。这样,当Ajax请求到达服务器...

    Struts2文件上传带进度条页面无刷新

    可以使用jQuery或者其他JavaScript库,配合Struts2的JSON插件来发送异步请求。在HTML页面中,创建一个form元素,添加一个input[type=file],以及一个进度条元素(例如使用Bootstrap的progress组件)。 ```html ...

Global site tag (gtag.js) - Google Analytics