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.
Related
While working on REST API, I am using POST method to fetch data from Mongo DB using #FormParam annotation. When I use GET type, then it returns the response in JSON and while changing the method from GET to POST, I am getting blank response.
The code:
//GetResponse.java
//
#Path("/Location")
public class GetProjectLocationResponse {
#POST
#Path("/State")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Object[] addBuild2(
#FormParam("Country") String Country,
#FormParam("State") String State) throws UnknownHostException, JSONException
{
System.out.println("ïnside Location");
Location loc = new Location();
List<DBObject> basicDBList=(List<DBObject>) loc.getState2(Country, State); //calling state method
return basicDBList.toArray();
}
//Location.java
//This defines the list of available zipcpdes on the basis on parameter 'Country' and 'States'.
public List<DBObject> getState2(String Country, String State) throws UnknownHostException {
DB db=ConnectToDB.getConnection();
DBCollection collection = db.getCollection("location");
BasicDBObject obj = new BasicDBObject();
obj.put("Country",Country);
obj.put("State",State);
BasicDBObject fields = new BasicDBObject();
fields.put("_id", 0);
DBCursor cursor = collection.find(obj, fields);
List<DBObject> obj1 =cursor.toArray();
System.out.println(""+obj1);
return obj1;
}
}
//index.html
//This file includes parameters 'country' and 'states' to return the JSON response.
<form action="rest/Location/State" method="post">
Enter Country:<input type="text" name="Country"/><br/><br/>
Enter State:<input type="text" name="State"/><br/><br/>
<input type="submit" value="submit"/>
I have checked the code but did not find any clue what is wrong in this that causing this blank response for POST type, while its working fine for GET type. I though it should have worked for POST type as the code specification is correct for both type. Please specify any issue there. Thanks in advance
You are using POST for a different and wrong purpose here.
Use GET for retrieving data and POST for creation of the required entity. A typical response from a POST call would be 201 - Created and the UI should not expect any response from the POST call.
HTTP POST was not specified to return data and do not expect it to return.
Similar question :
Can I use POST method to get data and GET method to post data?
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;
}
I'm trying to create add calculation in view, it was successfull, but how to create add operation's in controller?
here my code
public String jumlah(#RequestParam(value = "a") int angkaPertama, #RequestParam(value = "b") int angkaKedua, Model model) {
model.addAttribute("a", angkaPertama);
model.addAttribute("b", angkaKedua);
return "jumlah";
}
And i have one more question
here is my code:
<p th:text="'Welcome ' + ${name} + '!'">Good Morning</p>
Why "Good Morning" does'nt show up in my view?
Add #ResponseBody to the return type of method.And i hope you have proper request mapping for the url of your page.
I am trying to use SpringMVC to handle a form but now I am stuck and I'm here to ask for your help.
When the user submit the form, my controller returns the jsp result page and the user can check what he filled in. In that result page I have 2 buttons, one to send definitively the form and one to modify it.
Here my problem : when I click on modify all the fields of the form are again empty and I would like to keep the value filled by the user.
My controller :
#Controller
#RequestMapping( "/adhesion" )
public class FormController {
//Send the form
#RequestMapping( method = RequestMethod.GET )
public String getFormulaire( #RequestParam( value = "user", required = false ) T_demande_adhesion User, Map<String, Object> model ) {
System.out.println( "user" + User ); //Null everytime
model.put( "user", User );
System.out.println( "Envoi formulaire !" );
return "formulaireAdhesion";
}
//Handle the form
#RequestMapping( method = RequestMethod.POST )
public String gestionAdhesion( #ModelAttribute( "formAdhesion" ) #Valid T_demande_adhesion user, BindingResult erreurForm, Map<String, Object> model )
throws ServletException, IOException {
final String CHEMIN_DOC_APP = "C:/DocumentsApp/";
// Form JSP page
final String FORMULAIRE_ADHESION = "formulaireAdhesion";
// Result page
final String AFFICHER_RESULT = "afficherResult";
// Objet de validation du formulaire
ValidationDmdAdhesion demandeAdhesion = new ValidationDmdAdhesion();
//Return AFFICHER_RESULT or FORMULAIRE_ADHESION
String resultat = demandeAdhesion.validationUser( user, erreurForm, model, FORMULAIRE_ADHESION, AFFICHER_RESULT, CHEMIN_DOC_APP );
//putting the object to the request
model.put( "user", user );
return resultat;
}
}
In JSP side I added the parameter 'User' in the request :
'
<input type="button" value="Modifier" onclick="document.location.href='<c:url value="adhesion?user=${user}"/>';" class="boutonAdhesion" />
'
But this send me a string and the url is :
/adhesion?user=com.user.entities.T_demande_adhesion#1dfe8158
When the user clicks on modifiy button (which is in the result page), I would like to get this object #ModelAttribute( "formAdhesion" ) #Valid T_demande_adhesion user on the GET request to fill in the form, in purpose to avoid the user to put again the same informations.
Any help ?
An extract from the form :
<label for="nom">Nom <span class="requis">*</span></label><input type="text" id="nom" name="identite.nom" value="<c:out value ="${user.identite.nom}"/>" size="35" maxlength="30" />
<spring-ext:errors path="identite.nom" class="erreur" firstErrorOnly="true"/>
It's here : value="<c:out value ="${user.identite.nom}"/> that I want to get the value of nom.
Sorry for the English.
Frenchy.
When I click on modify all the fields of the form are again empty and
I would like to keep the value filled by the user
Because the form data is already available on the page at client side, there is no meaning of submitting the form again to the server & show the same data, which is an unnecessary round trip from the client to the server i.e.,
To keep the data on the form, do NOT to submit the form to the server/controller itself.
How can I check the validation of the information filled in without
submit the form? How can I display them in my result page?
There is no need to validate the data that the user is anyhow going to modify. So, the validation of the form will be done only after the user completes the modifications and clicks on Submit. Once the validations are successful/failed, your can show the result on the results page.
In this case, I didn't find another way than using #SessionAttributes. In this point off my application I didn't to use a session but it seems that there isn't another way.
#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