Same URL on request forward from servlet hence operation repeated again - java

I have been trying to make my project more structured hence i have been following the example in netbeans ecommerce sample project in https://netbeans.org/kb/docs/javaee/ecommerce/page-views-controller.html#controller. I changed my controller according to the example. Now I'm having trouble with going to the page where I display the values in the database.
My Servlet is given below.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
Op_Stock ops = new Op_Stock();
String userPath = request.getServletPath();
String param = null;
Map<String, String> prdMap = new LinkedHashMap<String, String>();
Map<String, String> lvlMap = new LinkedHashMap<String, String>();
ArrayList<HashMap<String, String>> stkList = new ArrayList<>();
switch (userPath) {
case "/ViewStock":
stkList = ops.getAllStockDetails();
request.setAttribute("stkList", stkList);
userPath = "Stock.jsp";
param = "type=m&page=stk";
break;
case "/AddStockForm":
prdMap = ops.getAllProducts();
lvlMap = ops.getAllLevels();
request.setAttribute("prdMap", prdMap);
request.setAttribute("lvlMap", lvlMap);
userPath = "Insertstk.jsp";
param = "type=m&page=stk";
break;
case "/AddStock":
System.out.println("prdId: " + request.getParameter("prdId"));
int iprdId = Integer.parseInt(request.getParameter("prdId"));
int istkIn = Integer.parseInt(request.getParameter("stkIn"));
int istkthld = Integer.parseInt(request.getParameter("stkthld"));
int ilvlId = Integer.parseInt(request.getParameter("lvlId"));
int stkIn = ops.insertStockDetails(iprdId, istkIn, istkthld, ilvlId);
stkList = ops.getAllStockDetails();
request.setAttribute("stkList", stkList);
if (stkIn > 0) {
userPath = "/Stock.jsp";
param = "message=Stock Details Created!&pg=stk&type=m";
} else {
prdMap = ops.getAllProducts();
lvlMap = ops.getAllLevels();
request.setAttribute("prdMap", prdMap);
request.setAttribute("lvlMap", lvlMap);
userPath = "/Insertstk.jsp";
param = "message=Could not create!&pg=stk&type=m";
}
break;
case "/DeleteStock":
int delStk = ops.deleteStockDetails(request.getParameter("stkId"));
if (delStk > 0) {
userPath = "Stock.jsp";
param = "message=Stock Details Deleted!&pg=stk&type=m";
stkList = ops.getAllStockDetails();
request.setAttribute("stkList", stkList);
} else {
userPath = "Stock.jsp";
stkList = ops.getAllStockDetails();
request.setAttribute("stkList", stkList);
param = "message=Could not delete!&pg=stk&type=m";
}
break;
}
// use RequestDispatcher to forward request internally
String url = userPath + "?" + param;
request.getRequestDispatcher(url).forward(request, response);
//response.sendRedirect(url);
}
In the servlet I'm setting attribute to the request in which the database contents are stored.
Suppose I'm doing an insert operation which is in the switch case "/AddStock" After doing this the request is forwarded to my page where the table is displayed, since i'm using forward it will go to the display page but the URL in the address bar will stay the same with all request parameters from my insert form, hence when I refresh the page the insertion operation will happen again. If I use response.sendRedirect(url), I wont be able to use the request attributes and hence wont't be able to display the DB values.
My Insert form is given below.
<div class="col-md-10">
<form method="POST" action="AddStock" class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label">Product</label>
<div class="col-sm-4">
<select id="s_prdname" class="form-control" name="prdId" required>
<option>Select</option>
<c:forEach items="${prdList}" var="mapItem">
<option value="${mapItem.key}">${mapItem.value}</option>
</c:forEach>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Level</label>
<div class="col-sm-4">
<select id="s_lvlname" class="form-control" name="lvlId" required>
<option>Select</option>
<c:forEach items="${lvlList}" var="mapItem">
<option value="${mapItem.key}">${mapItem.value}</option>
</c:forEach>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">In-Stock</label>
<div class="col-sm-2">
<input type="number" name="stkIn" class="form-control" id="stkIn"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Threshold</label>
<div class="col-sm-2">
<input type="number" name="stkthld" class="form-control" id="stkthld"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default btn-primary"><strong>Submit</strong></button>
</div>
</div>
</form>
</div>
My Display page is given below.
<div class="table-responsive">
<table class="table table-bordered table-striped table-hover">
<thead>
<th><strong>Product Name</strong></th>
<th><strong>Level</strong></th>
<th><strong>In Stock</strong></th>
<th><strong>Threshold</strong></th>
<th><strong>Expiry</strong></th>
<th><strong>Operations</strong></th>
</thead>
<tbody>
<jsp:useBean id="lvl" scope="request" class="Level.Level"/>
<jsp:useBean id="prd" scope="request" class="Product.Product"/>
<c:forEach items="${stkList}" var="row">
<tr>
<td><jsp:setProperty name="prd" property="prdId" value="${row.prdStk}"/><jsp:getProperty name="prd" property="prdName"/></td>
<td><jsp:setProperty name="lvl" property="lvlId" value="${row.lvlStk}"/><jsp:getProperty name="lvl" property="lvlName"/></td>
<td>${row.inStk}</td>
<td>${row.thldStk}</td>
<td>${row.expStk}</td>
<td>
<button type="button" class="btn btn-default btn-sm btn-danger" onclick="deletedata('${row.idStk}');">
<span class="glyphicon glyphicon-trash"></span>
</button>
<button class="btn btn-info btn-sm" data-toggle="modal" data-target="#myModal">
<span class="glyphicon glyphicon-eye-open"></span>
</button>
</td>
</tr>
</c:forEach>
</tbody>
<tfoot>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tfoot>
</table>
</div>
Please help me to solve this problem, if the method I used is wrong please suggest the right one.

