由于之前我写过几篇关于如何搭建springmvc项目的日志,故在本文中不在写各种配置怎么写。只写涉及到处理ajax请求的代码。如果有想了解springmvc项目怎么搭建的朋友,请选择如下合适你的链接进去交流。
springmvc+mybatis+spring整合
springmvc+spring+hibernate整合
不整合任何框架的springmvc环境
好,正文开始
controller的代码
package com.action; import java.io.unsupportedencodingexception; import java.util.list; import javax.annotation.resource; import javax.servlet.servletcontext; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpsession; import org.springframework.stereotype.controller; import org.springframework.ui.modelmap; import org.springframework.web.bind.annotation.modelattribute; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.requestparam; import org.springframework.web.bind.annotation.responsebody; import org.springframework.web.bind.annotation.sessionattributes; import com.bean.user; import com.service.iuserservice; /** * action层我也是用注解配的,这里面的注解@requestmapping的具体作用见上一篇springmvc入门笔记 * @author 百木森森 * */ @controller @requestmapping("testpath") public class testaction { @resource private iuserservice userservice; @requestmapping("ajaxtest") @responsebody public modelmap ajaxtest(){ system.out.println("进ajax的action了"); modelmap model=new modelmap(); model.addattribute("key", "i'm value"); return model; } }网页的写法
<%@ page language="java" contenttype="text/html; charset=gb2312" pageencoding="gb2312"%> <% string path = request.getcontextpath(); string basepath = request.getscheme()+"://"+request.getservername()+":"+request.getserverport()+path+"/"; %> <!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=gb2312"> <script type="text/javascript" src="/<%=path%>/js/jquery-1.10.2.js"></script> <script type="text/javascript"> $(function(){ alert("ajax一级准备!"); $.ajax({ url:"<%=path%>/testpath/ajaxtest.action", type:"post", success:function(data){ alert(data.key); } }) }) </script> <title>insert title here</title> </head> <body> <h1>success!!!</h1><br/> </body> </html>
控制台打印结果
页面加载后的效果
以上是一个非常简单的ajax操作,不包含json的传值,下面贴一个包含了json传值的代码
controller中的代码
@requestmapping("queryuseradvice") @responsebody public modelmap queryuseradvice(modelmap model, @requestparam int pageno, @requestparam int pagesize){ int count=this.qyjuseradviceservice.querycount();//从数据库查满足条件的数据的数量 int totalpage=count%pagesize==0?count/pagesize:count/pagesize+1;//计算共有几页 //将总页数和所有要传回页面的数据集合存入model中 model.addattribute("totalpage", totalpage); model.addattribute("advicelist", this.qyjuseradviceservice.queryadvice(pageno, pagesize)); return model; }
js代码(只包含ajax部分)
function queryadviceby(pageno, pagesize) { $("#none").hide(); $.ajax({ type:"post", url:"advicetest/queryuseradvice", cache:false, datatype:"json", data:{ pageno:pageno, pagesize:pagesize }, success:function(data) { //省略回调函数的内容 //想得到controller中传回的值得话像如下这样做 data.totalpage data.advicelist ?} }); }