Spring Web Application doesn't supports both GET and POST - java

I am supporting a web application developed in Spring MVC and Sitemesh. I have to add pagination capability in one of the pages in the application. I am getting the same page loaded first time with N number of records as I mentioned as MaximumResults in Hibernate. But when I click the Next button, it is saying that the POST method is not supported and supported method is GET. I then changed the respective method type in Controller and Form to GET. But then it is saying that GET is not supported and supported method is POST.
I removed the Sitemesh configuration itself and tried as I read Sitemesh sometimes creates the issue though it didn't works. I tried to replace the <mvc:resources> configuration as well with SimpleHttpRequestHandler though there were no joy.
Please see the respective JSP, Controller, Spring Configuration and web.xml attached .
Triggering page:
<form:form id="form-${eta.paymentPeriod.period}" method="post" modelAttribute="etaForm" action="${pageContext.request.contextPath}/performance/searchPeriodSpecificETADetails.htm">
<tr>
<input name="courierId" type="hidden" value="<c:out value="${etaDetails.courierId}"/>"/>
<input name="year" type="hidden" value="<c:out value="${eta.paymentPeriod.year}"/>"/>
<input name="period" type="hidden" value="<c:out value="${eta.paymentPeriod.period}"/>"/>
<input name="timeslot" type="hidden" value="<c:out value="${eta.timeSlot}"/>"/>
<input name="daysPassed" type="hidden" value="<c:out value="${eta.daysPassed}"/>"/>
<input name="percentage" type="hidden" value="<c:out value="${eta.percentage}"/>"/>
<td style="padding-left:10px; color:blue;">
<button type="submit" class="link"><span><c:out value="P${eta.paymentPeriod.period}"/></span></button>
<%-- ${eta.paymentPeriod.period} --%>
</td>
<td style="padding-left:40px"> <c:out value="${eta.timeSlot}"/> </td>
<td style="padding-left:20px"> <c:out value="${eta.percentage}"/> </td>
<td style="padding-left:30px"> <c:out value="${eta.daysPassed}"/> </td>
<td style="padding-left:30px"> <c:out value="${eta.daysFailed}"/> </td>
</tr>
</form:form>
*Paginated JSP:
<c:forEach var="eta" items="${etaDaySpecificDetails}">
<form:form method="post" modelAttribute="etaForm" action="${pageContext.request.contextPath}/performance/searchPeriodSpecificETAFailureDetails.htm">
<tr>
<c:set var="failed" value="${eta.set - eta.passed}"/>
<c:if test="${eta.passed == eta.set}">
<fmt:formatNumber value="100" var="success" maxFractionDigits="1"/>
</c:if>
<c:if test="${eta.passed != eta.set}">
<fmt:formatNumber value="${(eta.passed / eta.set)*100}" var="success" maxFractionDigits="1"/>
</c:if>
<fmt:formatDate value="${eta.date}" var="etaDate" pattern="E d MMM" />
<input name="year" type="hidden" value="<c:out value="${etaSummery.year}"/>"/>
<input name="period" type="hidden" value="<c:out value="${etaSummery.period}"/>"/>
<input name="timeslot" type="hidden" value="<c:out value="${etaSummery.timeslot}"/>"/>
<input name="courierId" type="hidden" value="<c:out value="${etaSummery.courierId}"/>"/>
<input name="dateId" type="hidden" value="<c:out value="${eta.dateId}"/>"/>
<input name="date" type="hidden" value="<c:out value="${eta.date}"/>"/>
<input name="daysPassed" type="hidden" value="<c:out value="${etaSummery.daysPassed}"/>"/>
<input name="percentage" type="hidden" value="<c:out value="${etaSummery.percentage}"/>"/>
<td style="padding-left: 10px; color: blue;"><c:out value="${etaDate}" /></td>
<td style="padding-left: 10px"><c:out value="${eta.set}" /></td>
<td style="padding-left: 20px"><c:out value="${eta.modified}" /></td>
<td style="padding-left: 30px"><c:out value="${eta.cancelled}" /></td>
<td style="padding-left: 30px"><c:out value="${eta.passed}" /></td>
<c:if test="${failed > 0}">
<td style="padding-left:30px;">
<button type="submit" id="failure_link_${eta.dateId}" class="link" style="color:red;text-decoration: underline;"><span><c:out value="${failed}"/></span></button>
</td>
</c:if>
<c:if test="${failed == 0}">
<td style="padding-left: 30px"><c:out value="${failed}" /></td>
</c:if>
<td style="padding-left: 15px"><c:out value="${success}" /> %</td>
</tr>
</form:form>
</c:forEach>
</table>
<form:form id="form-next" method="POST" modelAttribute="etaForm" action="${pageContext.request.contextPath}/performance/searchPeriodSpecificETADetailsNextRecord.htm">
<input name="year" type="hidden" value="<c:out value="${etaSummery.year}"/>"/>
<input name="period" type="hidden" value="<c:out value="${etaSummery.period}"/>"/>
<input name="timeslot" type="hidden" value="<c:out value="${etaSummery.timeslot}"/>"/>
<input name="courierId" type="hidden" value="<c:out value="${etaSummery.courierId}"/>"/>
<input name="paginationMetaInfo" type="hidden" value="<c:out value="${etaSummery.paginationMetaInfo}"/>"/>
<td style="padding-left:10px; color:blue;">
<button type="submit" class="link"><span>Next</span></button>
<%-- ${eta.paymentPeriod.period} --%>
</form:form>
**Controller **
#Controller
#SessionAttributes("courierDetails")
#RequestMapping("performance")
public class CourierPerformanceController {
private CourierPerformanceManager courierPerformanceManager;
#Autowired
private MessageSource messages;
private MyPerformanceManager myPerformanceManager;
private BeanPropertyCopier beanPropertyCopier;
#Value("${info.myperformance.depot.secondTarget}")
private Double depoSecondTarget;
#Value("${info.myperformance.delivery.secondTarget}")
private Double deliverySecondTarget;
#Value("${info.myperformance.collection.secondTarget}")
private Double collectionSecondTarget;
private static final String DOZ_ETA_VO_TO = "etaVOToEtaTo";
private static final String ATTR_ETA_DAY_SPECIFIC_DETAILS = "etaDaySpecificDetails";
private static final String ATTR_ETA_DAY_SPECIFIC_FAILURE_DETAILS = "etaDaySpecificFailureDetails";
private static final String ATTR_ETA_SUMMERY = "etaSummery";
private static final String ATTR_ETA_DETAILS = "etaDetails";
private static final String DATA_TYPE_JSON = "application/json";
#Autowired
public CourierPerformanceController(MyPerformanceManager myPerformanceManager,CourierPerformanceManager courierPerformanceManager,
BeanPropertyCopier beanPropertyCopier) {
this.myPerformanceManager = myPerformanceManager;
this.courierPerformanceManager = courierPerformanceManager;
this.beanPropertyCopier = beanPropertyCopier;
}
private DataTables buildDataTables(CourierDetails courierDetails) throws CouriersException {
MyPerformanceResults results = myPerformanceManager.getPerformanceDetails(courierDetails.getCrId());
return CourierPerformanceGraphUtil.createAndInitializeDataTableWithCourierPerformanceDetails(results, messages);
}
#RequestMapping(
value = {
WEB_REQUEST_URL.COUR_PERF_CONTROLLER_HTTP_GET_SEARCH_ENQUIRY_PEFORMANCE_DETAILS,
WEB_REQUEST_URL.COUR_PERF_CONTROLLER_HTTP_GET_SEARCH_COLLECTION_PEFORMANCE_DETAILS,
WEB_REQUEST_URL.COUR_PERF_CONTROLLER_HTTP_GET_SEARCH_RECEIPT_PEFORMANCE_DETAILS,
WEB_REQUEST_URL.COUR_PERF_CONTROLLER_HTTP_GET_SEARCH_DELIVERY_PEFORMANCE_DETAILS},
method = RequestMethod.GET, produces = DATA_TYPE_JSON)
public #ResponseBody DataTables searchCourierEnquiryPerformanceDetails(#ModelAttribute CourierDetails courierDetails, HttpServletRequest session)
throws CouriersException {
DataTables dataTables = buildDataTables(courierDetails );
return dataTables;
}
#RequestMapping(
value = WEB_REQUEST_URL.COUR_PERF_CONTROLLER_HTTP_GET_ETA_DETAILS_FOR_PRIMARY_TAB, method = RequestMethod.GET)
public ModelAndView searchCourierETAPerformanceDetailsForPrimaryTab(#ModelAttribute CourierDetails courierDetails,Model model, HttpServletRequest session)
throws CouriersException {
ETASearchCriteria searchCriteria = new ETASearchCriteria();
searchCriteria.setCourierId(courierDetails.getCrId());
resetPaginationMetaInfo();
final ETADetails etaDetails = courierPerformanceManager.searchETAForAllAvailablePeriods(searchCriteria);
return new ModelAndView(SPRING_VIEW_URL.COUR_PERF_CONTROLLER_COURIER_ETA_PERFORMANCE_DETAILS, ATTR_ETA_DETAILS , etaDetails);
}
#RequestMapping(
value = WEB_REQUEST_URL.COUR_PERF_CONTROLLER_HTTP_GET_DELIVERY_PEFORMANCE_DETAILS, method = RequestMethod.GET)
public ModelAndView redirectToCourierDeliveryDetails(#ModelAttribute CourierDetails courierDetails, HttpServletRequest session)
throws CouriersException {
return new ModelAndView(SPRING_VIEW_URL.COUR_PERF_CONTROLLER_COURIER_ETA_DELIVERY_DETAILS);
}
#RequestMapping(
value = WEB_REQUEST_URL.COUR_PERF_CONTROLLER_HTTP_GET_RECEIPT_PEFORMANCE_DETAILS, method = RequestMethod.GET)
public ModelAndView redirectToCourierReceiptDetails(#ModelAttribute CourierDetails courierDetails, HttpServletRequest session)
throws CouriersException {
return new ModelAndView(SPRING_VIEW_URL.COUR_PERF_CONTROLLER_MYPERFORMANCE);
}
#RequestMapping(
value = WEB_REQUEST_URL.COUR_PERF_CONTROLLER_HTTP_GET_COLLECTION_PEFORMANCE_DETAILS, method = RequestMethod.GET)
public ModelAndView redirectToCourierCollectionDetails(#ModelAttribute CourierDetails courierDetails, HttpServletRequest session)
throws CouriersException {
return new ModelAndView(SPRING_VIEW_URL.COUR_PERF_CONTROLLER_COURIER_COLLECTION_DETAILS);
}
#RequestMapping(
value = WEB_REQUEST_URL.COUR_PERF_CONTROLLER_HTTP_GET_ENQUIRY_PEFORMANCE_DETAILS, method = RequestMethod.GET)
public ModelAndView redirectToCourierEnquiryDetails(#ModelAttribute CourierDetails courierDetails, HttpServletRequest session)
throws CouriersException {
return new ModelAndView(SPRING_VIEW_URL.COUR_PERF_CONTROLLER_COURIER_ENQUIRY_DETAILS);
}
#RequestMapping(
value = WEB_REQUEST_URL.COUR_PERF_CONTROLLER_HTTP_POST_SERACH_PERIOD_SPECIFIC_ETA_DETAILS, method = RequestMethod.POST)
public String searchPeriodSpecificETADetails(#ModelAttribute CourierDetails courierDetails,#ModelAttribute("etaForm")
ETAValueObject etaValueObject , Model model,
HttpServletRequest session) throws CouriersException {
List<DaySpecificETAInformation> etaDetails = searchETADetailsForSpecificPeriod(etaValueObject);
model.addAttribute(ATTR_ETA_DAY_SPECIFIC_DETAILS, etaDetails);
model.addAttribute(ATTR_ETA_SUMMERY, etaValueObject);
return SPRING_VIEW_URL.COUR_PERF_CONTROLLER_COURIER_ETA_DAY_SPECIFIC_PERF_DETAILS;
}
#RequestMapping(
value = WEB_REQUEST_URL.COUR_PERF_CONTROLLER_HTTP_POST_SERACH_PERIOD_SPECIFIC_ETA_DETAILS_NEXT_RECORD, method = RequestMethod.POST)
public String searchPeriodSpecificETADetailsNextRecord(#ModelAttribute CourierDetails courierDetails,#ModelAttribute("etaForm")
ETAValueObject etaValueObject , Model model,
HttpServletRequest session) throws CouriersException {
List<DaySpecificETAInformation> etaDetails = searchETADetailsForSpecificPeriod(etaValueObject);
model.addAttribute(ATTR_ETA_DAY_SPECIFIC_DETAILS, etaDetails);
model.addAttribute(ATTR_ETA_SUMMERY, etaValueObject);
return SPRING_VIEW_URL.COUR_PERF_CONTROLLER_COURIER_ETA_DAY_SPECIFIC_PERF_DETAILS;
}
#RequestMapping(
value = WEB_REQUEST_URL.COUR_PERF_CONTROLLER_HTTP_POST_SERACH_PERIOD_SPECIFIC_ETA_FAIL_DETAILS, method = RequestMethod.POST)
public String searchDaySpecificETAFailureInformation(#ModelAttribute CourierDetails courierDetails,#ModelAttribute
ETAValueObject etaValueObject , Model model,
HttpServletRequest session) throws CouriersException {
List<DaySpecificETAFailureInformation> etaDetails = searchDaySpecificETAFailureInformation(etaValueObject);
model.addAttribute(ATTR_ETA_DAY_SPECIFIC_FAILURE_DETAILS, etaDetails);
model.addAttribute(ATTR_ETA_SUMMERY, etaValueObject);
return SPRING_VIEW_URL.COUR_PERF_CONTROLLER_COURIER_ETA_DAY_SPECIFIC_FAIL_DETAILS;
}
private List<DaySpecificETAInformation> searchETADetailsForSpecificPeriod(ETAValueObject etaValueObject) {
ETASearchCriteria searchCriteria = copyDetailsFromSourceToDestination(etaValueObject, ETASearchCriteria.class, DOZ_ETA_VO_TO);
availSearchResultsCountForETADetailsForSpecificPeriod(searchCriteria,etaValueObject);
List<DaySpecificETAInformation> etaDetails = courierPerformanceManager.searchETADetailsForSpecificPeriod(searchCriteria);
return etaDetails;
}
private void availSearchResultsCountForETADetailsForSpecificPeriod(ETASearchCriteria searchCriteria,ETAValueObject etaValueObject) {
PaginationMetaInfo paginationMetaInfoFromView = etaValueObject.getPaginationMetaInfo();
if(paginationMetaInfoFromView == null) {
paginationMetaInfoFromView = PaginationMetaInfo.getPaginationMetaInfo();
Integer maximumResults = courierPerformanceManager.findSearchResultsCountForETAFailureDetailsForSpecificDateAndPeriod(searchCriteria);
paginationMetaInfoFromView.setMaximumResults(maximumResults);
etaValueObject.setPaginationMetaInfo(paginationMetaInfoFromView);
}
PaginationMetaInfo.addPaginationMetaInfo(paginationMetaInfoFromView);
paginationMetaInfoFromView.updateNextRowIndex();
}
private void resetPaginationMetaInfo() {
PaginationMetaInfo.addPaginationMetaInfo(new PaginationMetaInfo());
PaginationMetaInfo.getPaginationMetaInfo().setNextRowIndex(0);
}
private List<DaySpecificETAFailureInformation> searchDaySpecificETAFailureInformation(ETAValueObject etaValueObject) {
ETASearchCriteria searchCriteria = copyDetailsFromSourceToDestination(etaValueObject, ETASearchCriteria.class, DOZ_ETA_VO_TO);
List<DaySpecificETAFailureInformation> etaDetails = courierPerformanceManager.searchETAFailureDetailsForSpecificDateAndPeriod(searchCriteria);
return etaDetails;
}
private <T> T copyDetailsFromSourceToDestination(Object src, Class<T> clazz, String mappingName) {
return beanPropertyCopier.copyDetailsFromSourceToDestination(src, clazz, mappingName);
}
}
I am hitting the searchPeriodSpecificETADetails from the first page and searchPeriodSpecificETADetailsNextRecord for the paginated results.
static String COUR_PERF_CONTROLLER_HTTP_POST_SERACH_PERIOD_SPECIFIC_ETA_DETAILS = "/searchPeriodSpecificETADetails";
static String COUR_PERF_CONTROLLER_HTTP_POST_SERACH_PERIOD_SPECIFIC_ETA_DETAILS_NEXT_RECORD = "/searchPeriodSpecificETADetailsNextRecord.htm";
Spring Configuration
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/images/**" location="/images/" />
<mvc:resources mapping="/img/**" location="/images/" />
<mvc:resources mapping="/fonts/**" location="/fonts/" />
<mvc:resources mapping="/js/**" location="/js/" />
<bean class="org.springframework.http.converter.ResourceHttpMessageConverter"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
Web.xml
<filter>
<filter-name>sitemeshGeneralFilter</filter-name>
<filter-class>uk.co.hermes.filters.SitemeshGeneralFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>sitemeshGeneralFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>ERROR</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
Sitemesh Filter
public class SitemeshGeneralFilter extends ConfigurableSiteMeshFilter {
private final Logger LOG = Logger.getLogger(SitemeshGeneralFilter.class);
public SitemeshGeneralFilter() {
super();
}
/**
* See http://wiki.sitemesh.org/display/sitemesh3/Configuring+SiteMesh+3
*/
#Override
protected void applyCustomConfiguration(SiteMeshFilterBuilder builder) {
// apply this decorator (template) to the path defined...
builder.addDecoratorPath("/*", "/WEB-INF/jsp/sitemeshDecorators/generalDecorator.jsp")
// ... when the response type matches one of these
.setMimeTypes("text/html", "application/xhtml+xml", "application/vnd.wap.xhtml+xml");``
}}
It would be really great if someone can help me.