To solve this problem I used.
response.sendRedirect(url);
Instead of
request.getRequestDispatcher(url).forward(request, response);
And Instead of displaying the values in the DB by setting an attribute in request, I have used to access the method in my class as shown below.
<jsp:useBean id="stk" scope="request" class="Stock.Op_Stock"/>
<c:forEach items="${stk.allStockDetails}" var="row">
// Values in the map displayed here
</c:forEach>

Related

Spring boot + Thymeleaf - Object with id null when editing

When you select an Expense object from the data table for editing, the edit method in the controller sends the Expense object to the edit screen that is the same to insert a new record. When the object is sent to the save method, it has nullo code attribute where an insert occurs instead of an update. I do not understand why.
Controller
#Controller
#RequestMapping("/despesas")
public class DespesaController {
#Autowired private DespesaService despesaService;
#Autowired private DespesaRepository despesaRepository;
#GetMapping("/add")
public ModelAndView novo(Despesa despesa) {
ModelAndView model = new ModelAndView("page/cadastro/despesa/cadDespesa");
model.addObject("tiposDespesa", TipoDespesa.values());
model.addObject("formasPagamento", FormaPagamento.values());
model.addObject(despesa);
return model;
}
#PostMapping("/save")
public ModelAndView salvar(Despesa despesa, BindingResult result, RedirectAttributes attributes) {
if (result.hasErrors()) {
return novo(despesa);
}
despesa.setDataDespesa(new Date());
despesaService.salvarDespesa(despesa);
attributes.addFlashAttribute("mensagem", "Despesa Salva com Sucesso!");
return new ModelAndView("redirect:/cadastroDespesa");
}
#GetMapping("/listDespesa")
public ModelAndView listagemDeDespesas() {
ModelAndView model = new ModelAndView("page/cadastro/despesa/listDespesa");
model.addObject("despesas", despesaRepository.findAll());
return model;
}
#GetMapping("/edit{id}")
public ModelAndView editar(#PathVariable("id") Long codigo) {
return novo(despesaRepository.findOne(codigo));
}
}
FormEdit
<form th:object="${despesa}" method="POST" th:action="#{/despesas/save}">
<div class="box-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Data</label>
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" th:field="*{dataDespesa}" class="form-control" disabled="disabled">
</div>
</div>
<div class="form-group">
<label>Valor</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-dollar"></i></span>
<input type="text" th:field="*{valor}" class="form-control">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Tipo Despesa</label>
<select class="form-control select2" th:field="*{tipoDespesa}" style="width: 100%;">
<option th:each="tipo : ${tiposDespesa}" th:value="${tipo}" th:text="${tipo}"></option>
</select>
</div>
<div class="form-group">
<label>Forma Pagamento</label>
<select class="form-control select2" th:field="*{formaPagamento}" style="width: 100%;">
<option th:each="forma : ${formasPagamento}" th:value="${forma}" th:text="${forma}"></option>
</select>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Observação</label>
<input type="text" th:field="*{observacao}" class="form-control">
</div>
</div>
</div>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Salvar</button>
<a class="btn btn-default" th:href="#{/}">Cancelar</a>
</div>
</form>
Data Table Where I select the object for editing
<table id="example2" class="table table-bordered table-hover">
<thead>
<tr>
<th>Data</th>
<th>Valor</th>
<th>Tipo Despesa</th>
<th>Forma Pagamento</th>
</tr>
</thead>
<tbody>
<tr th:each="obj : ${despesas}">
<td data-title="Data" th:text="${#calendars.format(obj.dataDespesa, 'dd/MM/yyyy HH:mm:ss')}"></td>
<td data-title="Valor" th:text="${#numbers.formatCurrency(obj.valor)}"></td>
<td data-title="Tipo Despesa" th:text="${obj.tipoDespesa}"></td>
<td data-title="Forma Pagamento" th:text="${obj.formaPagamento}"></td>
<td><a th:href="#{/despesas/edit{id} (id=${obj.codigoDespesa})}"><i class="glyphicon glyphicon-pencil"></i></a></td>
</tr>
</tbody>
</table>
As sr.praneeth said you need to add the fields you want to populate into the form, usually the ID are not visible but you need to send them.
<form th:object="${despesa}" method="POST" th:action="#{/despesas/save}">
<div class="box-body">
<input type="hidden" th:field="*{id}"/>
...
</form>
Then in your Controller you will be able to retrieve the id value, null if its a creation, or informed if its an update

