Controller does not recieve data from jsp page - ajax

I have sent data from jsp page to controller. It shows error.
The origin server did not find a current representation for the target
resource or is not willing to disclose that one exists.
This is my controller::::
#GetMapping(value = "/createdistrict")
public ModelAndView createdistrict(Locale locale, Model model) {
List<Division> allDivisionList = new ArrayList<Division>();
allDivisionList = this.districtService.listdivisions() ;
Map<Integer,String> allDivision = new LinkedHashMap<Integer,String>();
for( int i=0 ; i < allDivisionList.size() ; i++) {
//System.out.println(" division id ::::::::::" + allDivisionList.get(i).getId() + " division name:::::::::" + allDivisionList.get(i).getName());
allDivision.put(allDivisionList.get(i).getId() , allDivisionList.get(i).getName());
}
return new ModelAndView("createdistrict" , "allDivision" , allDivision);
}
#RequestMapping(value="/adddistrict/{division}")
public String addDistrict(#ModelAttribute("district")District district, ModelMap model ,#RequestParam("division") int division) {
System.out.println("id:::::::::::::::::::" + division);
this.districtService.adddistrict(district, division);
return "redirect:districtlist";
}
This is my jsp page::::
<form method="POST" action="/farmvill/adddistrict" modelAtribute="district">
<table class="create-table table table-hover">
<tr>
<td>
Division
</td>
<td>
<select id="division" name="division">
<c:forEach items="${allDivision}" var="allDivision">
<option class="dropdivision" value="${allDivision.key}">${allDivision.value }</option>
</c:forEach>
</select>
</td>
</tr>
<tr>
<td>
Name
</td>
<td>
<input type="text" id="name" name="name" path="name"></input>
</td>
</tr>
<!-- End of single tr -->
</table>
<!-- End of table -->
<div class="button-set text-right">
<button type="submit" class="btn site-btn filled-btn" id="savebutton">save</button>
cancel
reset
</div>
<!-- End of button-set -->
</form>
What I should do now?