Related

How to have add and remove buttons in html form handle by spring 5 controller?

I am using Spring 5 and Hibernate 5.
I have got form like below in jsp file:
<form:form action="addUser" method="post" modelAttribute="user">
<table>
<tr>
<td>Name</td>
<td>
<form:input path="name" /> <br />
<form:errors path="name" cssClass="error" />
</td>
</tr>
<tr>
<td>Email</td>
<td>
<form:input path="email" /> <br />
<form:errors path="email" cssClass="error" />
</td>
</tr>
<tr>
<td colspan="1"><button type="submit">Submit</button></td>
<td colspan="1"><button type="???delete???">Remove</button></td>
</tr>
</table>
</form:form>
And UserController.java like below:
#Controller
public class UserController {
#Autowired
private UserService userService;
#GetMapping("/")
public String userForm(Locale locale, Model model) {
model.addAttribute("users", userService.list());
return "editUsers";
}
#ModelAttribute("user")
public User formBackingObject() {
return new User();
}
#PostMapping("/addUser")
public String saveUser(#ModelAttribute("user") #Valid User user, BindingResult result, Model model) {
if (result.hasErrors()) {
model.addAttribute("users", userService.list());
return "editUsers";
}
userService.save(user);
return "redirect:/";
}
}
Right now I have got a submit button which allow me to save name and email of the user.
I would like to add button REMOVE which would also relay on the same form but will instead of adding new user will be removing existing user.
Could you tell how can I do it?
Maybe the first option is to add some attribute like action, but then I need to handle it in controller and I don't know how?
Thank you.
It can be done by changing the form action dynamically based on the button click using some javascript.
<script>
$('#addBtn').click(function(){
$("#userForm").submit();
});
$('#removeBtn').click(function(){
$('#userForm').attr('action', '<your remove action>');
$("#userForm").submit();
});
<script>
<form:form action="addUser" method="post" modelAttribute="user" id="userForm">
...
<td colspan="1"><button type="button" id='addBtn'>Submit</button></td>
<td colspan="1"><button type="button" id='removeBtn'>Remove</button></td>
...
</form:form>

