submit onchange using request mapping in spring mvc - java

Generating a Jasper report depending on the user selected values from drop down (have two drop downs).
JSP:
<form:form name="f" action="${flowExecutionUrl}" modelAttribute="simpleReportSelector">
<table class="search">
<tr><th colspan="3"><fmt:message key="report.someextract"/></th></tr>
<tr>
<td><b><fmt:message key="somereport.sortdate"/></b>
<select id="firstfield" name="localDate" onchange="this.form.reloadPage.value='true';submit()">
<c:forEach var="dl" items="${dateList}">
<c:if test="${dl.selected==false}">
<option value="${dl.itemValue}">${dl.itemLabel}</option>
</c:if>
<c:if test="${dl.selected==true}">
<option selected="selected" value="${dl.itemValue}">${dl.itemLabel}</option>
</c:if>
</c:forEach>
</select>
</td>
<td><input type="hidden" id="reloadPage" name="reloadPage" value=""/></td>
<td><b><fmt:message key="somereport.equipNumber"/></b>
<select id="uld" name="uldNumber">
<c:forEach var="u" items="${uldList}">
<option value="${u.itemValue}">${u.itemLabel}</option>
</c:forEach>
</select>
</td>
</tr>
<tr><td class="right" colspan="3"><button type="submit" name="_eventId_exportReport">Submit</button></td></tr>
<tr class="hide">
<td><input id="submithidden" type="submit" value="submithidden" name="_eventId_submitButton" /></td>
</tr>
</table>
</form:form>
When user selects this particular menu from header, page populates with datelist and uldlist. datelist will be defaulted to today date and uldlist with 'select'. When user selects a previous date or future date, uldlist supposed to populate with different list.
controller:
#Controller
#RequestMapping("/uldReport.do")
public class ULDReport {
#Transactional(readOnly=true)
#RequestMapping(value="/uldReport.do",method = RequestMethod.GET)
public String setupForm(Model model, HttpServletRequest request, HttpServletResponse response) {
//code to populate datelist and uld list(populates using present day)
}
#Transactional(readOnly=true)
#RequestMapping(params={"reloadPage='true'"}, value="/uldReport.do", method = RequestMethod.GET)
public String setUpUld(Model model, HttpServletRequest request, HttpServletResponse response) {
//this should populate the uld list by using the date seelcted by user
}
#Transactional(readOnly=true)
#RequestMapping(params={"reloadPage='false'"}, method = RequestMethod.POST)
public ModelAndView processSubmit(#ModelAttribute SimpleReportSelector simpleReportSelector, Model model, HttpServletRequest request, HttpServletResponse response) throws IOException{
//some code
}
}
First method works good, but when I change the date, app directs to an error page. I think may be something with #RequestMapping, if I remove params from second and third method in controller, app submits with processandsubmit. What am I doing wrong?

This could be happening because of the way the URL is constructed. The fact that the page is loading a blank page means that it can't find anything that matches the criteria you have set up, and so it's silently failing.
For it to work as you expect, chances are you need to have the url formatted something like this:
/uldReport.do?reloadPage=true
or
/uldReport.do/reloadPage/true
depending on your setup.
But the point is that it needs to be in the URL and not a submitted field in your form, which it seems like it is right now.

Related

Thymeleaf table not displaying on html page in Spring Boot app

