在我的Java Spring应用程序中,我一直试图弄清楚为什么当我在jsp页面中提醒此变量时,该变量始终返回null。我已经放置了系统控制台日志,它会打印实际值,但是在jsp页面中检索它时,它为null。
这是我在控制器中的尝试
String sound = "sound.mp3";
request.getSession().setAttribute("mp3", sound);
String mp3 = (String) request.getSession().getAttribute("mp3");
System.out.println("this is the sound notification>>>>>> " + mp3); //this returns the actual value
尝试在jsp页面中检索值时,它返回null,这是尝试
<script>
function getNotify() {
<% String mp3 = (String) request.getSession().getAttribute("mp3"); %>
var mp3 = "<%= mp3 %>";
alert(mp3);
setInterval(getNotify, 20000);
</script>
编辑:这是完整的控制器
@ResponseBody
@RequestMapping(value = "/post-book", method = RequestMethod.POST)
public ModelAndView postBook(HttpServletRequest request,
HttpServletResponse response,
@RequestParam String message,
@RequestParam String noteVal,
@CookieValue(required = true) String name,
@CookieValue(required = true) String emailaccess,
@CookieValue(required = true) String token) {
String token2 = (String) request.getSession().getAttribute("token");
String emailToken = (String) request.getSession().getAttribute("emailaccess");
try {
// fetch user info
User user = _userDao.getByToken(token);
if (user == null) {
return logout(request, response);
}
//}
Date today = new Date();
//formatting date in Java using SimpleDateFormat
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String date2 = DATE_FORMAT.format(today);
System.out.println("Today in dd-MM-yyyy format : " + date2);
// create new book object
Books book = new Books();
book.setMessage(message);
book.setUser(user);
book.setTimestamp(date2);
// save book in db
_bookDao.save(book);
String sound = "postnotificationsound.mp3";
request.getSession().setAttribute("sound", sound);
String mp3 = (String) request.getSession().getAttribute("sound");
System.out.println("this is the sound notification>>>>>> " + mp3); //this returns the actual value
System.out.println("this is the sound notification2>>>>>> " + noteVal);
} catch (Exception e) {
logger.error("Exception in saving book: ", e.getStackTrace());
e.printStackTrace();
}
return null;
}
请协助
最佳答案
好吧,“ $ {}”用于获取由控制器设置的会话值。就你而言
“ $ {mp3}”将达到目的。
试试看->
<script>
function getNotify() {
var mp3 = "${mp3}";
alert(mp3);
setInterval(getNotify, 20000);
}
</script>