Spring MVC: Unable to bind data to my modelAttribute when trying to edit the form

I am trying to edit a submitted form but I am facing difficulties in doing so the problem is when I am submitting the form after editing null is being sent.I have been trying to get rid of this by myself but alas I have not been able to so.Please help me out.
My controller(only significant part)
#RequestMapping(value = "/registerstudentProcess", method = RequestMethod.POST)
public ModelAndView addStudent(HttpServletRequest request, #ModelAttribute("add_student") Student user) {
userService.registerStudent(user, request.getParameter("password"));
ModelAndView mav = new ModelAndView("addedstudent");
mav.addObject("adminsession");
mav.addObject("user", user);
mav.addObject("success_msg", user.getId() + " has been successfully added as an Student");
return mav;
}
#RequestMapping(value = "/editstud",method=RequestMethod.GET)
public ModelAndView editstud(HttpServletRequest request) {
ModelAndView mav = new ModelAndView("editstudent");
// mav.addObject("upd", new Student());
mav.addObject("adminsession");
mav.addObject("olduser", userService.editStudent(Integer.parseInt(request.getParameter("nayastud"))));
mav.addObject("batches", userService.getAllBatches());
return mav;
}
#RequestMapping(value = "/updatestud", method = RequestMethod.POST)
public ModelAndView updatestud(HttpServletRequest request, #ModelAttribute("olduser") Student stup) {
ModelAndView mav = new ModelAndView("addedstudent");
mav.addObject("adminsession");
mav.addObject("user", userService.updateStudent(stup));
mav.addObject("success_msg", stup.getId() + " has been successfully added as an Student");
return mav;
}
Model:Student.java
package project.ams.model;
public class Student {
private Integer id;
private String email;
private String name;
private String batch;
private String session;
private String address;
private String contact;
private String status;
//with proper getters and setters
}
addedstudent.jsp
<table class="table table-bordered table-condensed" align="center">
<tr>
<th colspan="2" style="text-align: center;">DETAILS</th>
<tr>
<tr>
<td><label>Id</label></td>
<td>${user.id}</td>
</tr>
<tr>
<td><label>Name</label></td>
<td>${user.name}</td>
</tr>
<tr>
<td><label>Email</label></td>
<td>${user.email}</td>
</tr>
<tr>
<td><label>Batch</label></td>
<td>${user.batch}</td>
</tr>
<tr>
<td><label>Session</label></td>
<td>${user.session}</td>
</tr>
<tr>
<td><label>Address</label></td>
<td>${user.address}</td>
</tr>
<tr>
<td><label>Phone Number:</label></td>
<td>${user.contact}</td>
</tr>
</table>
<table class="table table-condensed" align="center">
<tr>
<td>
<form:form id="editForm" action="editstud" method="post">
<input type="hidden" name="nayastud" value="${user.id}"/>
<button name="register"
class="btn btn-default">Edit Details</button>
</form:form>
</td>
<td>
<button onclick="location.href='admhome'"
class="btn btn-default">Back To Home</button></td>
</tr>
</table>
editstudent.jsp
<form:form id="regForm" modelAttribute="olduser" action="updatestud"
method="post">
<div class="form-group">
<form:label path="id">Enrollment Number</form:label>
<form:input path="id" name="id" id="id" class="form-control"
value="${olduser.id}" disabled="true" />
</div>
<div class="form-group">
<form:label path="name">Name</form:label>
<form:input path="name" name="name" id="name" class="form-control"
value="${olduser.name}" />
</div>
<div class="form-group">
<form:label path="email">Email</form:label>
<form:input path="email" name="email" id="email"
class="form-control" value="${olduser.email}" />
</div>
<div class="form-group">
<form:label path="batch">Batch</form:label>
<form:select path="batch" name="batch" id="batch"
class="form-control">
<option value="${olduser.batch}" selected></option>
<c:forEach var="bat" items="${batches}">
<form:option path="batch" value="${bat}">${bat}</form:option>
</c:forEach>
</form:select>
</div>
<div class="form-group">
<form:label path="session">Session</form:label>
<form:input path="session" name="session" id="session"
class="form-control" value="${olduser.session}" />
</div>
<div class="form-group">
<form:label path="address">Address</form:label>
<form:input path="address" name="address" id="address"
class="form-control" value="${olduser.address}" />
</div>
<div class="form-group">
<form:label path="contact">Phone</form:label>
<form:input path="contact" name="contact" id="contact"
class="form-control" value="${olduser.contact}" />
</div>
<div class="form-group">
<input type="hidden" name="password" value="Hello#123" />
<form:input type="hidden" path="status" name="status" value="a" />
</div>
<button id="register" name="register" class="btn btn-default">Update</button>
</form:form>
Edit 1
Added Screenshots(Sorry not able to post more screenshots due to reputation issues.)
Here I am changing the address and trying to update its value in the db.
Editing Student Info
Error here.Getting null object back from the edit page
when you are sending get request to fetch edit_student then you are passing value through request param and you should access this value using #PathVariable
or #RequestParam ..
<form:form id="editForm" action="editstud" method="post">
Expects a post handler
#RequestMapping(value = "/editstud",method=RequestMethod.GET)
is defined to accept only GET requests.
Try changing edit student method to
#RequestMapping(value = "/editstud",method=RequestMethod.GET)
public ModelAndView editstud(#RequestParam String nayastud) {
ModelAndView mav = new ModelAndView("editstudent");
mav.addObject("adminsession");
mav.addObject("olduser", userService.editStudent(Integer.parseInt(request.getParameter("nayastud"))));
mav.addObject("batches", userService.getAllBatches());
return mav;
}

