1、SpringMVC中通过@ResponseBody返回对象,作为JQuery中的ajax返回值
package com.kuman.cartoon.controller;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.filefilter.FalseFileFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.kuman.cartoon.common.Page;
import com.kuman.cartoon.common.controller.BaseController;
import com.kuman.cartoon.entity.Comment;
import com.kuman.cartoon.entity.CommentType;
import com.kuman.cartoon.entity.User;
import com.kuman.cartoon.service.CommentService;
import com.kuman.cartoon.service.UserService;
/**
* @Title: 评论处理控制器
* @author huh 修改者:涂作权
*/
@Controller
@SessionAttributes(value = { "accountid", "account" })
public class CommentController extends BaseController {
private static final Logger LOGGER = LoggerFactory
.getLogger(CommentController.class);
/**
* 发布评论,下面的方法返回一个boolean值,可以直接在ajax回调中中使用
*
* @param request
* @param comment
* @return
*/
@ResponseBody
@RequestMapping(value = "/comment/add", method = RequestMethod.POST)
public boolean sendComment(HttpServletRequest request, Comment comment) {
if (comment == null) {
return Boolean.FALSE;
}
comment.setCommentType(CommentType.CONTENT);
// 保存浏览用户,从session中取
int userId = -1;
Object objUserId = request.getSession().getAttribute("accountid");
if (objUserId != null) {
try {
userId = Integer.parseInt(objUserId.toString());
} catch (Exception e) {
}
} else {
return Boolean.FALSE;
}
comment.setUser(userService.queryUser(userId));
try {
commentService.saveComment(comment);
} catch (Exception e) {
LOGGER.error("发布评论出错", e);
return Boolean.FALSE;
}
return Boolean.TRUE;
}
/**
* 赞同评论
*
* @param comment
* @return
*/
@ResponseBody
@RequestMapping(value = "/comment/commentlike", method = RequestMethod.POST)
public boolean commentLike(String cid) {
Comment comment = null;
try {
comment = commentService.queryCommentById(Integer.parseInt(cid));
if (comment == null) {
LOGGER.error("点赞出错未查找到评论" + cid);
return Boolean.FALSE;
}
} catch (Exception e) {
LOGGER.error("点赞出错", e);
}
try {
comment.setLikecount(comment.getLikecount() + 1);
commentService.updateComment(comment);
} catch (Exception e) {
LOGGER.error("点赞出错", e);
return Boolean.FALSE;
}
return Boolean.TRUE;
}
/**
* 删除评论
*
* @param comment
* @return
*/
@Deprecated
@ResponseBody
@RequestMapping(value = "/comment/del", method = RequestMethod.POST)
public boolean commentDel(String cid) {
Comment comment = null;
try {
comment = commentService.queryCommentById(Integer.parseInt(cid));
if (comment == null) {
LOGGER.error("删除出错未查找到评论" + cid);
return Boolean.FALSE;
}
} catch (Exception e) {
LOGGER.error("删除出错", e);
}
try {
commentService.delComment(Integer.parseInt(cid));
} catch (Exception e) {
LOGGER.error("删除出错", e);
return Boolean.FALSE;
}
return Boolean.TRUE;
}
/**
* 反对评论
*
* @param comment
* @return
*/
@Deprecated
@ResponseBody
@RequestMapping(value = "/comment/commentoppose", method = RequestMethod.POST)
public boolean commentOppose(String cid) {
Comment comment = null;
try {
comment = commentService.queryCommentById(Integer.parseInt(cid));
} catch (Exception e) {
LOGGER.error("反对出错", e);
return Boolean.FALSE;
}
try {
comment.setOppose(comment.getOppose() + 1);
commentService.saveComment(comment);
} catch (Exception e) {
LOGGER.error("反对出错", e);
return Boolean.FALSE;
}
return Boolean.TRUE;
}
/**
* 分页获取评论列表
*
* @param comment
* @return
*/
@SuppressWarnings("rawtypes")
@Deprecated
@ResponseBody
@RequestMapping(value = "/comment/listcomment")
public Page listCommentByPage(Map<String, Object> map, String nrid,
int pageNo, int pageSize) {
try {
Page page = commentService.listComment(pageNo, pageSize,
CommentType.CONTENT.name(), nrid);
// map.put("pageComment", page);
return page;
} catch (Exception e) {
LOGGER.error("分页获取评论列表出错", e);
}
return null;
}
/**
* 查询分页信息,并将信息保存到page,最终显示在comment页面对应的小页面中
*
* @param model
* @param nrid 内容id
* @param pageNo 查询页
* @param pageSize 每页显示条数
* @return
*/
@SuppressWarnings("rawtypes")
@RequestMapping(value = "/comment/comments",method = {RequestMethod.GET
,RequestMethod.POST})
public String listCommentByPage(
Model model,
String nrid,
@RequestParam(value = "pageNo", required = false, defaultValue = "1") int pageNo,
@RequestParam(value = "pageSize", required = false, defaultValue = "2") int pageSize) {
Page page = null;
try {
page = commentService.listComment(pageNo, pageSize,
CommentType.CONTENT.name(), nrid);
model.addAttribute("pageComment", page);
} catch (Exception e) {
e.printStackTrace();
}
return "common/comment-data";
}
/**
* 查询分页信息,并将信息保存到page,最终显示在comment页面对应的小页面中
*
* @param model
* @param nrid 内容id
* @param pageNo 查询页
* @param pageSize 每页显示条数
* @return
*/
@SuppressWarnings("rawtypes")
@RequestMapping(value = "/comment/comments2",method = {RequestMethod.GET
,RequestMethod.POST})
public String listCommentByPage2(
Model model,
String nrid,
@RequestParam(value = "pageNo", required = false, defaultValue = "1") int pageNo,
@RequestParam(value = "pageSize", required = false, defaultValue = "2") int pageSize) {
Page page = null;
try {
page = commentService.listComment(pageNo, pageSize,
CommentType.CONTENT.name(), nrid);
model.addAttribute("pageComment", page);
} catch (Exception e) {
e.printStackTrace();
}
return "common/comicvedio-data";
}
}
Js中调用@ResponseBody返回值,统计剩余评论字数的js
/*用于统计评论剩余字数的js*/
var content = "";
var totalNum = 2000;
var comment = (function($){
return {
calcuate:function(){
content = $(this).val();
// 算出剩余有多少个字符可以填写
var lengthRemain = totalNum - content.length;
// console.log("lengthRemain = " + lengthRemain);
if (lengthRemain <= 0) {
content = content.substring(0, totalNum);
$(this).val(content);
lengthRemain = 0;
// 设置剩余数值的个数
$("#fontnum").text(lengthRemain);
} else {
// 设置剩余数值的个数
$("#fontnum").text(lengthRemain);
}
}
}
})(jQuery);
$(function(){
// 数字控制
$("#fontnum").text(totalNum);
// $("#content").on("keyup,keydown,blur,click",calcuate);
$("#pinglun").keyup(comment.calcuate);
$("#pinglun").keydown(comment.calcuate);
$("#pinglun").blur(comment.calcuate);
$("#pinglun").click(comment.calcuate);
$("#pinglun").mouseout(comment.calcuate);
});
/*评论字数统计结束*/
$(function() {
$('#comments_fb').click(function() {
sendComment();
});
$('#praise').click(function() {
contentDz();
});
});
/**
* 发表评论
*/
function sendComment() {
//获取到现有的评论数
var commentNum = parseInt($(".content #pls").text());
//重新设置评论数
$(".content #pls").text((commentNum + 1));
var commentContent = $('#pinglun').val();
if (!commentContent) {
alert('请填写评论内容');
return;
}
if (commentContent.length > 2000) {
alert('评论内容不能超过2000个字符');
return;
}
var sorce = $('#scoreHidden').val();
if (!sorce) {
sorce = 0;
}
var param = {
content : commentContent,
objectid : contentId,
score : sorce
}
$.ajax({
type : "POST",
url : contextPath + "/comment/add",
data : $.param(param),
//这里success是add返回值
success : function(success) {
if (success) {
alert("评论发表成功");
$('#pinglun').val('')
var pageNo = $("#pageIndexSelect").attr("value");
gotoPage(pageNo);
} else {
alert("评论发表失败,请登录后发评论");
}
}
});
}
/**
* 赞同评论
*/
function commentLike(cid, oEvent) {
$("#comment-agree").unbind("click");
$.ajax({
type : "POST",
url : contextPath + "/comment/commentlike",
data : "cid=" + cid,
//这里success是赞同返回值
success : function(success) {
if (success) {
$('#like_' + cid).text(parseInt($('#like_' + cid).text()) + 1);
$("#comment-agree").bind("click",commentLike);
}
}
});
}
/**
* 删除评论
*/
function commentDel(cid, oEvent) {
$.ajax({
type : "POST",
url : contextPath + "/comment/del",
data : "cid=" + cid,
//这里success是删除返回值
success : function(success) {
if (success) {
$('#comment_' + cid).remove();
} else {
alert("删除评论失败!");
}
}
});
}
/**
* 反对评论
*/
function commentOppose(cid, oEvent) {
$('#oppose_' + cid).text(parseInt($('#oppose_' + cid).text()) + 1);
$.ajax({
type : "POST",
url : contextPath + "/comment/commentoppose",
data : "cid=" + cid,
//这里success是反对返回值
success : function(success) {
if (success) {
} else {
$('#oppose_' + cid).text(
parseInt($('#oppose_' + cid).text()) - 1);
alert(friendTip);
}
}
});
}
/**
* 重新加载评论
*
* @deprecated
*/
function reloadComment(pageNo) {
var param = {
nrid : contentId,
pageNo : pageNo ? pageNo : 1,
pageSize : 5
}
$
.ajax({
type : "GET",
url : contextPath + "/comment/listcomment",
data : $.param(param),
//这里Page是/comment/listcomment返回分页值
success : function(page) {
if (page) {
var lst = page.recordList;
// 评论信息
var html = '';
// console.log(lst);
for ( var j = 0; j < lst.length; j++) {
var one = lst[j];
html += '<dl id="comment_' + one.cid + '">';
html += '<dt><img src="'
+ contextPath
+ '/resources/cartoon2/images/content_read/pic03.jpg" width="58" height="58" /></dt>';
html += ' <dd>';
try {
if (one.user.userName) {
html += '<a href="' + contextPath
+ '/portal/index/'
+ one.user.userId + '">'
+ one.user.userName + '</a>'
+ '<br/>';
} else {
html += '<a href="' + contextPath
+ '/portal/index/'
+ one.user.userId + '">匿名</a>'
+ '<br/>';
}
} catch (e) {
}
html += one.content + '<br/>';
html += '<div class="fr gray" >';
html += new Date(one.commentTime)
.format("yyyy-MM-dd hh:mm:ss")
html += '<a href="javascript:void(0);" onclick="commentLike('
+ one.cid
+ ',event)"> 赞同</a>(<span id="like_'
+ one.cid
+ '">'
+ one.likecount
+ '</span>)';
html += '</div>';
html += ' </dd>';
html += '<div class="clear"></div>';
html += ' </dl>';
}
$('#commentWrapper').html(html);
function commonAppend(i) {
var li = '';
if (i == page.pageNum) {
li = '<li class="aa1" ><a href="javascript:void(0)" onclick="reloadComment('
+ i + ')" >' + i + '</a></li>';
} else {
li = '<li ><a href="javascript:void(0)" onclick="reloadComment('
+ i + ')" >' + i + '</a></li>';
}
return li;
}
// 分页
var html2 = '';
html2 += '<ul>';
if (page.allRows > 5) {
html2 += commonAppend(1);
}
if (page.allPages != 1) {
if (page.allPages <= 5) {
for ( var i = 2; i <= page.pageNum; i++) {
html2 += commonAppend(i);
}
} else {
if (page.pageNum - 3 > 2) {
html2 += '<li>... </li>';
}
for ( var i = page.pageNum - 3; i <= page.pageNum; i++) {
if (i <= 1) {
continue;
}
html2 += commonAppend(i);
}
}
if (page.pageNum >= page.allPages - 4
|| page.allPages - 4 <= 0) {
for ( var i = page.pageNum + 1; i <= page.allPages; i++) {
html2 += commonAppend(i);
}
} else {
for ( var i = page.pageNum + 1; i <= page.pageNum + 3; i++) {
html2 += commonAppend(i);
}
html2 += '<li>... </li>';
html2 += commonAppend(page.allPages);
}
}
html2 += '</ul>';
$('#page').html(html2);
$('#pls').html(page.allRows);
}
}
});
}
/**
* 这里是新的评论加载页面
*
* @param pageNo
*/
function gotoPage(pageNo) {
$.ajax({
type : "POST",
url : contextPath + "/comment/comments",
data : {
nrid : contentId,
pageNo : pageNo ? pageNo : 1,
pageSize : 5
},
dataType : 'html',
success : function(data) {
$("#common-comment-list").children().remove();
$("#common-comment-list").html(data);
}
});
}
/**
* 点击确定按钮之后执行的js代码
*/
function confirmButton(){
var pageNum = $("#pageNumInput").val();
//这一句专为输入框中获取参数
if(pageNum == "") {
alert("对不起,您还没有填写页码!");
}
//获得总页数
var pageCount = $("#pageCount").val();
if(pageNum < 1) {
this.gotoPage(1);
} else if (pageNum > pageCount) {
this.gotoPage(pageCount);
} else {
this.gotoPage(pageNum);
}
}
/**
* 点赞
*/
function contentDz() {
$("#praise").unbind("click");
$.ajax({
type : "POST",
url : contextPath + "/content/dz/" + contentId,
success : function(success) {
if (success) {
$('#dzs').text(parseInt($('#dzs').text()) + 1);
$("#praise").bind("click",contentDz);
}
}
});
}
2、@RequestParam默认值,@PathVariable的用法
package com.kuman.cartoon.controller.friendsfuns;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.kuman.cartoon.common.Page;
import com.kuman.cartoon.common.controller.BaseController;
import com.kuman.cartoon.entity.Friend;
import com.kuman.cartoon.entity.User;
import com.kuman.cartoon.service.UserService;
/**
* "我的好友"和"我的粉丝"部分的代码
*
* 修改原来的好友和粉丝部分的代码
*
* @author to.to
*/
@Controller
@RequestMapping(value = "/friendsAndFuns", method = { RequestMethod.GET,
RequestMethod.POST })
@SessionAttributes(value = { "accountid", "account" })
public class FriendsAndFuns extends BaseController {
@SuppressWarnings("unused")
private static final Logger LOGGER = LoggerFactory
.getLogger(FriendsAndFuns.class);
@Autowired
UserService userService;
/**
* 跳转到"我的好友"和"我的关注页面"
*
* @param userId
* 用户登录用的Id
* @param friendId
* 登录用户的好友的Id
* @param pageNo
* 当前页码数
* @param pageRow
* 每页显示条数
* @return
*/
@RequestMapping(value = "/toFriendFuns/{userId}")
public String toFriendFuns(
Model model,
@PathVariable("userId") int userId,
@RequestParam(value = "pageNo", required = false, defaultValue = "1") int pageNo,
@RequestParam(value = "pageRow", required = false, defaultValue = "12") int pageRow,
@RequestParam(value = "friendId", required = false, defaultValue = "-1") int friendId) {
// 1、判断用户是否登陆过了,如果登录过了直接进入到后续过程
User user = isLogin(model);
if (null == user) {
return "redirect:/user/login";
} else {
// 如果有了直接调转到登陆页面
// LOGGER.info("friendId = " + friendId);
// LOGGER.info("pageNo = " + pageNo);
// LOGGER.info("pageRow = " + pageRow);
model.addAttribute("user", user);
model.addAttribute("friendId", friendId);
model.addAttribute("pageNo", pageNo);
model.addAttribute("pageRow", pageRow);
return "/web/friendsfuns/friendfuns";
}
}
/**
* 显示关注的用户
*
* @param map
* @param userId
* @param pageNo
* @param pageRow
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@RequestMapping(value = "/follow/{userId}", produces = { "text/html" })
public String showFollow(
Map<String, Object> map,
Model model,
@PathVariable("userId") int userId,
@RequestParam(value = "friendId", required = false, defaultValue = "-1") int friendId,
@RequestParam(value = "pageNo", required = false, defaultValue = "1") int pageNo,
@RequestParam(value = "pageRow", required = false, defaultValue = "12") int pageRow) {
// 1、判断用户是否登录了,如果登录了直接查询,如果没有要跳转到登录页面
User loginedUser = isLogin(model);
if (null == loginedUser) {
return "redirect:/user/login";
} else {
User user = userService.queryUser(userId, false);
Page page = userService.queryUserByFansId(pageNo, pageRow,
user.getUserId());
// 关注的好友
List<Object> fUserList = new ArrayList<Object>();
for (Object o : page.getRecordList()) {
Friend friend = (Friend) o;
// 关注的好友
User fUser = friend.getUser();
// 关注的好友所关注的好友
List<Friend> friendList = userService.queryUserByFansId(fUser
.getUserId());
if (!CollectionUtils.isEmpty(friendList)) {
fUser.setFollowCount(friendList.size());
}
fUserList.add(friend);
}
page.setRecordList(fUserList);
// 用户信息
map.put("user", user);
map.put("page", page);
return "/web/friendsfuns/follow";
}
}
/**
* 用于模拟跳转到"动态管理"页面中去
*
* @param model
* @return
*/
@RequestMapping(value = "/toUserDy/{userId}")
public String toUserDy(Model model, @PathVariable("userId") int userId) {
return "/web/friendsfuns/userdy";
}
/**
* 获取粉丝信息
*
* @param map
* @param userId
* @param pageNo
* @param pageRow
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@RequestMapping(value = "/funs/{userId}", produces = { "text/html" })
public String showFuns(
Map<String, Object> map,
Model model,
@PathVariable("userId") int userId,
@RequestParam(value = "friendId", required = false, defaultValue = "-1") int friendId,
@RequestParam(value = "pageNo", required = false, defaultValue = "1") int pageNo,
@RequestParam(value = "pageRow", required = false, defaultValue = "12") int pageRow) {
// 1、判断用户是否已经登录进去了,如果登录进去了,则可以查询自己的粉丝
User loginedUser = isLogin(model);
if (null == loginedUser) {
return "redirect:/user/login";
} else {
User user = userService.queryUser(userId, false);
Page page = userService.queryFansByUserId(pageNo, pageRow, userId);
// 粉丝
List<Object> fUserList = new ArrayList<Object>();
for (Object o : page.getRecordList()) {
Friend friend = (Friend) o;
// 粉丝
User fUser = friend.getFans();
// 粉丝所关注的好友
List<Friend> friendList = userService.queryUserByFansId(fUser
.getUserId());
if (!CollectionUtils.isEmpty(friendList)) {
fUser.setFollowCount(friendList.size());
}
fUserList.add(friend);
}
page.setRecordList(fUserList);
map.put("user", user);
map.put("page", page);
return "/web/friendsfuns/funs";
}
}
}