Fetch data from database using ajax in jsp and spring - spring

i have dropdown a label in that already values are coming from database using spring jsp & mysql , now i need to apply ajax search in my dropdown or text box .How can i apply in my jsp spring forms ??
example:
controller#
#RequestMapping(value = "/addBank1")
public ModelAndView addBank(ModelMap model, #RequestParam String entityType) {
ArrayList<HashMap<String, String>> allbankAccounts = accService
.getAllbankAccounts(entityType);
model.addAttribute("allbankAccounts", allbankAccounts);
}
Jsp#
<p class="text-muted font-13">
<strong>Bank name </strong>
<span class="m-l-15">
<form:select class="form-
control" path="empQufnId" title="Select" id="report">
<form:option value="" label="Select
bank name" />
<c:forEach items="${allbankAccounts}"
var="sal" varStatus="status"
<form:option path="empQufnId"
value="${sal.bankId}" >${sal.bankName}</form:option>
</c:forEach>
</form:select>

Related

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

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.

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