Invalid target for Validator - Spring MVC

I'm having problems with validating in Spring. I'm getting the following error after opening the form:
java.lang.IllegalStateException: Invalid target for Validator [com.example.validator.UserValidator#6ac0a8f4]: com.example.web.forms.UserDTO#4d3b2379
My Validator for the time being, wanted to check if anything works first:
#Component
public class UserValidator implements Validator {
#Autowired
ServiceUser serviceUser;
#Override
public boolean supports(Class<?> clazz) {
return User.class.equals(clazz);
}
#Override
public void validate(Object target, Errors errors) {
User user = (User) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "NotEmpty.userForm.name");
}
}
Controller:
#Controller
public class UserController {
#Autowired
UserValidator userValidator;
#InitBinder
public void initBinder(WebDataBinder binder) {
CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true, 10);
binder.registerCustomEditor(Date.class, editor);
binder.setValidator(userValidator);
// binder.addValidators(userValidator);
}
final static Logger logger = Logger.getLogger(UserController.class);
#Autowired
protected ServiceUserImpl service;
#RequestMapping("/lista")
public String showIndex(Model model) {
User contest = new User();
model.addAttribute("element", contest);
model.addAttribute("collection", service.findAll());
return "lista";
}
#RequestMapping("/dodaj")
public String showFormPublication(HttpServletRequest request, #ModelAttribute("userDto") #Valid UserDTO userDTO, BindingResult result) {
if (request.getMethod().equalsIgnoreCase("post") && !result.hasErrors()) {
if (result.hasErrors()) {
return "forms/contest";
} else {
User user = new User();
user.setId(userDTO.getId());
user.setName(userDTO.getName());
user.setSurname(userDTO.getSurname());
user.setDateOfBirth(userDTO.getDateOfBirth());
user.setIndexNumber(userDTO.getIndexNumber());
user.setEmail(userDTO.getEmail());
service.save(user);
return "redirect:/lista";
}
}
return "dodaj";
}
}
Form in .jsp:
<form:form action="dodaj" method="POST" modelAttribute="userDto">
<table border="1">
<tbody>
<tr>
<th>ImiÄ™</th>
<td>
<form:input type="text" path="name" />
<c:if test="${pageContext.request.method=='POST'}"><form:errors path="name" /></c:if>
</td>
</tr>
<tr>
<th>Nazwisko</th>
<td>
<form:input type="text" path="surname" />
<c:if test="${pageContext.request.method=='POST'}"><form:errors path="surname" /></c:if>
</td>
</tr>
<tr>
<th>DataUrodzenia</th>
<td>
<form:input type="date" path="dateOfBirth" />
<c:if test="${pageContext.request.method=='POST'}"><form:errors path="dateOfBirth" /></c:if>
</td>
</tr>
<tr>
<th>NumerIndeksu</th>
<td>
<form:input type="number" path="indexNumber" />
<c:if test="${pageContext.request.method=='POST'}"><form:errors path="indexNumber" /></c:if>
</td>
</tr>
<tr>
<th>Email</th>
<td>
<form:input type="text" path="email" />
<c:if test="${pageContext.request.method=='POST'}"><form:errors path="email" /></c:if>
</td>
</tr>
<tr>
<td colspan="2" align="right"><input type="submit" value="Dodaj!" /></td>
</tr>
</tbody>
</table>
</form:form>
I tried adding ("userDto") next to #InitBinder, it didn't help unfortunately. Haven't found much more in terms of applicable solutions. If there's anything else I should post here let me know. I can also provide a link to repository should anyone be eager enough to try to run it.
I think you need to change the supports method in UserValidator to UserDTO class:
public boolean supports(Class<?> clazz) {
return UserDTO.class.equals(clazz);
}

