Accessing SpringMVC model key value inside java code - java

#RequestMapping(value = "",method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
model.addAttribute("message", doctorDetails);
return "doctorchannelling/index";
}
I have added this controller in my SpringMVC project now I need to access the element doctorDetails in a java code which is inside a jsp
how can I call this doctorDetails inside <% %> Mark

Something like below
<% String message = (String)request.getAttribute("message"); %>
or
<%
String message = ${message};
%>

You can simply use the EL to print them as,
${message}
If it is a String set in the request. For Model objects use ,
${message.fieldName}
See Also
How to avoid Java code in JSP files?
printing servlet request attributes with expression language

Related

Add string array to request in Spring controller in order to forward to another service

I'm looking to cut out the JSP middleman here. I have a POST Spring endpoint that returns a string representing a view. This view is a JSP ("the middleman") that simply POSTs hidden HTML input elements on $(document).ready() to another system's URL. In order to remove this JSP, I will need to stuff the request parameters w/in the calling controller already mentioned (e.g., request.setAttribute("var1", "val1")).
First question: should I do this by returning a "forward:" + URL? A redirect does not seem to be an option because the outside-system's endpoint is expecting a POST (instead of a get in what would be the first post-redirect-get pattern of this flow).
Second question: There is a loop in the JSP that stuffs the same hidden input element multiple times:
<c:forEach var="elem" items="${requestScope.elements}">
<input type="hidden" name="thing" value="<c:out value="${elem}"/>">
</c:forEach>
How would I migrate this to the calling controller. Perhaps, something like this:
#RequestMapping(value = "/path_val", method = RequestMethod.POST)
public String handleRequest(HttpServletRequest request) {
// below is the code in question
#SuppressWarnings("unchecked")
List<String> elements = (List<String>) request.getAttribute("elements");
for (ListIterator<String> elemIter = elements.listIterator(); elemIter.hasNext();) {
request.setAttribute("item[" + elemIter.nextIndex() + "]", elemIter.next());
}
return "forward:" + outsideURL;
}

How to get Uuid from User

I am trying to get the UUID from a user.
So far i tried
Accessing the user from a liferay portlet?
Get the current user Liferay using a simple Java code
putting String userId = renderRequest.getRemoteUser() into the view.jsp worked to get the intern ID.
However i wanted the UUID instead.
If i use the code from the links above (into the java-class doView) i only get a null-user object.
Using getUserUuid() and getUuid() returns null.
Here is my class:
ThemeDisplay td =(ThemeDisplay)renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
User user = td.getUser();
String userId = user.getUuid();
renderRequest.setAttribute("myUser", userId);
and my view.jsp
<%
String userId = (String) renderRequest.getAttribute("myUser");
%>
<%= userId %>
Any help is appreciated.
On JSP, extract your parameter from implicit request object. Like:
<%
String userId = (String) request.getAttribute("myUser");
%>

#ModelAttribute is returning something wrong

