spring doesn't execute javascript - java

I use Spring MVC 3 in my project.
This is my AddressController :
#Controller
public class AddressController {
private static Logger logger = Logger.getLogger(AddressController.class);
#RequestMapping(value="/address",method=RequestMethod.GET)
public ModelAndView init(
#RequestParam(value="language",required=false,defaultValue="fr") String language){
Locale locale = new Locale(language);
logger.info("here");
String[] isoCountries = locale.getISOCountries();
Map<String,String> treeMap = new TreeMap<String,String>();
for(String isoCountry : isoCountries){
Locale countryLoc = new Locale(language, isoCountry);
String name = countryLoc.getDisplayCountry(locale);
if(!"".equals(name)){
treeMap.put(name,name);
}
}
Map<String,String> tree = new TreeMap<String,String>(treeMap);
ModelAndView modelAndView = new ModelAndView("address");
modelAndView.addObject("address",new Address());
modelAndView.addObject("countriesList", tree);
return modelAndView;
}
}
The first time, when I executed /address, it's going well to my controller and it returns my address.jsp by executing the javascript in this last one. But when I execute /address?language=fr or /address?language=en, the javascript code of my address.jsp is not executed.
This is a part of my address.jsp :
<%#page import="org.springframework.context.i18n.LocaleContextHolder"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="forms" uri="http://www.springframework.org/tags/form" %>
<%#page import="com.application.myGoogleAppEngine.Internationale"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page import="java.util.Locale" %>
<%# page import="java.util.List" %>
<%# page import="java.util.ArrayList" %>
<%# page import="java.util.Collections" %>
<html>
<head>
<jsp:include page="ressources.jsp"></jsp:include>
<link rel="stylesheet" type="text/css" href="stylesheets/320x480/portrait/address.css" />
<%! Internationale internationale = Internationale.getInstance(); %>
<script>
$(document).ready(function(){
//checkParams();
alert("here");
var unit = "em";
alert("here2");
$("#backButton").attr("href","/index");
$('#validationBtn').click(function(){
var streetName = $('#streetName').val();
var streetNumber = $('#streetNumber').val();
var zipCode = $('#zipCode').val();
var city = $('#city').val();
var country = $('#country').val();
var ref = "MyServlet?streetName="+streetName+"&streetNumber="+streetNumber+"&zipCode="+zipCode+"&city="+city+"&country="+country;
$(this).attr("href",ref);
});
});
//rest of the script
</script>
<body>
<a id="backButton" data-role="button" data-icon="arrow-l"
data-ajax="false">
<spring:message code="backButton"/>
</a></div>
//rest of the code
</body>

In web MVC spring serves as server side technology. Javascript is client (browser) side technology, thus Spring "cannot" execute javascript.

Related

How to pass the values from Spring controller to JSP

I have Spring controller and I am setting a model value and want to display in my JSP:
public class TestController {
#RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello(Model model){
model.addAttribute("message", "Programmer Gate");
return "/test";
}
}
My test.jsp code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Welcome</title>
</head>
<body>
<%
double num = Math.random();
if (num > 0.95) {
%>
<h2>You'll have a luck day!</h2><p>(<%= num %>)</p>
<%
} else {
%>
<h2>Well, life goes on ... </h2><p>(<%= num %>)</p>
<%
}
%>
<p>${message}</p>
</body>
</html>
I am not seeing the message value as the JSP rendering as follows:
Well, life goes on ...
(0.3343913194169942)
${message}
How to access the model message variable value in the JSP?

Using jquery to show time every 3 seconds does not work properly

I am very new at "jsp" and "jquery", I think the code below should display a number on screen and increase it by one every 3 seconds, but after 2 or 3 repetitions it breaks and starts to show wrong numbers
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<script type="text/javascript" src="js/jquery-1.11.2.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function () {
$('#load_me').load('index.jsp').fadeIn("fast");
}, 3000); // autorefresh the content of the div after
//every 3000 milliseconds(3sec)
</script>
</head>
<body>
<%! int i = 0;%>
<div id="load_me">
<%out.print(++i);%>
</div>
</body>
</html>
I even tried to show time instead of printing a number, but the same problem accrued :
<%# page import="java.text.SimpleDateFormat" %>
<%# page import="java.util.Date" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<script type="text/javascript" src="js/jquery-1.11.2.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function () {
$('#load_me').load('index.jsp').fadeIn("fast");
}, 3000); // autorefresh the content of the div after
//every 3000 milliseconds(3sec)
</script>
</head>
<body>
<div id="load_me">
<%
Date d = new Date();
SimpleDateFormat sp = new SimpleDateFormat("hh:mm:ss");
String t= sp.format(d);
out.print(t);
%>
</div>
</body>
</html>
it seems you want a 'div#load_me' should display a number increment of 1 every 3 seconds.. Try the following plain javaScript for the same:
setInterval((function() {
var currNumber = 0;
return function() {
document.getElementById('load_me').innerHTML = ++currNumber;
}
})(), 3000);
EDIT (To demonstrate the full code) :
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<!-- we do not need jquery any more :-) -->
</head>
<body>
<div id="load_me">
</div>
<script>
setInterval((function() {
var currNumber = 0;
return function() {
document.getElementById('load_me').innerHTML = ++currNumber;
}
})(), 3000);
</script>
</body>
</html>
And this way you can avoid the unnecessary server calls as well.
This code below works for time showing, but you have to create date.jsp page,
<%# page import="java.text.SimpleDateFormat" %>
<%# page import="java.util.Date" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<script type="text/javascript" src="js/jquery-1.11.2.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function () {
$('#load_me').load('date.jsp').fadeIn("slow");
}, 3000);
</script>
</head>
<body>
<div id="load_me">
<%# include file="date.jsp"%>
</div>
</body>
</html>
date.jsp :
<%# page import="java.util.Date" %>
<%# page import="java.text.SimpleDateFormat" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
</head>
<body>
<%
Date d = new Date();
SimpleDateFormat sp = new SimpleDateFormat("hh:mm:ss");
String t= sp.format(d);
out.print(t);
%>
</body>
</html>