Neither BindingResult nor plain target object for bean name 'index' available as request attribute

I have a problem when trying to access the controller.
Here is my controller:
#Controller
#RequestMapping("/index.htm")
public class LoginController {
#Autowired
private UserService userService;
#RequestMapping(method = RequestMethod.GET)
public String showForm(Map model) {
model.put("index", new LoginForm());
return "index";
}
#RequestMapping(method = RequestMethod.POST)
public String processForm(LoginForm loginForm, BindingResult result,
Map model) {
if (result.hasErrors()) {
HashMap<String, String> errors = new HashMap<String, String>();
for (FieldError error : result.getFieldErrors()) {
errors.put(error.getField(), error.getDefaultMessage());
}
model.put("errors", errors);
return "index";
}
List<User> users = userService.getUsers();
loginForm = (LoginForm) model.get("loginForm");
for (User user : users) {
if (!loginForm.getEmail().equals(user.getEmail()) || !loginForm.getPassword().equals(user.getPassword())) {
return "index";
}
}
model.put("index", loginForm);
return "loginsuccess";
}
}
Here is my form:
<form:form action="index.htm" commandName="index">
<table border="0" cellspacing="12">
<tr>
<td>
<spring:message code="application.loginForm.email"/>
</td>
<td>
<form:input path="email"/>
</td>
<td class="error">
<form:errors path="email"/>
</td>
</tr>
<tr>
<td>
<spring:message code="application.loginForm.password"/>
</td>
<td>
<form:password path="password"/>
</td>
<td class="error">
<form:errors path="password"/>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
On form submit I am getting this exception:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'index' available as request attribute.
What am I doing wrong here?
It's because you're only doing this bit down at the bottom
model.put("index", loginForm);
If you return from the validation error, or from a success, there is no backing object in the model map named "index" so your form tag that has commandName="index" pitches a fit.
A common solution is to simply do this
#ModelAttribute("index")
public LoginForm getLoginForm() {
return new LoginForm();
}
Then there will always be one present, and you can take adding it out of the GET method.