I'm building an application that has these methods in the Controller for a form handling:
//This will prepare the model and populate the form
#RequestMapping(value="verbete",method = RequestMethod.GET, params="new")
public String addVerbete(#ModelAttribute("verbeteform") VerbeteForm verbeteForm,
Map<String, Object> model){
verbeteForm.getNomes().add(new NomesVerbete());
// add one significado
verbeteForm.getSignificados().add(new SignificadosVerbete());
// depois de implementar o Security
verbeteForm.getVerbete().setAutor(usuarioService.buscarUsuarioPorLogin("greati"));
// seta a data
verbeteForm.getVerbete().setDataLancamento(new Date());
// popula categorias
verbeteForm.setCategorias(verbeteService.listarCategorias());
return "editorVerbete";
}
#RequestMapping(value="verbete", params="new", method = RequestMethod.POST)
public String addVerbeteFromForm(#ModelAttribute("verbeteform") VerbeteForm verbeteForm,
Map<String, Object> model){
Verbete verbete = verbeteForm.getVerbete();
List<NomesVerbete> nomes = verbeteForm.getNomes();
List<SignificadosVerbete> significados = verbeteForm.getSignificados();
long idVerbeteSalvo = verbeteService.addVerbete(verbete);
Verbete verbeteSalvo = verbeteService.getVerbetePorId(idVerbeteSalvo);
for(NomesVerbete nome:nomes){
nome.setVerbete(verbeteSalvo);
verbeteService.addNomesVerbete(nome);
}
for(SignificadosVerbete significado:significados){
significado.setVerbete(verbeteSalvo);
significado.setCategoria(verbeteService.getCategoriaPorNome(significado.getCategoria().getNome()));
verbeteService.addSignificadosVerbete(significado);
}
return "editorVerbete";
}
So, I was expecting that the date and the author would be setted in the model, but, when I submit the form, it says that the attributes dataLancamento (it's a date) and autor are not in the model, throwing an error because they cannot be null in the database.
Maybe I didn't understand how #ModelAttribute works, or maybe I'm doing something wrong.
A solution would be set the dataLancamento and autor in the second method, but I don't know if it's right. So, could you show me a way?
(Some words are in Portuguese... Please, tell me if it's a problem.)
When the first method is execute and the form is rendered the first time, the autor should be in the model. So using ${verbeteform.autor} should print the autor field.
But when you submit the form, the model is fullfilled with the data in the form. So if the form doesnt have a autor field like:
<form:form modelAttribute="verbeteform" method="POST">
<form:input path="autor"/>
</form:form>
the value is not added to the model, so in the second controller you have a null value in the autor field because the model is regenerated.

Want to pass the java value into javascript function in jsp

I am trying to pass a string value to a JavaScript function by taking from request parameter in JSP, in my struts based project. here is the code:
<%
String timeVal = "Not found";
if(request.getAttribute("myDate")!=null){
timeVal= (String)request.getAttribute("myDate");
}
%>
and then pass it in function as parameter
<html:submit property = "save" styleClass = "button_c" onclick = "return SubmitPage('update', <%=timeVal %>)">Save</html:submit>
Where the JavaScript function is
function SubmitPage(action, aa)
{
alert("Date is ...." + aa);
}
But when i try to run this it gives me an error
HTTP Status 400 - Request[/AMResourceLibraryListAction] does not contain handler parameter named ref
With message on web page.
Request[/AMResourceLibraryListAction] does not contain handler parameter named ref
Thanks in advance.
EDIT Here is stack trace
[ERROR] DispatchAction - -Request[/AMResourceLibraryListAction] does not contain handler parameter named ref
it's work for me :
<html:submit property = "save" styleClass = "button_c" onclick = "return SubmitPage('<%=timeVal %>')">Save</html:submit>
('<%=timeVal %>') // between single Quotation
Rather using that i will advise you to use value like this in your JavaScript function
var tt = <%=(String)request.getAttribute("myDate")%>
alert(tt+ "Done this....");
Hope this will help you.
Use '<%=timeVal %>' instead of <%=timeVal %> in Javascript method:
<html:submit property = "save" styleClass = "button_c" onclick = "return SubmitPage('update', '<%=timeVal %>')">Save</html:submit>

How do I send data from Struts action to javascript?

I'm trying to create a webb application using Struts 2 and javascript and I'm having some trouble passing data from my action into my javascript.
This is the list I'm trying to send/access:
List<MarkerClass> markers;
MarkerClass is defined acoprding to belove:
final class MarkerClass
{
public Integer objectId;
public String street;
public String streetNumber;
public String zip;
public String city;
public Integer statusId;
public Float lattitude;
public Float longitude;
}
The action also includes a getter for markers:
public List<MarkerClass> getMarkers()
{
return markers;
}
In my jsp-file I have tried doing this:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function initialize()
{
var titel = "";
for(var i, "${markers}")
{
titel = titel+ "${markers[i].street}";
}
}
The browser substitutes "${markers}" with "[se.fubar.test.MarkerClass#37a4, se.fubar.test.MarkerClass#9ad97c]"
I'm guessing there is a better and smarter way to do this but since I'm a bit new to Struts and is trying to code while under the influence of a migrane the answer elludes me.
You cannot just use a struts variable in a javascript function and expect it to work. Remember that the ${...} stuff gets processed before the HTML for the page is sent to the browser. By the time the javascript is rendered at the browser, you are only left with the textual representations. What you will need to do is something like (check the syntax, I haven't used this stuff i a while):
function initialize() {
var title = "";
<c:foreach var="marker" list="${markers}">
title = title + "${marker.street}";
</c:foreach>
}
Something along those lines anyway... Basically the Javascript seen by your browser will look like
function initialize() {
var title = "";
title = title + "Street1";
title = title + "Street2";
title = title + "Street3";
title = title + "Street4";
}
I hope that makes sense and is related to what you were asking.
By the way, there are usually better ways of accomplishing this functionality that building dynamic js etc. Probably there are built in Struts 2 components that you can use?
you would have to set that variable in request or in session and then access it using a <c:out jsp tag like so
var myVar= '<c:out value="${requestScope.myVar}"/>';
then use the var inside your js.
In case you set an object in request or session you have to use the get method to access the value of an attribute then use it like so:
var myVar= '<c:out value="${requestScope.myObj.attribute}"/>';
(assuming you getter method is getAttribute)
it is not possible to access data in session or request directly from js
hope this helps
You could convert the object to json on the server (see http://www.json.org/java/index.html ) and then call eval() on the string to get a javascript representation of your object.
you can try accessing it something like this.
but you have to use a loop to fetch each object from the list place it on the value stack and than fetch each object of it.else you can ask ognl to do it for you.something like
<script type="text/javascript">
function initialize()
{
var titel = "";
for(var i, "${markers}")
{
titel = titel+ <s:property value="%{markers.get(i).street}">;
}
}
just try it since OGNL has capacity to access the object on the value stack

Categories

Resources