springMVC框架中的ajax驗證

固然,你在使用springMVC以前須要進行環境的配置,這裏就不講了,直接上代碼.javascript

在使用springMVC以前,我在使用ajax驗證的時候,須要用到一個解析json的jar包:將數據經過ajax拿到後臺servlet,再經過jsonObject對象進行來像前臺進行數據的傳遞.像下面這樣:html

JSONObject j = new JSONObject();
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

j.put("msg", "該用戶名已被註冊");
out.write(j.toString());

使用起來仍是很方便的.可是在學習到了框架以後,尤爲是使用到了springMVC以後,使用起來就更方便了.下面是使用過程,其實和以前的使用是同樣的.java

 

這是實體類:set/get代碼就不貼了jquery

 

1 public class User {
2     private int uid;
3     private String uname;
4     private String password;

jsp代碼:注意導入jquery包,在這裏咱們使用jquery的ajax驗證web

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    
    <script type="text/javascript" src="resource/js/jquery-1.8.2.js"></script>
    <script type="text/javascript">
        $(function(){
        
            $("#password").blur(function(){
                $.ajax({
                    url:"user/ajax",
                    data:{uname:$("#uname").val(),password:$("#password").val()},
                    type:"post",
                    success:function(data){
                        alert(data);
                    }
                });
            });
        });
    </script>
  </head>
  
  <body>
        用戶名<input id="uname" type="text" name="uname">
        密碼<input id="password" type="password" name="password">
  </body>
</html>

後臺代碼:這裏使用的是springMVC的註解方式,須要在具體的ajax驗證方法的上面標註@ResponseBody.return的內容就是你要在前臺頁面上要處理的數據.ajax

 
 

 

package com.mi.controller;



import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.mi.entity.User;
@Controller
@RequestMapping("user")
public class MyController extends MultiActionController{
    @RequestMapping(value="ajax",produces={"text/html;charset=utf-8;"})
    @ResponseBody
    public Object ajax(User user){
        System.out.println(user.getUname());
        System.out.println(user.getPassword());
        System.out.println(user);
        return user.getPassword();
    }
}

大概就是這些,暫時先學了這麼一些,作一個小小的總結,以後有新的知識再進行更新.spring

相關文章
相關標籤/搜索