Spring & JSP: Get value from certain input using spring controller - spring

Can somebody help me to get value from certain input using spring controller.
I have 2 input data, and I just need a value from one of these inputs:
<input type="text" name="data01" />
<input type="text" name="data02" />
I just want to retrieve a value from "data01".
I just have used
(HttpServletRequest) request.getParameter("data01")
Or
#RequestParam(value="data01") Integer data01
but the value is null.
Can somebody help me
EDIT:
jsp:
<table>
<tr>
<input type="text" name="data01" />
<input type="text" name="data02" />
</tr>
</table>
controller:
#RequestMapping(value = "/user", method=RequestMethod.GET)
public String showAllData(ModelMap model, HttpServletRequest request) {
String retrievedData = request.getParameter("data01");
System.out.println("data= " + retrievedData);
model.addAttribute("data", new data());
return "data";
}
The retrievedData value is null.

You should be able to get the parameter using this method
<form action="/user" method="get">
<table>
<tr>
<input type="text" name="data01" />
<input type="text" name="data02" />
<input type="submit" value="submit"/>
</tr>
</table>
</form>
and in the controller
#RequestMapping(value = "/user", method=RequestMethod.GET)
public String showAllData(String data01, ModelMap model) {
// your logic here
}
and from the code you have posted. You are casting the parameter to HttpServletRequest
request.getParameter("data01") //returns String as default.
Integer.parseInt(request.getParameter("data01");
From your comment at #user1516735 answer, you cannot use it outside of the form tag. Unless you include it in the parameter from ajax or append the value of "name01" in the url as /user?name01=value

You will get the value of data01 by using the below code:
request.getParameter("data01");
Here request is of type HttpServletRequest. Make sure your input control is inside form tag.

Related

Thymeleaf th:field doesn't bind the value for input text

I want to send an object to the view for presentation and send it back to controller using springboot and Thymeleaf, however, I encounter a weird problem with Thymeleaf's th:value.
This is my controller:
#GetMapping("/food/buy/{fid}")
public String buyFood(HttpServletRequest request, #PathVariable("fid") Long fid, Model model) {
Food food = consumerService.getFood(fid);
System.out.println("foodid = " + food.getId());
model.addAttribute("food", food);
model.addAttribute("order", new OrderVO());
return "user/direct/f_order";
}
and my view:
<form th:action="#{/user/buy/direct/food}" method="post" th:object="${order}">
<table border="1px">
<tr th:hidden="true">
<td><input type="text" th:value="${food.id}" th:field="*{fid}" th:readonly="true"></td>
</tr>
</table>
</form>
and the VO class:
public class OrderVO {
private Long fid, address;
private Integer amount;
#DateTimeFormat(pattern = "HH:mm")
private Date deliverTime;
}
the problem is, the input field's value is null, but I'm sure that the food's id is not null (I print it in the controller)
I remove the th:field block, and the food.id can be properly presented. If I add the th:field block back, the problem reoccur.
So there may be something wrong with th:field, but I can't figure out. Can somebody point out my mistake?
===========================UPDATE============================
Some friends kindly points out that th:field may overwrite th:value, but I also use them in other views and it works fine:
<tr>
<td>UserName</td>
<td><input type="text" th:value="*{userName}" th:field="*{userName}"></td>
</tr>
The problem is getting incresing weird I think :(
Replace *{fid} with fid
My team had this same issue and it worked
In tabualr form try using th:name instead of th:field to overcome th binding issue
th:name="|order.fid|"
and stick to java naming convention.
Supposing you have to collect a comment to a page. You must transmit to the controller, besides the comment, the name of the page. Ofcourse, the user don't have to re-enter the name of this page. This information must be passed to controller, but th:field only map the values entered by the user, not the values generated by default.
But you can transmit the name of this page to controller as parameter in URL.
In html, you have something like that:
<form th:action="#{/saveComment(lastPage=${lastPage})}" th:object="${comments}" method="post" enctype="multipart/form-data">
<div class="row">
.................................................................................
<h2>Enter your comment</h2>
<textarea th:field="${comments.comment}" rows="10" cols="100" name="comment" id="comment"></textarea>
<label for="comment">Your comment here</label><br />
<input type="submit" name ="submit" value="Submit" />
</div>
</form>
In controller, you put stuff like this:
#PostMapping("/saveComment")
public String saveComment(Comments comments, String lastPage) {
comments.setPage_commented(lastPage);
commentsRepository.save(comments);
return "redirect:/";
}
It works fine to me.

Controller Not receiving value from span in HTML using Spring boot and Thymeleaf

I have the following content in my HTML which is using Thymeleaf
<form action="#" th:action="#{/shutDown}" th:object="${ddata}" method="post">
<span>Domain</span>
<span th:text="${domain}" th:field="*{domain}">domain</span>
<input type="Submit" value="close" />
</form>
And I have the following in my Controller which is using Sprint Boot
#RequestMapping(value = "/shutDown", method = RequestMethod.POST)
public ModelAndView shutDownPage(ModelAndView modelAndView, Authentication authentication,
#ModelAttribute("ddata") DInputBean dInputBean) {
String domain = dInputBean.getdomain();
return modelAndView;
}
I'm hoping I'd get value of domain from the HTML in the Controller but it's always null. DInputBean has getters and setters for "domain" field.
The th:field attribute can be used on <input>, <select>, or, <textarea>.
A solution you could possibly replacing you second <span> with a hidden input element.
<form action="#" th:action="#{/shutDown}" th:object="${ddata}" method="post">
<span>Domain</span>
<input type="hidden" th:field="*{domain}" th:value="${domain}" />
<input type="Submit" value="close" />
</form>
If you wanted to keep the second div, just place the <input type="hidden"> inside the second <span> and remove the th:field attribute from the second <span>.
Edit:
If you wanted to add the value of domain in a span.
<form action="#" th:action="#{/shutDown}" th:object="${ddata}" method="post">
<span>Domain</span>
<span th:text="${domain}">domain<span>
<input type="hidden" th:field="*{domain}" th:value="${domain}" />
<input type="Submit" value="close" />
</form>
http://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html#inputs
An option is to use a read-only input field:
<input type="text" th:field="*{domain}" th:value="${domain}" readonly="readonly"/>
This both displays the value and sends it on submit.
The key is to add the value of the domain variable to the form:
#GetMapping("/shutDownPage")
public String shutDownPage(Model model) {
model.addAttribute("ddata" new Ddata()); //or however you create your bean
String username = ... //however you get your username
String domain = myRepositoryService.findDomainByUsername(username);
model.addAttribute("domain", domain);
return "shutDownPage";
}
Include an HTML page in the action so that when you open the HTML page in a browser without a server/container, the button will still appear to work:
<form action="confirmationPage.html" th:action="#{/shutDown}" th:object="${ddata}" method="post">
<!-- You can benefit from using a conditional expression -->
<span th:text="${domain != null ? domain : 'No domain supplied'}">[domain]</span>
<input type="hidden" th:field="*{domain}" th:value="${domain}"/>
<input type="Submit" value="close"/>
</form>
And your post method:
#PostMapping("/shutDown") //use shorthand
public String shutDownPagePost(#ModelAttribute("ddata") DInputBean dInputBean {
String domain = dInputBean.getDomain();
//do whatever with it
return "confirmationPage";
}

dynamic spring form:select element not bound to model

I am using Spring.AjaxEventDecoration to dynamically populate a drop down on my JSP but it is throwing an error as it cannot bind to the original model. I have been researching this for a while and I do not think this is possible but it seeems like it should be hence this post.. Help me out somebody!
OK My controller dumbed down looks like this,
#Controller
#RequestMapping(value = "/cis/crimeProperty/")
public class CrimePropertyController
{
#RequestMapping(value = "/manageView", method = RequestMethod.GET)
public ModelAndView managePropertyDetails(Long propertyId) throws DAOException
{
Map<String, Object> model = new HashMap<String, Object>();
CrimePropertyVO crimePropertyVO = new CrimePropertyVO();
model.put("crimePropertyVO", crimePropertyVO);
return new ModelAndView("cis.crime.property.edit", model);
}
#RequestMapping(value = "/changeItemList", method = RequestMethod.POST)
public ModelAndView retrieveItemList(String propertyClass)
{
Map<String, Object> model = new HashMap<String, Object>();
..call service to get list of items from class..
model.put("propertyItemList", propertyItemList);
return new ModelAndView("/cis/property/crime_property_item", model);
}
}
I am using tiles so my tile definition looks like this,
<definition name="cis.crime.property.edit" template="/WEB-INF/jsp/cis/property/manage_crime_property.jsp">
<put-attribute name="itemListFrag" value="/WEB-INF/jsp/cis/property/crime_property_item.jsp"/>
My (manage_crime_property.jsp) JSP looks like so,
<form id= "changeList" action="${pageContext.request.contextPath}/smvc/cis/crimeProperty/changeItemList" method="post">
<select id="propertyClassChange" path="propertyClass">
<option value="" label="-Please Select-"/>
<option value="CLO" label="CLOTHING"/>
<option value="TOL" label="TOOLS"/>
</select>
</form
<form:form modelAttribute="crimePropertyVO" action="${pageContext.request.contextPath}/smvc/cis/crimeProperty/saveProperty" method="post">
<table class="genericOutlinedTable" style="width: 100%;">
<tr>
<td><b>Item</b></td>
<td>
<tiles:insertAttribute name="itemListFrag" flush="true" ignore="false"/>
</td>
</tr>
<tr>
<td><b>Make</b></td>
<td><form:input path="propertyMake" size="20" maxlength="20"/></td>
<td><b>Model</b></td>
<td><form:input path="propertyModel" size="15" maxlength="15"/></td>
</tr>
</form:form>
<script type="text/javascript">
Spring.addDecoration(new Spring.AjaxEventDecoration({
elementId:'propertyClassChange',
event:'onchange',
formId:'changeList',
params: {fragments: 'itemListFrag'}
}));
My (crime_property_item.jsp) JSP fragment looks like this,
<span id="itemListFrag">
<form:select path="propertyItem">
<form:option value="" label="-Please Select-">
<c:forEach var="itemList" items="${propertyItemList}">
<form:option value="${itemList.propertyCode}" label="${itemList.propertyCode}" />
</c:forEach>
</form:select>
</span>
Its all configured correctly and when I change the first drop down it calls my controller changeItemList method which returns my JSP frag and list of items to make up the options but I get a server error ...
Neither BindingResult nor plain target object for bean name propertyItemavailable as request attribute
I've tried having just the options tags in my frag but that doesn't work and I've tried using the spring:bind tag and normal select but can't get that to work either.
Many Thanks in advance for any help with this.

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.

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.

Resources