Spring3 MVC中Ajax的使用

来源:http://hhdem.com/2012/01/30/spring3-mvc-ajax-sample/

现在已经开始使用Spring3了,MVC虽然用了很久不过Ajax一直通过DWR实现,不过既然Spring3已经支持Ajax访问,那就必须折腾下了。

1. 首先,新建Controller类用于接收ajax请求,这里建立AjaxCheckController,目的是检查注册用户是否已经存在

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Controller
@RequestMapping ( "/a" )
public class AjaxCheckController extends BaseController {
 
   @Autowired
   private UserManager userManager;
 
   @RequestMapping (value = "/checkexists/loginname/{loginName}" , method = RequestMethod.GET)
   public @ResponseBody Map<String, Object> checkLoginNameExists( @PathVariable String loginName) {
     User user = userManager.findUserByLoginName(loginName);
     Map<String, Object> modelMap = new HashMap<String, Object>();
     modelMap.put( "exists" , user != null );
     return modelMap;
   }
 
   @RequestMapping (value = "/checkexists/email" , method = RequestMethod.GET)
   public @ResponseBody Map<String, Object> checkEmailExists( @RequestParam (value = "email" , required = true ) String email) {
     User user = userManager.findUserByEmail(email);
     Map<String, Object> modelMap = new HashMap<String, Object>();
     modelMap.put( "exists" , user != null );
     return modelMap;
   }
 
}

2. 请求页面,在这里就是注册页面了,部分js代码如下:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
function loginOnChange(event) {
             ....
               $.ajax({
                 type : 'GET' ,
                 contentType : 'application/json' ,
                 url : 'a/checkexists/loginname/' +loginname,
                 dataType : 'json' ,
                 success : function (data) {
                     if (data && data.exists) {
                     log_tip_div.style.display = "inline" ;
                 log_tip.innerHTML= "<img src='<@common.basePath/>/img/exclamation.gif'/> 该用户名已经被使用" ;
                 canSub = false ;
                 loginUserError = true ;
                 isLoginUserExists = true ;
                     } else {
                 log_tip_div.style.display = "inline" ;
                 log_tip.innerHTML= "<img src='<@common.basePath/>/img/fit.gif'/> 用户名可以使用" ;
                 canSub = true ;
                 loginUserError = false ;
                 isLoginUserExists = true ;
                 }
                 },
                 error : function () {
                   alert( "error" )
                 }
             });
 
         .....
           }
 
           function emailOnChange(event) {
             ....
               $.ajax({
                 type : 'GET' ,
                 contentType : 'application/json' ,
                 url : 'a/checkexists/email' ,
                 data: 'email=' +email,
                 dataType : 'json' ,
                 success : function (data) {
               if (data && data.exists) {
                 email_tip_div.style.display = "inline" ;
                 email_tip.innerHTML= "<img src='<@common.basePath/>/img/exclamation.gif'/> 该邮箱已经注册过" ;
                 canSub = false ;
                 emailError = true ;
                 isEmailExists = true ;
               } else {
                 email_tip_div.style.display = "inline" ;
                 email_tip.innerHTML= "<img src='<@common.basePath/>/img/fit.gif'/> 邮箱未被注册过,可以使用" ;
                 canSub = true ;
                 emailError = false ;
                 isEmailExists = true
               }
             },
                 error : function () {
                   alert( "error" )
                 }
             });
         ....
           }

到此就可以了,可以通过jquery轻松访问Spring的Controller,是不是很简单呀!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Spring MVCAJAX 可以相互调用,具体步骤如下: 1. 在 Spring MVC 的控制器定义一个处理 AJAX 请求的方法,使用 @ResponseBody 注解将方法返回值转化为 JSON 格式。 2. 在前端页面使用 AJAX 发送请求到该方法。 3. 接收到请求后,Spring MVC 控制器处理请求并返回 JSON 数据。 4. 在前端页面使用 JavaScript 解析 JSON 数据,完成页面的渲染和交互。 具体实现方式可以参考以下代码: 1. Spring MVC 控制器的方法: ``` @RequestMapping(value = "/ajax", method = RequestMethod.GET) @ResponseBody public Map<String, Object> handleAjaxRequest() { Map<String, Object> result = new HashMap<>(); // 处理 AJAX 请求,返回数据 result.put("key1", "value1"); result.put("key2", "value2"); return result; } ``` 2. 前端页面AJAX 请求: ``` $.ajax({ url: "/ajax", type: "GET", dataType: "json", success: function(data) { // 处理返回的 JSON 数据 console.log(data); }, error: function(xhr, status, error) { // 处理请求失败的情况 console.log("AJAX request failed: " + status + ", " + error); } }); ``` 注意,在 Spring MVC 的配置文件,需要添加以下配置,以支持将方法返回值转化为 JSON 格式: ``` <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值