How to hold filter parameters. Pagination

I have some problem with search filter and pagination. Filter works good, but i can't say the same about pagination.
I have a table with users. I can show all users or by filter(by name, by email). When i'm using filter and trying to go to second page, it return all users without filtration. I understand why it happens, because has no filter parameters. Help me find solution. How can i hold selected filters? Something with sessions?
Here my code.
My Controller
#Controller
#RequestMapping(value = "/admin")
public class AdminController {
#Autowired
UserService userService;
#RequestMapping(value = "/edit-user", method = RequestMethod.GET)
public ModelAndView editUsers(#RequestParam(value = "page", defaultValue = "0") Integer page,
#RequestParam(value = "pattern", required = false) String pattern,
#RequestParam(value = "category", required = false) String category) {
ModelAndView view = new ModelAndView("edit-user");
if(pattern == null){
Page<User> userList = userService.findAll(page);
view.addObject("userList", userList.getContent()).addObject("maxPage", userList.getTotalPages());
}else if(category.equals("username")){
Page<User> userList = userService.findByUsernameContaining(pattern, page);
view.addObject("userList", userList.getContent()).addObject("maxPage", userList.getTotalPages());
}else {
Page<User> userList = userService.findByEmailContaining(pattern, page);
view.addObject("userList", userList.getContent()).addObject("maxPage", userList.getTotalPages());
}
return view;
}
}
My part of JSP
<div class="row top-buffer">
<div class="col-md-4 col-md-offset-4">
<form class="form-inline text-center" role="form" method="get" action="/admin/edit-user?pattern=pattern?category=category">
<fieldset>
<!-- Search Name -->
<div class="form-group">
<label class="sr-only" for="item-name">Product Name</label>
<input id="item-name" name="pattern" placeholder="..." class="form-control">
</div>
<!-- Search Category -->
<div class="form-group">
<label class="sr-only" for="item-category">Product Category</label>
<select id="item-category" name="category" class="form-control">
<option value="username" selected>By username</option>
<option value="email">By email</option>
</select>
</div>
<!-- Search Action -->
<div class="form-group">
<button type="submit" class="btn btn-primary"><span
class="glyphicon glyphicon-search" aria-hidden="true"></span></button>
</div>
</fieldset>
</form>
</div>
</div>
<div class="row top-buffer">
<div class="col-md-8 col-md-offset-2">
<table class="table">
<thead>
<th>Id</th>
<th>Username</th>
<th>Email</th>
<th>Password</th>
</thead>
<c:forEach var="user" items="${userList}">
<tr>
<td>${user.id}</td>
<td>${user.username}</td>
<td>${user.email}</td>
<td>${user.password}</td>
<td>
<button type="button" class="btn btn-info btn-sm editButton" data-toggle="modal"
data-target="#myModal" data-id="${user.id}">Edit
</button>
</td>
</tr>
</c:forEach>
</table>
</div>
</div>
<div class="row">
<div class="col-md-4 pull-right">
<ul class="pagination">
<c:forEach begin="0" end="${maxPage - 1}" var="i">
<li>${i+1}</li>
</c:forEach>
</ul>
</div>
</div>
In your case, putting filter information in session should be OK. You can create a Filter enum that has e.g. name, email fields. Store/update a Filter instance in session every time user wants to filter something.
You can attach your filters to your link(page number in your case) as a query string like so:
${i+1}
In your controller, you need to get the filter information and handle it accordingly (get the value of param filterby, which is name or email). If the filterby param has no value, then no filter is chosen.