Remove division from mapping path. it's a regular request parameter
#RequestMapping(value="/adddistrict")
public String addDistrict(#ModelAttribute("district")District district, ModelMap model ,#RequestParam("division") int division) {

Related

Request method 'POST' not supported Spring MVC

I've a spring form and when I click a submit button I would like to send a list of elements previously updated.
Here's the jsp :
<form:form method="post" modelAttribute="listeBlocs" action="saveFiche">
<c:forEach var="oneBloc" items="${listeBlocs}" varStatus="status">
<h5 class="col m12 s10">${oneBloc.typeBloc}</h5>
<tr>
<td><textarea name="listeBlocs[${status.index}].blocContenu" >${oneBloc.blocContenu}</textarea></td>
</tr>
</c:forEach>
<input type="submit" value="saveFiche" />
</form:form>
Here's the destination Controller:
#RequestMapping(value="/saveFiche", method = RequestMethod.POST)
private ModelAndView updateBloc(#ModelAttribute("listeBlocs") List<Bloc> lblocs) {
BlocDAO blocDAO = new BlocDAO();
for (Bloc b : lblocs) {
System.out.println("------------\nNouveau bloc : " + b.getblocContenu());
blocDAO.update(b);
}
return new ModelAndView("confirmation_update");
}
Any suggestions ?

ModelAttribute not working with lists in spring

I want to bind a List using ModelAttribute. The list contains objects of type Transaction each of which contains transactionid (type int). This is my controller code:
#RequestMapping(value = "/approvecreditdebit.do", method = RequestMethod.POST)
public ModelAndView doActions(HttpServletRequest request,
#ModelAttribute("clc") Clc transactionList, BindingResult result,
ModelMap model) {
/*
* switch (action) { case "approve":
*/
System.out.println("Obj = " + transactionList.getClass());
System.out.println("Val = " + transactionList.getTransactionList());
Users users = new Users();
return new ModelAndView("internal","internal",users);
}
This is my jsp code:
<form:form action="approvecreditdebit.do" method="POST"
modelAttribute="clc">
<table border="1">
<tr>
<th>no</th>
<th>ID</th>
</tr>
<c:forEach items="${clc.transactionList}"
var="transaction" varStatus="status">
<tr>
<td>${status.index}</td>
<td><input name = "transaction[${status.index}].transactionId"
value="${transaction.transactionId}" /></td>
</tr>
</c:forEach>
</table>
<br>
<br>
<center>
<input type="submit" value="approve" />
</center>
</form:form>
This is the Clc class:
public class Clc{
private List<Transaction> transactionList;
public List<Transaction> getTransactionList() {
return transactionList;
}
public void setTransactionList(List<Transaction> transactionList) {
this.transactionList = transactionList;
}
}
The value of transactionList is not being set to the values received from the form. I receive the following error:
Request processing failed; nested exception is java.lang.NullPointerException
I tried searching for the solution on google and got a lot of solutions from stackoverflow but none of them seem to work.
Try something like this (notice the use of <form:input>). I just tried it on a simple Spring MVC app and it works (list is not null and has the values from the form when I try to access it in my POST method).
<c:forEach var="transaction" varStatus="status" items="${clc.transactionList}">
<tr>
<td>${status.index}</td>
<td><form:input path="transactionList[${status.index}].id" /></td>
</tr>
</c:forEach>

is it possible to add buttons dynamically and pass their values accordingly?

I am new to spring technology please help to solve this problem.
I am developing a web application in spring in which I have a leaveRecords.jsp page,and It should load following things,
For each records the page should display records into the table with two buttons like
<button id="Accept"
name="action"
type="submit"
value="Accept<%= dtoBean.getEmployee_id()/>
<button id="Reject"
name="action"
type="submit"
value="Accept<%= dtoBean.getEmployee_id()/>
After clicking on accept button relevant action will be performed and should redirect to same page but this time the page should contain button like
<button id="Cancel"
name="action"
type="submit"
value="Accept<%= dtoBean.getEmployee_id() />
the leaveRecords.jsp is:
<form:form method="POST" action="upcomingLeaves.do" commandName="loginForm" modelAttribute="loginForm">
<% CommonDTOBean dtoBean=(CommonDTOBean)session.getAttribute("dtoBean");
List upcomingLeavesList=(ArrayList)session.getAttribute("upcomingLeavesList");%>
<table ><col><thead ><tr style="background-color:#666633;">
<th>Employee id</th>
<th>Leave Balance</th>
<th>Date</th>
<th>Leave Type</th>
<th>Leave Period</th>
<th>Applied Leaves</th>
<th>Status</th>
<th colspan="4">Action</th>
</tr></thead>
<tbody>
<%if(upcomingLeavesList!=null){
for(int i=0;i<upcomingLeavesList.size();i++){
dtoBean=(CommonDTOBean)upcomingLeavesList.get(i);%>
<tr>
<td ><span><%= dtoBean.getEmployee_id() %></span></td>
<td ><span><%= dtoBean.getNo_of_leave() %></span></td>
<td ><span></span><%= dtoBean.getFromDate() %>-<%= dtoBean.getToDate() %></td>
<td > <span><%= dtoBean.getLeaveType() %></span></td>
<td ><span></span><%= dtoBean.getLeavePeriod() %></td>
<td><span></span><%= dtoBean.getAppliedLeave() %></td>
<td><span></span><%= dtoBean.getLeaveStatus() %></td>
<td><button id="btnAccept" name="action" type="submit" value="Accept<%= dtoBean.getEmployee_id() %>" onclick="">Approve</button></td>
<td><button id="btnReject" name="action" type="submit" value="Reject<%= dtoBean.getEmployee_id() %>">Reject</button></td>
<td><button id="btnCancel" name="action" type="submit" value="Cancel<%= dtoBean.getEmployee_id() %>">Cancel</button></td>
</tr>
<%}}%>
</tbody>
</table>
</form:form>
Controller class is:
public String ApproveLeaves(#RequestParam(required=false , defaultValue="")String aion,#RequestParam(required=false,defaultValue="")String Cancel,HttpServletRequest request, HttpServletResponse response, ModelMap model){
try{
//following strings are used for getting the value of button and spiting it to get employee id
String buttonName=request.getParameter("action");
String buttonValue=buttonName.substring(0,6);// here we are spliting up the string and button name
int buttonValue1=Integer.parseInt(buttonName.substring(6));
if (buttonValue.equalsIgnoreCase("Reject"))
{
boolean status=LeaveStatusWorker.Approve(buttonValue1,buttonValue,dtoBean);
if (status)
{
return "redirect: GlobalConstants.UPCOMING_LEAVES";
}
}
if (buttonValue.equalsIgnoreCase("Cancel"))
{
boolean status=LeaveStatusWorker.Approve(buttonValue1,buttonValue,dtoBean);
if (status)
{
return "redirect: GlobalConstants.UPCOMING_LEAVES";
}
}
if (buttonValue.equalsIgnoreCase("Accept"))
{
boolean status=LeaveStatusWorker.Approve(buttonValue1,buttonValue,dtoBean);
if (status)
{
return "redirect: GlobalConstants.UPCOMING_LEAVES";
}
}
return GlobalConstants.UPCOMING_LEAVES;
}
catch(Exception e)
{
System.out.println(e);
}
return GlobalConstants.ERRORPAGE;
}
service class has a method for db interaction:
public static boolean Approve(int id,String buttonValue,CommonDTOBean dtoBean2)
{
try {
con=DBConnection.getConnection();
String query="select no_of_leave from newemp_register where emp_id=?";//get available leaves from db
pstmt.executeQuery();
if(buttonValue.equalsIgnoreCase("Cancel"))
{
String approve="Update newemp_register set no_of_leave=? where emp_id=?";
pstmt.executeUpdate();
}
if(buttonValue.equalsIgnoreCase("Reject"))
{
return true;
}
if(buttonValue.equalsIgnoreCase("Accept"))
{
String approve="Update newemp_register set no_of_leave=? where emp_id=?";
pstmt.executeUpdate();
return true;
}
}
}//End Of while
} catch (Exception e) {
}
return false;
}//End of Approve
Please go through this example and help me I have tried very hard and searched on Google but could not solve it.
CommonDTOBean class:
public class CommonDTOBean {
private int emp_id;
private String Status;
public int getEmp_id() {
return emp_id;
}
public void setEmp_id(int emp_id) {
this.emp_id = emp_id;
}
public String getStatus() {
return Status;
}
public void setStatus(String status) {
Status = status;
}
Use JSTL for conditional rendering the DOM in jsp. like:
<form:form method="POST" action="upcomingLeaves.do" commandName="loginForm" modelAttribute="loginForm">
<table>
<thead>
<tr style="background-color:#666633;">
<th>Employee id</th>
<th>Leave Balance</th>
<th>Date</th>
<th>Leave Type</th>
<th>Leave Period</th>
<th>Applied Leaves</th>
<th>Status</th>
<th colspan="4">Action</th>
</tr></thead>
<tbody>
<c:choose>
<c:when test="${not empty upcomingLeavesList}">
<c:forEach items="${upcomingLeavesList}" var="upComLeave">
<tr>
<td><span>${upComLeave.emp_id}</span></td>
<td><span>${upComLeave.status}</span></td>
<td><span>${upComLeave.fromDate} - ${upComLeave.toDate}</span></td>
<td><span>${upComLeave.leaveType}</span></td>
<td><span>${upComLeave.leavePeriod}</span></td>
<td><span>${upComLeave.appliedLeave}</span></td>
<td><span>${upComLeave.leaveStatus}</span></td>
<c:if test="${upComLeave.leaveStatus ne 'accepted' }"> //check status if accepted, don't render Accept button
<td><button id="btnAccept" name="action" type="submit" value="Accept${upComLeave.emp_id}" onclick="">Approve</button></td>
</c:if>
<c:if test="${upComLeave.leaveStatus ne 'rejected' }">//check status if accepted, don't render Reject button
<td><button id="btnReject" name="action" type="submit" value="Reject${upComLeave.emp_id}">Reject</button></td>
</c:if>
<c:if test="${upComLeave.leaveStatus eq 'cancel' }">//check status if cancel, render cancel button
<td><button id="btnCancel" name="action" type="submit" value="Cancel${upComLeave.emp_id}">Cancel</button></td>
</c:if>
</tr>
</c:forEach>
</c:when>
<c:otherwise>
upcomingLeavesList is empty or null..
</c:otherwise>
</c:choose>
</tbody>
</table>
</form:form>
Edit 1(based on comments):
If I click on approve the page should redirect with only Cancel and
Reject button
use one more if condition like:
<c:if test="${upComLeave.leaveStatus eq 'accepted' }">
<td><button id="btnReject" name="action" type="submit" value="Reject${upComLeave.emp_id}">Reject</button></td>
<td><button id="btnCancel" name="action" type="submit" value="Cancel${upComLeave.emp_id}">Cancel</button></td>
</c:if>
Note:
add this on top of jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

Encounter error when there is if else in mvc view

i am new in mvc and trying to learn.i want to display a form when ViewBag.Success is null or empty but if ViewBag.Success is true then i want to render a partial view.
here is my code
<div id="mydiv">
#if (ViewBag.Success != null && ViewBag.Success == true) //Show the message
{
Html.RenderPartial("Message");
}
else
{
#using (Html.BeginForm("Save", "Game", FormMethod.Post, new { #Id = "Form1" }))
{
<table border="0">
<tr>
<td>
Name :
</td>
<td>
<input name="name" type="text" />
</td>
</tr>
<tr>
<td>
Salary :
</td>
<td>
<input name="salary" type="text" />
</td>
</tr>
<tr>
<td colspan="2">
<input name="btnSubmit" type="submit" value="Save" />
</td>
</tr>
</table>
}
}
</div>
the error message i am getting when i am running like
Expected a "{" but found a "/". Block statements must be enclosed in "{" and "}". You cannot use single-statement control-flow statements in CSHTML pages. For example, the following is not allowed:
what i am doing wrong not being able to understand. please help & guide. thanks
# symbol is only required when your code is contained within an HTML element. The using statement does not need the # because it is a direct decedent of your if else block.
Example:
<div> <!-- html tag -->
#if(something == somethingElse) // requires # because direct decedent of html tag <div>
{
<p>
#for (var i=0; i < len; i++) // requires # because direct decedent of html tag <p>
{
if(i == 1) // doesnt require #, not decedent of any HTML tag, instead direct decedent of another razor statement (for)
{
//do something
}
}
</p>
}
</div>
The # sign is use to distinguish between a simple string / HTML and razor statements. You only need that when you are writing C# code between HTML code. But when you are have started a C# code block, the ASP.NET MVC View Engine is intelligent enough to understand that the code that follows is C# and not simply some string.

How to modify a record displaying a form in a view

I am trying to accomplish the following:
I have a list of fruits, that are stored in a table with two columns "id", "name" and "color".
Next to each fruit, I got a "modify" button. What I want to do here is being able to display the fruit in a form and being able to modify the "name" and "color" attributes.
I don't understand why, but when I click the "modify" button, the form is being displayed but the properties of the fruits that I clicked are not.
Here is the code:
Controller:
#RequestMapping(value = "/fruit/modify", method = RequestMethod.POST)
public String modifyFruit( #RequestParam("id") int id, ModelMap model) {
Fruit fruit = fruitManager.getFruitById(id);
model.addAttribute("fruit", fruit);
return "redirect:/modifyfruit";
}
#RequestMapping(value = "/modifyfruit", method = RequestMethod.GET)
public String showAddForm(#ModelAttribute("fruit") Fruit fruit, ModelMap model) {
model.addAttribute("fruit", fruit);
return "/secure/modifyfruit";
}
Here is the modify button that I am displaying next to each fruit in my list:
<td>
<c:url var="modifyUrl" value="/fruit/modify.html"/>
<form id="${fruitForm}" action="${modifyUrl}" method="POST">
<input id="id" name="id" type="hidden" value="${fruit.id}"/>
<input type="submit" value="modify"/>
</form>
</td>
Here is the modifyfruit.jsp that I am using to display the form that I want to populate:
<body>
<form:form method="post" commandName="fruit">
<table width="95%" bgcolor="f8f8ff" border="0" cellspacing="0"
cellpadding="5">
<tr>
<td align="right">Name:</td>
<td><form:input path="title" value="${fruit.name}"/></td>
</tr>
<tr>
<td align="right">Color:</td>
<td><form:input path="color" value="${fruit.color}"/></td>
</tr>
</table>
<br>
<input type="submit" align="center" value="Post Ad">
</form:form>
</body>
Your redirect is simply going to that new URL without any request params being added. Therefore your fruit ID is being discarded, which is why nothing gets displayed.
The redirect seems pointless - why not return the same view name string as the GET version instead?
To redirect with the params, try:
return "redirect:/modifyfruit?id=" + id;
EDIT: just noticed you have added the Fruit to the model - this does not get transferred in a redirect and wouldn't work anyway.

Resources