Spring SimpleFormController - Including Search Form In Success View

UPDATE 1/31/10: Since this thread continues to get a lot of views...I am curious if it has been of help to anyone recently? Feel free to leave comments/feedback, thanks.
I have a Spring form where I would like to reuse the search page to include the results under the search form. Currently when I do this I get the following error on loading the success view:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'searchAccounts' available as request attribute
Here is my bean configuration:
<bean name="/search.html" class="myapp.web.AccountSearchController">
<property name="sessionForm" value="true"/>
<property name="commandName" value="searchAccounts"/>
<property name="commandClass" value="myapp.service.AccountSearch"/>
<property name="validator">
<bean class="myapp.service.AccountSearchValidator"/>
</property>
<property name="formView" value="accountSearch"/>
<property name="successView" value="accountSearchResults"/>
</bean>
Here is the snippet of JSP that includes the search form:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<form:form method="post" commandName="searchAccounts">
<table valign="top" cellspacing="0" cellpadding="0" width="500" border="0">
<tr>
<td valign="top">
<div class="border-title">Account Search</div>
<div id="navhome">
<div class="border">
<div id="sidebarhome">
<table id="form">
<tr>
<td colspan="2">Search by Account ID or Domain Name. If
values are provided for both, only accounts matching both values
will be returned.</td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td align="right" valign="top"><form:label path="accountId">Account ID</form:label>:</td>
<td><form:input path="accountId" size="30"/></td>
</tr>
<c:set var="accountIdErrors"><form:errors path="accountId"/></c:set>
<c:if test="${not empty accountIdErrors}">
<tr>
<td> </td>
<td>${accountIdErrors}</td>
</tr>
</c:if>
<tr>
<td align="right" valign="top"><form:label path="domainName">Domain Name</form:label>:</td>
<td><form:input path="domainName" size="30"/></td>
</tr>
<c:set var="domainNameErrors"><form:errors path="domainName"/></c:set>
<c:if test="${not empty domainNameErrors}">
<tr>
<td> </td>
<td>${domainNameErrors}</td>
</tr>
</c:if>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Search">
</td>
</tr>
</table>
</div>
</div>
</div>
</td>
</tr>
</table>
</form:form>
And...here is my form controller class (less the imports):
public class AccountSearchController extends SimpleFormController {
protected final Log logger = LogFactory.getLog(getClass());
public ModelAndView onSubmit(Object command, BindException errors) throws ServletException {
String accountId = ((AccountSearch) command).getAccountId();
String domainName = ((AccountSearch) command).getDomainName();
logger.info("User provided search criteria...\n\tDomain Name: " + domainName + "\n\tAccountId: " + accountId);
//TODO do search
logger.info("returning from AccountSearch form view to " + getSuccessView());
return new ModelAndView(getSuccessView());
}
protected Object formBackingObject(HttpServletRequest request) throws ServletException {
AccountSearch accountSearch = new AccountSearch();
return accountSearch;
}
}
Thanks in advance for your help!
-aj
UPDATE:
I ported this to an annotated controller per answer below. Here is the new/working code:
#Controller
#RequestMapping("/search.html")
public class AccountSearchController {
// note: this method does not have to be called setupForm
#RequestMapping(method = RequestMethod.GET)
public String setupForm(Model model) {
AccountSearchCriteria accountSearchCriteria = new AccountSearchCriteria();
model.addAttribute("accountSearchCriteria", accountSearchCriteria);
model.addAttribute("title", "Account Search");
return "accountSearch";
}
// note: this method does not have to be called onSubmit
#RequestMapping(method = RequestMethod.POST)
public String onSubmit(#ModelAttribute("accountSearchCriteria") AccountSearchCriteria accountSearchCriteria, BindingResult result, SessionStatus status, Model model) {
new AccountSearchValidator().validate(accountSearchCriteria, result);
if (result.hasErrors()) {
return "accountSearch";
} else {
ArrayList<AccountSearchCriteria> accountSearchResults = new ArrayList<AccountSearchCriteria>();
AccountSearchCriteria rec = new AccountSearchCriteria();
rec.setDomainName("ajcoon.com");
accountSearchResults.add(rec);
AccountSearchCriteria rec2 = new AccountSearchCriteria();
rec2.setDomainName("ajcoon2.com");
accountSearchResults.add(rec2);
//TODO do search
//ArrayList<HashMap<String,String>> accountSearchResults = new AccountSearchService().search(accountId,domainName);
if( accountSearchResults.size() < 1 ){
result.rejectValue("domainName", "error.accountSearch.noMatchesFound", "No matching records were found.");
return "accountSearch";
} else if(accountSearchResults.size() > 1){
model.addAttribute("accountSearchResults", accountSearchResults);
return "accountSearch";
} else {
status.setComplete();
return "redirect:viewAccount?accountId=";
//return "redirect:viewAccount?accountId=" + accountSearchResults.get(0).getAccountId();
}
}
}
}
try to use (throws Exception instead of ..)
protected Object formBackingObject(HttpServletRequest request)
throws Exception {
AccountSearch accountSearch = new AccountSearch();
System.out.println("inside formBackingObject");
return accountSearch;
}
It looks like your formBackingObject Method is not executed. rerun the code with the above change and see log console to see if the method is executed.
--
You should be using annotation instead of extending controller. Spring 3.0 will deprecate the controller hierarchy.

Categories