2012-02-14 233 views
4

我有一個顯示錶格內容的jsp頁面。 用戶查看頁面時,表格的內容會逐秒更改。 因此,用戶必須每次刷新頁面以查看新鮮和更新的內容。 如何更新jsp頁面的內容而不必刷新頁面。 我想要一個功能,就像gmail.com一樣,郵箱的大小不斷增加,用戶不會刷新。更新jsp頁面的內容而不刷新

回答

7

你應該看看使用Ajax(jQuery是我的首選方法)。

http://api.jquery.com/jQuery.get/

http://api.jquery.com/jQuery.post/

這將然後打一個控制器,它會回報你想要的數據而無需刷新頁面。

因此,舉例來說,如果你有一個login.jsp的...

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
<%@ page session="true" %> 
<html> 
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 
<head> 
    <title>Login</title> 
</head> 
<body> 
<h1> 
    Hello please login to this application 
</h1> 
<script> 

     function login(){ 
      var username = $("#username").val(); 
      var password = $("#password").val(); 

      $.post('login', { username : username , password : password }, function(data) { 
       $('#results').html(data).hide().slideDown('slow'); 
      }); 
     } 

</script> 
Username : <input id="username" type="text" /> 
Password : <input id="password" type="password" /> 
<input name="send" type="submit" value="Click me" onclick="login()" /> 
<form name="next" action="auth/details" method="get"> 
    <input name="send" type="submit" value="Go Through"/> 
</form> 
<div id="results" /> 
</body> 
</html> 

在你的控制,你會然後打的型號,但爲了簡單起見,我做了一個很簡單的例子.. 。

/** 
* Handles requests for the application home page. 
*/ 
@Controller 
public class LoginController { 

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class); 

    Util util; 

    /** 
    * Simply selects the home view to render by returning its name. 
    */ 
    @RequestMapping(value = "/login", method = RequestMethod.POST) 
    public String home(Locale locale, Model model, String username, String password) { 


     if(username.equalsIgnoreCase("david")) 
     { 
      model.addAttribute("validUser", "Welcome " + username); 

      return "home"; 
     } 
     else 
     { 
      model.addAttribute("validUser", "Incorrect username and password"); 
      return "home"; 
     } 

    } 

} 

這再加入HTML緩慢滾動位到div說,如果它是有效的,爲家庭的代碼如下...

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
<%@ page session="true" %> 
<html> 
<body> 
<P> ${validUser}. </P> 
</body> 
</html> 
+0

你能提供做同樣的JSP頁面的樣本數據。 – 2012-02-14 16:23:35

+0

示例添加的重要位是$ .post ... – david99world 2012-02-14 16:38:08

2

可以使Ajax請求,並從服務器提取數據,並使用Java腳本來渲染視圖上

+1

您可以提供一個jsp頁面的樣本做同樣的 – 2012-02-14 16:24:34