Get id value from list jsp

I have view on my jsp like this:
<form:form name = "command"
method = "post"
action = "withdrawRequest"
class = "form-horizontal group-border-dashed"
style = "border-radius: 0px;">
<table class = "table table-bordered"
id = "datatable-icons" > <!-- start table table-bordered -->
<thead>
<tr>
<th>ID</th>
<th>NO</th>
<th>AMOUNT (RP)</th>
<th>DOCTOR BALANCE (RP)</th>
<th>DOCTOR ID</th>
<th>DOCTOR NAME</th>
<th>TRANSFER ADMIN NAME</th>
<th>TRANSFER DATE</th>
<th>TRANSFER REFERENCE</th>
<th>TRANSFERRED</th>
</tr>
</thead>
<tbody>
<c:forEach var = "withdrawal"
items = "${listWithdrawals}"
varStatus = "loopStatus">
<tr class="odd gradeX">
<td>${withdrawal.id}</td>
<td>${loopStatus.index + 1}</td>
<td class="text-right"><fmt:formatNumber type="number" maxFractionDigits="2" value="${withdrawal.amount}" /></td>
<td class="text-right"><fmt:formatNumber type="number" maxFractionDigits="2" value="${withdrawal.doctor_balance}" /></td>
<td>${withdrawal.doctor_id}</td>
<td>${withdrawal.doctor_name}</td>
<td>${withdrawal.transfer_admin_name}</td>
<td><%-- <fmt:formatDate type="date" value="${withdrawal.transfer_date}" /> --%>${withdrawal.transfer_date}</td>
<td>${withdrawal.transfer_reference}</td>
<td class="text-center">
<c:if test="${withdrawal.transferred == true}">
<span class="label label-success">Transferred</span>
</c:if>
<c:if test="${withdrawal.transferred == false}">
<button class="btn btn-warning btn-sm md-trigger" data-modal="form-primary" type="button">Pending</button>
</c:if>
<div class="md-modal colored-header danger custom-width md-effect-9" id="form-primary">
<div class="md-content">
<div class="modal-header">
<h3>Confirm Withdrawal Request</h3>
<button type="button" class="close md-close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body form">
<div class="form-group">
<label class="col-sm-3 control-label">Admin Name</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="adminName" value="${adminName}">
<input type="text" class="form-control" name="id" value="${withdrawal.id}" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Transfer Reference</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="transferReference" value="${transferReference}">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default btn-flat md-close" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-danger btn-flat md-close" name="submitRequest">Submit</button>
</div>
</div>
</div>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</form:form>
I cannot get the ID of which button I selected from view,
<input type = "text"
class = "form-control"
name = "id"
value = "${withdrawal.id}" />
If I use this code
String withdrawalId = request.getParameter("id");
The value is always 120.
For example:
How do I get the correct ID when I click the modal window?
It seems that the problem is in Nifty Modal Window Effects you are using for popup. It opens modal window for the last row.
It can be fixed with following jsp modifications.
Move modal window declaration out of table. Make it single for page. And rename id field to make it unique, e.g. transferredId
Add onclick to buttons opening modal window in order to init it (set transferredId and others) with necessary values
So your form would be (just ending to save space)
....
<td class="text-center">
....
<c:if test="${withdrawal.transferred == false}">
<button class="btn btn-warning btn-sm md-trigger" data-modal="form-primary" type="button"
onclick="document.getElementById('transferredId').value=${withdrawal.id}">
Pending
</button>
</c:if>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<div class="md-modal colored-header danger custom-width md-effect-9" id="form-primary">
<div class="md-content">
<div class="modal-header">
<h3>Confirm Withdrawal Request</h3>
<button type="button" class="close md-close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body form">
<div class="form-group">
<label class="col-sm-3 control-label">Admin Name</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="adminName" value="${adminName}">
<input type="text" class="form-control" name="transferredId" id="transferredId" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Transfer Reference</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="transferReference">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default btn-flat md-close" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-danger btn-flat md-close" name="submitRequest">Submit</button>
</div>
</div>
</div>
After that String withdrawalId = request.getParameter("transferredId"); will return correct id.
Excuse me for not add this as a comment, as i can't because i still not have 50 reputation (still 16), i just want you to test something, try to refresh the page, and open row with ID 119 for example first time, i mean any Id rather than 120, and see what happen, if the value that you opened first time is always still exist, so the problem is not in id 120 and the problem is that u may use if not null to set the value some where, so first time it will be null and the value added to it, but next times it will have a value already so u can't change it, and if u can't solve the problem after doing that, please upload your controller so we can detect the problem
Check the generated HTML. Looks to me that it contains listWithdrawals.length instances of that <input and all of them have the same name.
request.getParameter("id") is going to return a single value, not a list of all the values. What you need is request.getParamaterValues("id") that is going to return all of them.
This is because when the form is submitted all those input values are going to be sent.
So the simple solution (with no JavaScript magic) is to get all the lists of values with request.getParamaterValues and deal with everything that changed. ids[0] and transferReferences[0] would be the needed values for the first item in listWithdrawals:
String[] ids = request.getParamaterValues("id");
String[] transferReferences = request.getParamaterValues("transferReference");
for (int i = 0; i < ids.length; i++) {
System.out.println(ids[i]);
System.out.println(transferReferences[i]);
}
Another solution would be to generate unique names for each input/item in listWithdrawals:
<c:forEach var="withdrawal" items="${listWithdrawals}" varStatus="loopStatus">
<input type="text" class="form-control" name="${'transferReference_'.concat(withdrawal.id)}" value="${withdrawal.id}" />
</c:forEach>
And then you'd be able to access the transferReference value of a withdrawal with ID 119 like this:
request.getParameter("transferReference_119")

