在不刷新的情况下更新jsp页面的内容

Updating contents of a jsp page without refreshing

本文关键字:jsp 更新 刷新 情况下      更新时间:2023-09-26

我有一个显示表内容的jsp页面。当用户查看页面时,表的内容会一秒一秒地变化。因此,用户每次都必须刷新页面才能看到新鲜更新的内容。如何在不刷新页面的情况下更新jsp页面的内容。我想要一个像gmail.com一样的功能,邮箱的大小不断增加,用户不会刷新。

您应该研究使用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";
        }
    }
}

然后,这将在div中添加一个缓慢滚动的html,说明它是否有效,home的代码如下。。。

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

您可以发出ajax请求,从服务器提取数据,并使用java脚本在视图上呈现该数据