这是我的JSP
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!doctype html>
<html>
<head>
<script src='https://cdn.firebase.com/js/client/1.0.17/firebase.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'></script>
<link rel='stylesheet' type='text/css' href='../css/example.css'>
</head>
<body>
<div id='messagesDiv'></div>
<input type='text' id='nameInput' placeholder='Name'>
<input type='text' id='messageInput' placeholder='Message'>
<script>
var myDataRef = new Firebase('https://shining-fire-5148.firebaseio.com/');
$('#messageInput').keypress(function (e) {
if (e.keyCode == 13) {
var address1 = $('#nameInput').val();
var address2 = $('#messageInput').val();
myDataRef.push({Address1: address1, Address2: address2});
$('#messageInput').val('');
}
});
myDataRef.on('child_added', function(snapshot) {
var message = snapshot.val();
displayChatMessage(message.Address1, message.Address2);
});
function displayChatMessage(name, text) {
$('<div/>').text(text).prepend($('<em/>').text(name+': ')).appendTo($('#messagesDiv'));
$('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
};
</script>
</body>
</html>
这是我的控制器 包控制器;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
@WebServlet("/test.jsp")
public class MyServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws IOException, ServletException {
DateFormat dateFormat;
PrintWriter out = response.getWriter();
try {
dateFormat = new SimpleDateFormat(request.getParameter("format"));
} catch (Exception e) {
dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:MM:ss");
}
String date = dateFormat.format(new Date());
request.setAttribute("date",date);
// request.getRequestDispatcher("/messages.jsp").forward(request, response);
}
}
控制器完全删除了我页面上的所有内容,为什么?我只想将日期变量传递给它,以便在我的jsp上我可以调用$ {date} ...如何编写servlet以不删除页面上存在的所有内容?
答案 0 :(得分:0)
如果我理解你的问题,
控制器完全删除了我页面上的所有内容,为什么?
而不是
request.getRequestDispatcher("/messages.jsp").forward(request, response);
使用RequestDisplatcher.include(ServletRequest, ServletResponse)
request.getRequestDispatcher("/messages.jsp").include(request, response);
来自forward
javadoc,
将来自servlet的请求转发到服务器上的另一个资源(servlet,JSP文件或HTML文件)。此方法允许一个servlet对请求进行初步处理,并允许另一个资源生成响应。
与include
javadoc相比,
在响应中包含资源(servlet,JSP页面,HTML文件)的内容。从本质上讲,这种方法可以实现程序化服务器端包含。