Spring MVC getting value of element that is not an object property on the server

I have a jsp page which uses spring tag lib. I have elements on he page that is bind to properties of an object. I also have button values that are not bind to the POJO i am trying to get these values on the server. Under is the code
JSP
<body>
<form:form id="monitoringList" name="monitoringList" commandName="monitoring">
<h3>Monitoring For Criminals Victims/Wittiness</h3>
<h3>Crime Record - ${crimeRecNo}</h3>
<div id="victims">
<h3>Victims</h3>
<hr>
<input type="hidden" id="records" value="${records}"/>
<div id="citizen_row">
<label class="name"></label>
<form:input class="citizen" type="hidden" name="socialSecurityNumber" path="socialSecurityNumber"/>
<table border="1">
<tr>
<td><form:input type="hidden" path="crimeRecNo" name = "crimeRecNo"/>
<canvas id="photoCvs${citizen.socialSecurityNumber}" class="canvas" height="200" width="200"></canvas></td>
<td><label>Start Date : </label><form:input name= "monitoringStDate" path="monitoringStDate" id="monitoringStDate"/></td>
<td><label>End Date : </label><form:input name="monitoringEndDate" path="monitoringEndDate" id="monitoringEndDate"/></td>
<td>
<label>Monitoring Type : </label>
<form:select path="monitoringTypeId" name="monitoringTypeId" id="monitoringTypeId" title="Monitoring Type">
<form:options items="${monitoringType.monitoringTypeList}" itemValue="monitoringTypeId" itemLabel="monitoringTypeDesc" />
</form:select>
</td>
</tr>
</table>
<div><button id="action" onclick="submitPage('${pageContext.request.contextPath}/monitoringList.htm','POST');" type="button">Create Monitoring Records</button></div>
</div>
<!-- MySql first record starts at 0. So we need to send in the value 0 to get the first record. Create Record Navigation based on record count -->
<div id= "recordNavigation">
<c:forEach begin="0" end="${records - 1}" var="i">
<input type="submit" class="navigationbtns" id="page" onclick="submitPage('${pageContext.request.contextPath}/monitoringList.htm','POST');" value="${i}"/>
</c:forEach>
</div>
</div>
</form:form>
</body>
This is the controller and i am using request.getParameter to get the value of the button however the value id null when i click on the button which post me to the server
Controller
#RequestMapping(value = "monitoringList.htm", method = RequestMethod.POST)
public ModelAndView handleNextMonitoringPage(#ModelAttribute("crimeRecNo")Integer crimeRecNo, Model model,#ModelAttribute Monitoring monitoring, BindingResult result,ModelMap m,HttpServletRequest request,SessionStatus status, HttpSession session) throws Exception {
String p_page = request.getParameter("page");
logger.info("Page request was ::" + p_page);
//int page = 0;
myMonitoringTypeList.put("monitoringTypeList",this.monitoringTypeManager.getListOfMonitoringType());
model.addAttribute("monitoringType",myMonitoringTypeList);
Monitoring aMonitoringRecord = new Monitoring();
aMonitoringRecord = this.monitoringManager.getAMonitoringRecByCrimeRecNo(crimeRecNo, page);
int recordCount = this.monitoringManager.MonitoringRecords_RecordCount(crimeRecNo);
model.addAttribute("records",recordCount);
model.addAttribute("crimeRecNo", crimeRecNo);
model.addAttribute("monitoring", aMonitoringRecord);
return new ModelAndView(new RedirectView("monitoringList.htm"),"page",page);
}
you are missing the name attribute under which the value is being submitted
<button name="page" ....>
and
<input type="submit" name="page" ..../>

