how to differenciate between onchange submit and button submit in spring controller - spring

I have the jsp code as :
<s:url value="add" var="addUrl"/>
<form:form name="add" action="${addUrl}" modelAttribute="content" method="post">
<input type="hidden" name="add" value="" />
<form:select path="id" class="dClass" onchange="submit()">
<form:options items="${list}" /></form:select>
<input type="submit" class="btn" value="Refresh Content" />
</form:form>
And I have one controller method for both this call, is there any way to differentiate that from where the form is submitted? Either from the drop down or from the submit button?
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String getContentById(Model model, String id,Content content,HttpServletRequest request) {
if(call by onChange)
else if(call by submit button)
}

Kindly note that, onchange="submit()" will not submit your page. It will look for the function with name submit. Inside that function you can use code like this $('form#form_id').submit(); to submit. Check submit-a-form-using-jquery for more details.

#Vinoth Krishnan Thanks for your answer , its working now :) added a filed in my form as "dropDownSubmit"
function submitForm(formId){
var input = $("<input>").attr("type", "hidden").attr("name", "dropDownSubmit").val("true");
$("#" + formId).append($(input));
$("#" + formId).submit();
}
Then in controller:
if("true".equalsIgnoreCase(form.getDropDownSubmit()){
..
}
else{
.. button submit
}

Related

Thymeleaf - Button click to call http delete method

I would like to call the url via http delete method. I tried th:onclick and th:action but not working.
html code:
<button id="delete" name="delete" th:onclick="#{'/foos/{id}'(id=${foo.id})}" th:method="delete">Delete</button>
controller code:
#RequestMapping(value="/foos/{id}", method = RequestMethod.DELETE)
#ResponseBody
public String delete(#PathVariable String id) {
studentService.delete(id);
return "Successfully deleted";
}
I think you will need a form for your transaction. And also this hidden input field.
<form action="#" th:action="#{'/delete/{id}'(id=${foo.id})}" th:method="delete" >
<input type="hidden" name="_method" value="delete" />
<button type="submit" id="submitButton"> </button>
</form>
The th:method="delete" creates the hidden input field automatically for you. If you add it manually as well you will have it twice. Check the source code.
I still got the POST Error message after the recommendations here. I found out Spring ignores those hidden fields by default. The solution is to activate it in your application.properties file:
spring.mvc.hiddenmethod.filter.enabled=true
My working code in my application looks like this:
Form:
<form action="#" th:action="#{'/books/delete/{id}'(id=${book.id})}" th:method="delete" >
<button type="submit" class="btn">
Delete
</button>
</form>
Controller:
#RequestMapping(value="/books/delete/{id}", method = RequestMethod.DELETE)
public String deleteBook(#PathVariable Long id) {
bookService.deleteBook(id);
return "books";
}

How to pass list containing hash map from jsp to controller on page submit in spring mvc

The list size in controller is getting 0.
The JS file is simply submitting the form, jsp file is iterating the list of hashMap which is getting populated on page load, and third one is the controller receiving the list after the submit button has been clicked in jsp page.
JS file:
function getFormDetails(){
document.forms[0].action=requestPath+"/admin/updateInterfaceParams.do";
document.forms[0].submit();
}
JSP file:
<form:form method="post" cssStyle="float:left;">
<c:forEach var="list" items="${manageInterfaceList }" varStatus="stat">
<c:forEach var="entry" items="${list}">
<c:if test="${entry.key eq 'A'}">
<input type="hidden" name="interfaceList[${stat.index}].key"
value="${entry.key}" />
<span>Key:</span>
<input type="text" id="keyAjax" name="interfaceList[${stat.index}].value"
value="${entry.value}"/>
</c:if>
<br />
<c:if test="${entry.key eq 'B'}">
<input type="hidden" name="interfaceList[${stat.index}].key"
value="${entry.key}" />
<span>Password:</span>
<input type="text" id="password"
name="interfaceList[${stat.index}].value" value="${entry.value }"/>
<br />
</c:if>
</c:forEach>
</c:forEach>
<span><input type="button"
name="Submit" value="Submit" onclick="getFormDetails();"/></span>
</form:form>
Controller:
#RequestMapping(value = "/updateInterfaceParams.do")
public ModelAndView updateInterfaceParams(HttpServletRequest request,
#ModelAttribute ArrayList<HashMap<String,String>> manageInterfaceList) {
ModelMap modelMap = new ModelMap();
try {
System.out.println(manageInterfaceList.size());
} catch (Exception e) {
modelMap.addAttribute("errorMessage",e.getMessage());
}
return new ModelAndView("manageinterface", modelMap);
}
Any suggestions regarding why the list size is coming as 0 and how to get list elements in controller.
Becuase the form is not associated with a form backing object, you need to specify commandName attribute of form element - which would be your pojo containing the list.

Passing parameters from JSP to controller - Spring MVC

I have a little problem when I want to pass parameter to my controller.
I have one method in controller:
#RequestMapping("/redirect")
public String print(String type, HttpServletRequest servletRequest)
{
String path = "redirect:" + servletRequest.getParameter("type");
return path;
}
And I have some buttons in my jsp file:
<form method="post" action="/WWP/redirect">
<button onclick=" <input type="text" name="type" value="/developer"/>">Developer</button>
<button onclick=<input type="text" name="type" value="/graphic"/>>Graphic</button>
<button onclick=" <input type="text" name="type" value="/cleaner"/>">Cleaner</button>
</form>
In this way I have 3 buttons and when for example I press Developer button variable "type" is "/developer" and I'm sending it to controller. But now my buttons look like this:
http://imageshack.us/photo/my-images/854/buttonspx.png/
It works correct, but I can't get rid this HTML tag and it's really nervous. How to do this? Or how send value to controller in different way. Thanks in advance.
Instead of normal buttons you can have submit buttons and handle them in controller as below
<input type="submit" value="Developer" name="developer"></input>
<input type="submit" value="Graphic" name="graphic"></input>
<input type="submit" value="Cleaner" name="cleaner"></input>
And you can have different methods in the controller class for each of the buttons clicked using the params attribute like this
#RequestMapping(value = "/redirect", method = {RequestMethod.POST}, params = "developer")
public ModelAndView developerMethod(){
}
#RequestMapping(value = "/redirect", method = {RequestMethod.POST}, params = "graphic")
public ModelAndView graphicMethod(){
}
#RequestMapping(value = "/redirect", method = {RequestMethod.POST}, params = "cleaner")
public ModelAndView cleanerMethod(){
}

How to make dynamic url-pattern using Spring MVC #PathVariable?

I'm working that make search function.
I have a search form on jsp view.
<form action="<c:url value="/community/board/list/search" />">
<p class="serch_Area">
<select name="searchCategory">
<option value="subject" selected="selected">subject</option>
<option value="contents">contents</option>
</select>
<input type="text" name="searchWord" class="inputCom" style="width:150px; height:17px;" value="" maxlength="15" />
<input type="image" src="<c:url value="/resources/images/common/btn_search.gif" />" alt="search" />
</p>
</form>
I want to make request url-pattern like "/community/board/list/search/subject/abc". But this form action url like "/community/board/list/search?subject=abc"
How can I make request url pattern like RESTful?
This is my controller.
#RequestMapping("/list/search/{searchCategory}/{searchWord}/{pageNum}")
public String getSearchList(#PathVariable(value = "searchCategory") String searchCategory,
#PathVariable(value = "searchWord") String searchWord,
#PathVariable(value = "pageNum") int pageNum, ModelMap model) {
Please help me.
You can do this with JavaScript. You should add an onSubmit listener on your form and change your form action within that method.

Portlet:actionurl is not going to #Actionmapping in controller

I am using Liferay portal-6 with Spring-3.
In my portlet, first it goes to the #Rendermapping without params and displays the default jsp,
when I click on a button I am passing the actionurl, but its not going to the corresponding #Actionmapping.
My searchForm.jsp looks like this:
<portlet:actionURL var="showSearchResultsUrl">
<portlet:param name="myaction" value="searchResults" />
</portlet:actionURL>
<form:form id="searchForm" name="searchForm" commandName="patientStoryForm" method="POST" action="${showSearchResultsUrl}" enctype="multipart/form-data" >
<input type="button" name="search_btn" value="Search"/></td>
</form:form>
My controller is like this:
#Controller(value = "searchPatientStoryController")
#RequestMapping(value = "VIEW")
#SessionAttributes(types = PatientStoryForm.class)
public class SearchPatientStoryController {
#RenderMapping
public String showSearchForm(RenderResponse response, Model model) {
return "searchForm";
}
#RenderMapping(params = "myaction=searchResultsForm")
public String showSearchResultsForm(RenderResponse response, Model model) {
return "searchResultsForm";
}
#ActionMapping(params = "myaction=searchResults")
public void searchResults(
#ModelAttribute(value = "patientStoryForm") PatientStoryForm patientStoryForm,
BindingResult bindingResult, ActionResponse response, ActionRequest request,
SessionStatus sessionStatus, Model model) {
response.setRenderParameter("myaction", "searchResultsForm");
}
}
When I click on button in searchForm.jsp it is supposed to go to #Actionmapping but it is not going.
Please help me.
Thanks in advance.
You would need to submit the form in order to invoke the associated action method.
However, in the jsp code, I see the below code which indicates that it is just a button.
<input type="button" name="search_btn" value="Search"/>
In order to submit the form, you can do either of the following ways:
Use a submit button instead of a normal form button like this:
<input type="submit" name="search_btn" value="Search"/>
Invoke a javascript function on click event of the button and submit the form:
<script type="text/javascript">
function submitForm(form){
var actionUrl = '<portlet:actionURL var="showSearchResultsUrl"><portlet:param name="myaction" value="searchResults"/></portlet:actionURL>';
form.action = actionUrl;
form.submit();
}
</script>
and
<input type="button" name="search_btn" value="Search" onclick="javascript:submitForm(this.form)"/>
Can you try replacing your actionURL like the following
<portlet:actionURL name="searchResults" var="showSearchResultsUrl">
<portlet:param name="myaction" value="searchResults" />
</portlet:actionURL>
You need to set the action of your form, something like this:
<form:form action="<%=showSearchResultsUrl%>" id="searchForm" name="searchForm" commandName="patientStoryForm" method="POST" action="${showSearchResultsUrl}" enctype="multipart/form-data" >
<input type="button" name="search_btn" value="Search"/></td>
This way your action name will be "myaction" with the value "searchResults" as your mapping on the controller side.

Resources