Spring MVC modelAndView object in javascript

Problem:
I have a simple controller which returns me a list of hardcoded locations. When i want to get my locations in my javascript file using $.get and print it in my console, i get some weird "undefined" results.
Controller:
#RestController
#RequestMapping("/locationOverview")
public class LocationOverviewController {
private LocationGuide service;
public LocationOverviewController() {
this.service = new LocationGuide("Memory");
}
#RequestMapping(method = RequestMethod.GET)
protected ModelAndView getLocations() {
ArrayList<Location> locations = new ArrayList<Location>();
locations.add(new Location(1,"KHL",new Geolocation(51,51)));
locations.add(new Location(2,"KUL",new Geolocation(51,51)));
return new ModelAndView("locationOverview", "locations", locations);
}
}
mapScript JS:
function initialize() {
$.get("locationOverview.htm", function(data){
for(var i=0; i<data.length; i++){
console.log(data[i].name);
}
})
}
JSP file:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="domain.Location"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Leuven Speaks</title>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
<script type="text/javascript" src="<c:url value="/js/mapScript.js" />"></script>
</head>
<body onload="initialize()">
<jsp:include page="header.jspf"/>
</body>
</html>
You should actually inspect with dev tools what that data contains. The controller method you show us looks like it is not the one mapped to locationOverview.htm. If you want to query data with ajax, return the list using the #ResponseBody annotation instead.
Data passed in a model would be available in the JSP page that you define as the view in ModelAndView.
Some learning resources:
http://www.beingjavaguys.com/2014/05/json-response-with-responsebody_31.html
https://developer.chrome.com/devtools/docs/javascript-debugging

How do I reset a ModelAttribute in Spring 3?

I just started with Spring MVC so it's probably a rookie mistake.
The ModelAttribute is reused every request. How can I make sure every POST starts with a clean object?
My controller (MyController.java):
#Controller
public class MyController {
#RequestMapping(method = RequestMethod.POST)
public String processChoice(#ModelAttribute("myData") MyData myData, BindingResult bindingResult) {
System.out.println("POST: myData = " + myData);
return "redirect:/myview?choice=" + myData.getChoice();
}
#RequestMapping(method = RequestMethod.GET)
public String displayChoice(#RequestParam(required = false) String choice, Model model) {
System.out.println("GET: Choice = " + choice);
model.addAttribute("myData", new MyData(choice));
return "myview";
}
}
My view (myview.jsp):
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Spring Tests</title>
</head>
<body>
<form:form modelAttribute="myData" method="POST">
<form:select path="choice">
<option></option>
<option value="one">One</option>
<option value="two">Two</option>
</form:select>
<input type="submit" value="Choose"/>
</form:form>
<c:if test="${not empty myData.choice}">Choice = ${myData.choice}</c:if>
<c:if test="${empty myData.choice}">No choice</c:if>
</body>
</html>
Successive clicks on the "Choose" button appends the chosen values instead of just POST-ing the current one:
GET: Choice = null
POST: myData = MyData [choice=two]
GET: Choice = two
POST: myData = MyData [choice=two,one]
GET: Choice = two,one
POST: myData = MyData [choice=two,one,]
GET: Choice = two,one,
POST: myData = MyData [choice=two,one,,one]
GET: Choice = two,one,,one
Add this into your controller:
#ModelAttribute("myData")
public MyData getMyData() {
return new MyData();
}

<c:forEach> JSTL tag crashing the WebSphere 7 server

I'm using Spring MVC to pass a ArrayList object from my Controller to JSP and I want to iterate it over there using JSTL (forEach), but it is always crashing Java server after 10~20 seconds loading the page. It's not throwing any exception.
Trying to use "c:out" to print the String representing the array works fine. Same to not empty validation. It always crashes when program reaches the forEach.
SIMPLIFIED EXAMPLE BELOW
Controller method
#RequestMapping(value = "/main", method = {RequestMethod.POST}, params = "create")
public ModelAndView createBranch (Branch branch) throws FxtrmServiceException, JsonGenerationException, JsonMappingException, IOException{
ModelAndView branchMV = new ModelAndView("branch");
ArrayList<String> array1 = new ArrayList<String>();
array1.add("test1");
array1.add("test2");
branchMV.addObject("alertMap1", array1);
populateAutoCompletes(branchMV);
return branchMV;
}
JSP:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
(...)
<c:if test="${not empty alertMap1}">
<c:forEach items="${alertMap1}" var="entry1">
<c:out value="${entry1}"/><br>
</c:forEach>
</c:if>

Categories