Spring MVC Multiple ModelAttribute On the Same Form

I have a form with two ModelAttributes one is citizens and the other is punishment. The two objects are separated by jquery tabs. I am having problems in getting the items on the form to display properly some are being displayed and some are not. I mean the html elements.
I am not sure how the Controller would look when there is multiple ModleAttributes on the page. Under is a sample of the code:
Page
<title>Citizen Registration</title>
</head>
<body>
<div id="tabs">
<ul>
<li>Citizen Registration</li>
<li>Punishment</li>
</ul>
<div id="tab1">
<form:form id="citizenRegistration" name ="citizenRegistration" method="post" modelAttribute="citizens" action="citizen_registration.htm">
<div id="divRight" class="mainDiv">
<div class="divGroup" id="divCharInfo">
<fieldset>
<legend>Characteristics Info</legend>
<ol>
<li><form:label for="photo" path="photo">Select Photo</form:label>
<form:input path="photo" type="file" id="photo" title="Upload a photo"/><form:errors path="photo" id="errors"/></li>
<li>
<label>Select Gender</label>
<form:select path="genderId" id="genderId" title="Select Your Gender">
<form:options items = "${gender.genderList}" itemValue="genderId" itemLabel="genderDesc" />
</form:select>
<form:errors path="genderId" class="errors"/>
</li>
<li><form:label for="weight" path="weight">Enter Weight <i>(lbs)</i></form:label>
<form:input path="weight" id="weight" title="Enter Weight"/><form:errors path="weight" id="errors"/>
</li>
<li><form:label for="height" path="height">Enter Height <i>(feet)</i></form:label>
<form:input path="height" id="height" title="Enter Height"/><form:errors path="height" id="errors"/>
</li>
.......................
<div id="tab2">
<form:form id="punishmentRegistration" name ="punishmentRegistration" method="post" modelAttribute="punishment" action="punishment_registration.htm">
<ol>
<li>
<form:label for ="punishmentId" path="punishmentId">Punishment Number</form:label>
<form:input path="punishmentId" id="punishmentId"/><form:errors path="punishmentId" id="errors"/>
</li>
<li>
<form:label for="crimeRecNo" path="crimeRecNo">Select Crime</form:label>
<form:select path="crimeRecNo" id="CrimeRecNo" title="Select Crime">
<form:options items = "${crime.crimeList}" itemValue="crimeRecNo" itemLabel="crimeRecNo" title="crimeDesc"/>
</form:select>
<form:errors path="crimeRecNo" id="errors"/>
</li>
<li>
<form:label for ="monitoringStDate" path="monitoringStDate"> Start Date </form:label>
<form:input path="monitoringStDate" id="monitoringStDate"/><form:errors path="monitoringStDate" id="errors"/>
</li>
<li>
<form:label for ="monitoringEnDate" path="monitoringEnDate"> End Date </form:label>
<form:input path="monitoringEnDate" id="monitoringEnDate"/><form:errors path="monitoringEnDate" id="errors"/>
</li>
</ol>
</form:form>
</div>
</div>
</body>
</html>
Controller
#RequestMapping(value="citizen_registration.htm", method = RequestMethod.GET)
public ModelAndView loadPage(HttpServletRequest request,
HttpServletResponse response,
#ModelAttribute Citizens citizens, #ModelAttribute Punishment punishment,
BindingResult result,
ModelMap m, Model model) throws Exception {
//code here
return new ModelAndView("citizen_registration");
This is my code however when i run it nothing in tab2 is displayed andnot all elements in tab1 is shown.
I don't think so if you can bind multiple models using the Spring form. In fact you should take a look in the spring binding form.
http://static.springsource.org/spring/docs/1.1.5/taglib/tag/BindTag.html
Take a look in the sample code. I have not tested the code. Let know in case of any issues.
Model
public class User{
private String username;
private String password;
..Setter and Getters
}
public class UserProfile{
private String firstName;
private String lastName;
setter and getter
}
Controller
#Controller
public class MyController{
#RequestMapping(....)
public String newAccountForm(ModelMap map){
User user = new User(); //Would recommend using spring container to create objects
UserProfile profile = new UserProfile();
map.addAttribute('user', user);
map.addAttribute('profile', profile);
return "form"
}
#RequestMapping(....)
public String newAccountForm(#ModelAttrbite('User')User user, BindingResult resultUser, #ModelAttribute('UserProfile')UserProfile userProfile, BindingResult resultProfile){
//Check the binding result for each model. If not valid return the form page again
//Further processing as required.
}
}
JSP
<%#taglib uri="http://www.springframework.org/tags" prefix="spring">
<form action="" method="post">
<spring:bind path="user.username">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="user.password">
<input type="password" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="profile.firstName">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="profile.lastName">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<input type="submit" value="Create"/>
</form>
I already gave alternate approach in this link here
<form:form method="POST" modelAttribute="applicationGeneralInformation">
<div class="section2">
<h2>General Informaion</h2>
<form:input type="hidden" path="id" id="id"/>
<label for="app_version">Version</label>: <form:input type="text" id="app_version" path="version"/><br/>
<label for="app_func_desc">Description</label>: <form:input type="text" id="app_func_desc"
path="functionalDescription"/><br/>
<label for="app_sec_func">Functions</label>: <form:input type="text" id="app_sec_func"
path="securityFunctions"/><br/>
</div>
<div class="section2">
<h2>Application Content</h2>
<form:form method="POST" modelAttribute="applicationContent">
<div>
<h3>CIA Rating</h3>
<label for="CIARating">CIA Rating</label>: <form:select type="text" id="CIARating" path="CIARating">
<form:option value="1">1</form:option>
<form:option value="2">2</form:option>
<form:option value="3">3</form:option>
<form:option value="4">4</form:option>
</form:select><br/><br/>
</div>
<div>
<h3>Business Continuity and Disaster Recovery</h3>
<div>
<h4>RTO</h4>
<label for="RTO">RTO</label>: <form:select type="text" id="RTO" path="RTO">
<form:option value="1">< 2<sub>Hrs</sub></form:option>
<form:option value="2">2<sub>Hrs</sub>-4<sub>Hrs</sub> </form:option>
<form:option value="3">4<sub>Hrs</sub>-48<sub>Hrs</sub></form:option>
<form:option value="4">> 48<sub>Hrs</sub></form:option>
</form:select><br/>
</div>
<div>
<h4>RPO</h4>
<label for="RPO">RPO</label>: <form:input type="text" id="RPO" path="RPO"/><br/>
</div>
</div>
</form:form>
<input type="submit" value="Submit">
</div>
</form:form>
<script type="text/javascript">
$(document).ready(
function() {
$("#userAttendance").submit(
function(e) {
e.preventDefault();
jQuery.ajaxSetup({
async : false
});
var a = "${pageContext.request.contextPath}";
alert(a);
$.post($(this).attr("action"), $(this).serialize(),
function(response) {
$("#showTableByDate").html(response);
jQuery.ajaxSetup({
async : true
});
});
});
//Date picker
$('#datepicker').datepicker({
autoclose : true
});
});

Categories