I have a spring project and my problem is that my model objects becomes null on jsp when I debug it in the controller it shows data but on jsp nothing is displayed and there are no errors in the log.
I have added spring tiles config recently and tiles are working fine but these objects stopped getting displayed earlier it was working fine.
I have searched a lot on this and checked same links like Spring Model Object is not rendering on stackoverflow but nothing worked.
Here is my controller:
#RequestMapping(value = "/viewClient", method = RequestMethod.GET)
public String viewClient(ModelAndView model) {
ArrayList<SystemUser> systemUsers = clientController.getAllUsers();
model = new ModelAndView("systemUsers");
model.addObject("systemUsers", systemUsers);
return "viewClient";
}
spring-config.xml
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView" />
<property name="order">
<value>0</value>
</property>
</bean>
<bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer" id="tilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
tiles.xml
<tiles-definitions>
<definition name="base.definition" template="/WEB-INF/pages/Theme/Template/mainTemplate.jsp">
<put-attribute name="title" value=""></put-attribute>
<put-attribute name="header" value="/WEB-INF/pages/Theme/Template/header.jsp"></put-attribute>
<put-attribute name="menu" value="/WEB-INF/pages/Theme/Template/menu.jsp"></put-attribute>
<put-attribute name="body" value=""></put-attribute>
<!-- <put-attribute name="footer" value="/WEB-INF/pages/Theme/Template/footer.jsp"></put-attribute> -->
</definition>
<definition name="base.definition.login" template="/WEB-INF/pages/Theme/Template/loginTemplate.jsp">
<put-attribute name="title" value=""></put-attribute>
<put-attribute name="body" value=""></put-attribute>
</definition>
<definition extends="base.definition" name="viewClient">
<put-attribute name="title" value="View Client"></put-attribute>
<put-attribute name="body" value="/WEB-INF/pages/Theme/Admin/viewClient.jsp"></put-attribute>
</definition>
<tiles-definitions>
viewClient.jsp:
<table class="table table-striped table-advance table-hover">
<h4>
<!-- <i class="fa fa-angle-right"></i> --> Client Details
</h4>
<thead>
<tr>
<th><i class="fa fa-bullhorn"></i> index --${systemUsers.size()}--size </th>
<th><i class="fa fa-bullhorn"></i> Username</th>
<th><i class="fa fa-bullhorn"></i> Password</th>
<th><i class="fa fa-bullhorn"></i> User role</th>
<th><i class="fa fa-bullhorn"></i> Mobile No</th>
<th><i class="fa fa-bullhorn"></i> Email ID</th>
<th><i class="fa fa-bullhorn"></i> SMSC</th>
<th><i class="fa fa-bullhorn"></i> Virtual Sim ID</th>
<th></th>
</tr>
</thead>
<tbody>
<c:set var="count" value="0" scope="page" />
<c:forEach var="user" items="${systemUsers}">
<tr>
<td>${count + 1}</td>
<td>${ user.getUsername()}</td>
<td>${ user.getPassword()}</td>
<td>${user.getUserrole()}</td>
<td>${user.getMobileNumber()}</td>
<td>${user.getPrimaryEmailAddress()}</td>
<td>${user.getSmsc()}</td>
<td>${user.getVirtualSimID()}</td>
<td>
<button class="btn btn-success btn-xs">
<i class="fa fa-check"></i>
</button>
<button class="btn btn-primary btn-xs">
<i class="fa fa-pencil"></i>
</button>
<button class="btn btn-danger btn-xs">
<i class="fa fa-trash-o "></i>
</button>
</td>
</tr>
<c:set var="count" value="${count + 1}" scope="page" />
</c:forEach>
</tbody>
</table>
In the jsp the systemUsers are not getting iterated nor displayed not its size is getting displayed..
Make it correct and change return type to ModelAndView
#RequestMapping(value = "/viewClient", method = RequestMethod.GET)
public ModelAndView viewClient() {
ArrayList<SystemUser> systemUsers = clientController.getAllUsers();
ModelAndView model = new ModelAndView("viewClient");
model.addObject("systemUsers", systemUsers);
return model ;
}
OR use
#RequestMapping(value = "/viewClient", method = RequestMethod.GET)
public String viewClient(ModelMap model) {
ArrayList<SystemUser> systemUsers = clientController.getAllUsers();
model.addAttribute("systemUsers", systemUsers);
return "viewClient";
}
Look at ModelAndView that accepts view name.
You can also try this interface Model for this issue:
#RequestMapping(value = "/viewClient", method = RequestMethod.GET)
public String viewClient(Model model) {
ArrayList<SystemUser> systemUsers = clientController.getAllUsers();
model.addAttribute("systemUsers", systemUsers);
return "viewClient";
}
Make sure that in your pom.xml the following dependency exist:
<properties>
<spring.version>4.0.2.RELEASE</spring.version>
</properties>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
Do not reinitialize ModelAndView Object
#RequestMapping(value = "/viewClient", method = RequestMethod.GET)
public String viewClient(ModelAndView model) {
ArrayList<SystemUser> systemUsers = clientController.getAllUsers();
model.addObject("systemUsers", systemUsers);
return "viewClient";
}
Related
I have two Models-
Customer and Address
I passed both of the objects to the getMethod-
#RestController
public class NewCustomerController {
#Autowired
NewCustomerService newCustomerService;
#GetMapping(value = "newCustomer")
public ModelAndView newCustomer(){
ModelAndView modelAndView=new ModelAndView("views/customer/newCustomer");
modelAndView.addObject("customer",new Customer());
modelAndView.addObject("address",new Address());
return modelAndView;
}
After submitting a form i want to store these objects into my db-
My JSP Page-
<body class="container-fluid">
<jsp:include page="/navbar.jsp" />
<article>
<form action="newCustomer" method="post">
<spring:bind path="customer.customerCode">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="customer.firstName">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="customer.lastName">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="customer.dateOfBirth">
<input type="date" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="customer.nationality">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="customer.occupationType">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="customer.totalWorkExperience">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="customer.organizationName">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<h2>ADDRESS</h2>
<spring:bind path="address.addressId">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="address.houseNo">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="address.city">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="address.state">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="address.country">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="address.pincode">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<input type="submit" value="Create"/>
</form>
</article>
</body>
Here is a post method i want to call on clicking the create button-
continue after get method...
#PostMapping(value = "newCustomer")
public ModelAndView addCustomer(#ModelAttribute("customer") Customer customer, BindingResult resultCustomer,#ModelAttribute("address") Address address,BindingResult resultAddress){
newCustomerService.createNewCustomer(customer);
newCustomerService.createNewAddress(address);
ModelAndView modelAndView=new ModelAndView("views/loanapplication/loanApplication");
return modelAndView;
}
}
After clicking on create button-
I am getting this error-
Request method 'POST' not supported
For reference i am showing the urls after before clicking create button-
before click-
http://127.0.0.1:8080/Project/newCustomer
After click-
http://127.0.0.1:8080/Project/newCustomer
Are you using spring security? Check the csrf setting of spring security.
By default, csrf defense is enabled to enable spring security. At this point, the solution is the same.
You can send csrf token value in form.
<input type = "hidden" name = "$ {_ csrf.parameterName}" value = "$ {_ csrf.token}"/>
If you want to ignore csrf, you can set a class that inherits
WebSecurityConfigurerAdapter class to ignore certain URLs
#EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {
#Value("${security.enable-csrf}")
private boolean csrfEnabled;
#Override
protected void configure(HttpSecurity http) throws Exception {
if (!csrfEnabled) {
http.csrf().disable();
}
}
}
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>
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;
}
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.
I need help. I am working on a project where I have multiple pages and multiple forms; each page has one form. I just need to be able to pass values from one jsp to another. What should I do?
I am new to Spring MVC. I am using spring 2.5.6.
Here's my design:
formPage1.jsp --> Controller1 --> formPage2a.jsp --> Controller2 needs val frm pg1 & pg2a.
formPage1.jsp --> Controller1 --> formPage2b.jsp --> Controller3 needs val frm pg1 & pg2b.
formPage1.jsp --> Controller1 --> formPage2c.jsp --> Controller4 needs val frm pg1 & pg2c.
As you can see above, formPage1.jsp can load either formPage2a, formPage2b or formPage2c. Based on the input provided in formPage1.jsp, it goes to the controller (which is an extension of SimpleFormController) and controller get the values entered by user = command object.
I want to be able to use these command object values in either formPage2a, formPage2b or formPage2c when they are submitted to another controller.
here's the current code:
formPage1.jsp:
<form:form method="post" commandName="gainLossRequest">
<form:errors path="*" cssClass="error"/>
<table>
<tr>
<td>
<table>
<tr>
<td><h4>Choose Client</h4></td>
<td style="font-size: medium; font-family: Arial, bold; color: red">*</td>
</tr>
</table>
</td>
<td>
<form:select path="client">
<form:option value="none" label="Select" />
<form:option value="abc" label="abc" />
<form:option value="def" label="def" />
<form:option value="xyz" label="xyz" />
</form:select>
</td>
</tr>
<tr>
<td colspan="2">
<input type="reset" value="Reset" />
<input type="submit" value="Next" />
</td>
</tr>
</table>
</form:form>
Controller1.java
public class TestController extends SimpleFormController {
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
public TestController() {
logger.info("entering TestController.constructor..");
setCommandClass(UserPreference.class);
setCommandName("userPreference");
}
public ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws ServletException {
logger.info("entering TestController.onSubmit all..");
UserPreference userPreference = (UserPreference) command;
ModelAndView view = null;
if ("abc".equals(userPreference.getClient())) {
GainLossRequest gainLossRequest = new GainLossRequest(userPreference);
view = new ModelAndView("redirect:/test/gainLossRequest.htm",
"gainLossRequest", gainLossRequest);
} else if ("def".equals(userPreference.getClient())) {
IncomingPositionsRequest incomingPositionsRequest = new IncomingPositionsRequest();
view = new ModelAndView(
"redirect:/test/incomingPositionsRequest.htm",
"incomingPositionsRequest", incomingPositionsRequest);
} else if ("xyz".equals(userPreference
.getClient())) {
TaxStrategyRequest taxStrategyRequest = new TaxStrategyRequest();
view = new ModelAndView("redirect:/test/taxStrategyRequest.htm",
"taxStrategyRequest", taxStrategyRequest);
}
}
}
formPage2a.jsp
<form:form method="post" commandName="gainLossRequest">
<form:errors path="*" cssClass="error"/>
<table style="width: 60%">
<tr>
<td>Account Number (s):</td>
<td style="font-size: medium; font-family: Arial, bold; color: red">*</td>
</tr>
<tr>
<td>
User Chosen Client:
</td>
<td>
<c:out value="${gainLossRequest.client}"/>
</td>
</tr>
<tr colspan="2">
<td>
<input type="reset" value="Reset" />
<input type="submit" value="Submit" />
</td>
</tr>
dispatcher servlet config
<!-- setupNew.jsp is the first jsp -->
<bean name="/test/setupNew.htm" class="chimeraweb.web.TestController">
<property name="sessionForm" value="true"/>
<property name="commandName" value="userPreference"/>
<property name="commandClass" value="chimeraweb.service.UserPreference"/>
<property name="validator">
<bean class="chimeraweb.service.UserPreferenceValidator"/>
</property>
<property name="formView" value="/test/setupNew"/>
</bean>
<!-- gainLossRequest.jsp is the 2nd jsp where I want to display the values captured in the first jsp page -->
<bean name="/test/gainLossRequest.htm" class="chimeraweb.web.SimpleGainLossController">
<property name="sessionForm" value="true"/>
<property name="commandName" value="gainLossRequest"/>
<property name="commandClass" value="chimeraweb.service.GainLossRequest"/>
<property name="validator">
<bean class="chimeraweb.service.GainLossValidator"/>
</property>
<property name="formView" value="/test/gainLossRequest"/>
</bean>
Please help!!
You could also use session attributes, either manually, such as:
public ModelAndView handleRequest(HttpServletRequest request){
request.getSession().getAttribute("nameOfAttribute");
}
Apologies for writing this as an annotated controller, I do not recall if xml config controllers offer this feature...
There is no Spring code involved for that. The other option is to use the #SessionAttribute annotation on your controller:
#Controller
#SessionAttributes("nameOfAttribute")
public class MyController{
//your session attribute can be accessed in controller methods using #ModelAttribute
public ModelAndView handleRequest(#ModelAttribute("nameOfAttribute")){
session.getAttribute("nameOfAttribute");
}
Note
You will need to clear the session attribute when you are done with it:
request.getSession().setAttribute("nameOfAttribute", null);
You have to persist the user entered information on the first page either using a hidden variable as mentioned above by JB Nizet. Or you can set the value in the model attribute that will be returned on your corresponding controllers.
The pseudo code for you.
formPage1.jsp --> Controller1 --> set the values in this form by retrieving it from the Request object --> formPage2a.jsp --> Controller2 will have val frm both pg1 & pg2a.
In this way there is no need to maintain a session attribute.
The simplest way is to use hidden fields in the second page(s) to store what the user has enetered in the first form. This way, all the fields, inclusing those from the first page, will be submitted with the second form(s).