I have a table which is populated via a custom select statement to a database.
This has previously worked but now it is not displaying any values, not even the defaults.
I have created the table headings and here is the content declaration in the HTML:
<tr th:each="user : ${listUser}">
<td>
<a th:href="#{/editUser(user_id=${user.user_id})}">
<span th:text="${user.user_id}">Default ID</span>
</a>
</td>
<td th:text="${user.username}">Default username</td>
<td th:text="${user.email_address}">Default email</td>
<td th:text="${user.role_code}">Default role code</td>
<td th:text="${user.enabled_ind}">Default enabled</td>
<td>Default enabled</td>
</tr>
Here are the declarations in the Web Controller (The problems started when I added #GetMapping and #PostMapping, it seems to be ignoring #RequestMapping.
#GetMapping("/admin")
public String greetingForm(Model model) {
model.addAttribute("searchuser", new Searchuser());
return "admin";
}
#PostMapping("/userresults")
public String greetingSubmit(#ModelAttribute Searchuser searchuser) {
return "userresults";
}
#RequestMapping(value = "/userresults")
public ModelAndView listUser(ModelAndView model) throws IOException {
List<User> listUser = userDAO.loadAllUser();
model.addObject("listUser", listUser);
model.setViewName("userresults");
return model;
}
I know the SQL method is working as I have previously called it from another page.
Try this table structure for displaying your data.
<table border="1" style="width: 300px">
<tr>
<th>User name</th>
<th>Default Heading</th>
</tr>
<tr th:each="user : ${listUser}">
<td th:text="${user.username}">Default username</td>
<td>Default enabled</td>
</tr>
</table>
PS: I tested your code with the above table structure and both #GetMapping and #RequestMapping is working fine. Also make sure the listUser has atleast one User otherwise even the default won't be displayed.

How to delete an elements from a list in spring mvc

In workers.jsp I have:
....
<form action="/workers" id="personForm" method="post" >
<c:forEach items="${page.content}" var="row" varStatus="status">
<tr>
<td><input type="checkbox"/></td>
<td>${row.name}</td>
...
<td>
<input type='image' src='/pages/img/del.png' />
<input type='hidden' name="removeid" value='${row.id}'/>
</td>
</tr>
</c:forEach>
</form>
When I click on input, ${row.id} goes to:
#RequestMapping(value = "/workers", method = RequestMethod.POST)
public ModelAndView getAllByPage(#ModelAttribute("removeid") Long removeid, Model uiModel, Pageable pageable) {
if(removeid!=null) {
userService.remove(removeid);
}
...
}
But removeid in this case is always the first, that was added to the jsp page.
Besides that, how to get the array of ids, using jsp to remove many items?
Help me, please.
You can write 1 separate REST end point for deleting multiple items.
Example:
public List<Long> deleteMultiple(List<Long> toBeDeleted){
deleteService(toBeDeleted);
return toBeDeleted;
}
You can call this End point via AJAX with multiple ides & refresh your page.

passing parameter using JSP URL to controller in spring mvc, returns 404

First I am getting a list of objects on JSP page, each has an hyperlink(anchor), then on click of anchor I have to send index of the list(surveyId which is also originally coming in surveyList) to controller but the controller is not getting called. It returns 404.
<body>
Create a new survey
<table border="1" cellpadding="5" cellspacing="5">
<tr>
<td><b>Existing Surveys</b></td>
</tr>
<c:forEach var="survey" items="${surveyList}" varStatus="status">
<tr>
<td>${survey.surveyTitle}</td>
<td><a id="byParameter"
href="<c:url value='/home.htm/${surveyList[status.index].surveyId}' />">Share</a>
</td>
</tr>
</c:forEach>
</table>
</body>
URL getting generated is what is need, for example: /project/home.htm/15
This is how the controller looks, I have tried with both #RequestParam and #PathVariable annotations, both return 404. Controller is not getting called.
#Controller
#RequestMapping("/home.htm/parameter/surveyId=1")
public class UserHomeController {
#RequestMapping(value = "/home.htm/{surveyId}", method = RequestMethod.GET)
protected String doSubmit(#PathVariable("surveyId") int surveyId, HttpServletRequest request,
HttpServletResponse response, #ModelAttribute("userSurvey") UserSurvey userSurvey, BindingResult result)
throws AdException {
System.out.println("inside home controller, surveyId:"+surveyId");
return null;
}
}
Could anyone please help me out.

OnClick Event Not Firing Before Spring MVC Controller

I am trying to fire onClick event and Spring controller one by one.
In the click event of the button, I set a hidden field and then I want the controller to be executed AND the hidden field to be available in it. Here is my code for the JSP and the Spring Controller
JSP
<html:hidden property="MenuID" name="MenuID" id="hidMenuID" />
<c:forEach items="${menus}" var="menu" >
<tr class="cartItem">
<td align="left" >${MenuId}</td>
td align="right"><input type="text" name="menu_name" value="${Name}"/></td>
<td align="right"><input type="text" name="menu_price" value="${MenuPrice}"/></td>
<td align="right"><input type="submit" class="button" name="add_menu" value="Add" onclick="return SetMenuID();"></td>
<td align="right"><input type="submit" class="button" name="remove_menu" value="Remove" onclick="return SetMenuID();"></td>
</tr>
</c:forEach>
JavaScript
<script type="text/javascript">
function SetMenuID()
{
var MenuID = document.getElementById('hidMenuID');
MenuID.value = 'The new value';
return true;
}
</script>
Spring MVC
#RequestMapping(params = "add_menu", method = RequestMethod.POST)
public ModelAndView AddMyMenu(#RequestParam("MenuID") String menu_id, Model model, #ModelAttribute("cart") ArrayList<Menu> mycart)
{
int nMenuId = Integer.parseInt(menu_id);
Menu menu = m_arrMenus.get(nMenuId);
model.addAttribute("menus", GetMenus());
mycart.add(menu);
return new ModelAndView("edit_menu");
}
As you might guess, I am populating data from database. I have an onClick function associated with each ADD button. I set hidden field in thid function and want it to be available in my controller. But a runtime exception comes that
Error Status 400 - Required string MenuID is not present
What should I do to achieve similar result ? Thanks for any input.
#RequestParam expects a parameter my name in the request url.
Since your form is submitted and there are no request param that the action recieves. This is a reason you are getting 400 http error from server.
See the difference between #RequestParam vs #PathVariable
So either change the #RequestParam annotation or add (required = false) to it.

How to pass a session value as request parameter from JSP to servlet?

<c:forEach var="it" items="${sessionScope.projDetails}">
<tr>
<td>${it.pname}</td>
<td>${it.pID}</td>
<td>${it.fdate}</td>
<td>${it.tdate}</td>
<td> Related Documents</td>
<td>${it.pdesc}</td>
<form name="myForm" action="showProj">
<td><input id="button" type="submit" name="${it.pID}" value="View Team">
</td>
</form>
</c:forEach>
Referring to the above code, I am getting session object projDetails from some servlet, and displaying its contents in a JSP. Since arraylist projDetails have more than one records the field pID also assumes different value, and the display will be a table with many rows.
Now I want to call a servlet showProj when the user clicks on "View Team" (which will be in each row) based on the that row's "pID".
Could someone please let me know how to pass the particular pID which the user clicks on JSP to servlet?
Instead of an <input> for each different pID, you could use links to pass the pID as a query string to the servlet, something like:
View Team
In the showProj servlet code, you'll access the query string via the request object inside a doGet method, something like:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String pID = request.getParameter("pID");
//more code...
}
Here are some references for Java servlets:
HttpServletRequest object
Servlet tutorials
Pass the pID along in a hidden input field.
<td>
<form action="showProj">
<input type="hidden" name="pID" value="${it.pID}">
<input type="submit" value="View Team">
</form>
</td>
(please note that I rearranged the <form> with the <td> to make it valid HTML and I also removed the id from the button as it's invalid in HTML to have multiple elements with the same id)
This way you can get it in the servlet as follows:
String pID = request.getParameter("pID");
// ...
Define onclick function on the button and pass the parameter
<form name="myForm" action="showProj">
<input type='hidden' id='pId' name='pId'>
<td><input id="button" type="submit" name="${it.pID}" value="View Team" onclick="populatePid(this.name)">
</td>
.....
Define javascript function:
function populatePid(name) {
document.getElementById('pId') = name;
}
and in the servlet:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String pID = request.getParameter("pId");
.......
}

Categories