1.下载jackson依赖的jar包例如以下下载地址:jackson-all
http://jackson.codehaus.org/1.9.11/jac/jackson-all-1.9.11.jar
2.demo
2.1servlet传输java对象到jsp页面
Controller.java
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
private ObjectMapper objectMapper = new ObjectMapper();
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String action = request.getRequestURI();
String url = action.substring(action.lastIndexOf("/"),action.lastIndexOf(".do"));
if(url.equals("/reply")){
response.setContentType("application/json;charset=UTF-8");
Reply reply = new Reply();
reply.setContent(request.getParameter("content"));
reply.setTime(getTime());
objectMapper.writeValue(response.getOutputStream(), reply);
}
}
}
Reply.java
public class Reply {
private Integer id;
private String content;
private Date time;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getCommentId() {
return commentId;
}
public void setCommentId(Integer commentId) {
this.commentId = commentId;
}
public Reply() {
}
public Reply(Integer id, String content, Date time) {
this.id = id;
this.content = content;
this.time = time;
}
}
reply.jsp
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.js"></script>
<script type="text/javascript">
$(function(){
//回复进行ajax提交
$("#reply").bind("click",function(){
var data = $("textArea[name='content']").val();
var commentId = $(":hidden[name='commentId']").val();
$.ajax({
type:"get",
url:"reply.do",
data:"content="+data+"&commentId="+commentId,
dataType:"json",
success:function(data){
//克隆一个回复的div
var div = $(".reply:eq(0)").clone();
var time = getTime(new Date(data.time));
$(div).find("div:eq(0) span:eq(0)").text(data.userId);
$(div).find("div:eq(0) span:eq(1)").text(time);
$(div).find("div:eq(1)").text(data.content);
$(div).css("display","block");
$(".main-reply").append(div);
},
error:function(){
alert("系统异常!");
},
async:true
});
});
function getTime(date){
var now = "";
now = date.getFullYear()+"-";
now += (date.getMonth()+1)+"-";
now += (date.getDate())+" ";
now += ((date.getHours()))+":";
now += (date.getMinutes())+":";
now += (date.getSeconds());
return now;
}
});
</script>
这样后台可以将java对象传送到前台页面