Spring MVC Multiple ModelAttribute On the Same Form - java

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
});
});

Related

405 - request GET and POST

Hello i have problem with update object, i dont know how always aftre update data i have message: Request method 'GET' not supported. But date after refresh object is update.
Controller with GET and POST method to update object
#Controller
#RequestMapping("/packet")
public class PacketController {
#GetMapping("/modify/{id}")
public String modifyPacketGet(Model model, #PathVariable Long id)
{
model.addAttribute("channels", channelService.getAllChannels());
model.addAttribute("packet", packetService.getById(id));
return "packet/modify";
}
#PostMapping("/modify")
public String modifyPacketPost(Model model, #ModelAttribute PacketDto packetDto)
{
packetService.updatePacket(packetDto);
return "redirect:/packet/modify";
}
HTML form
<form th:action="#{/packet/modify}" method="post" th:object="${packet}" enctype="multipart/form-data">
<input type="text" hidden="hidden" readonly="readonly" th:field="*{id}" />
<input type="text" hidden="hidden" readonly="readonly" th:field="*{filename}" />
<div class="form-group">
<label for="name" class="h3 text-success">Name:</label>
<input id="name" type="text" th:field="*{name}" class="form-control">
</div>
<div class="form-group">
<label for="price" class="h3 text-success">Price:</label>
<input id="price" type="text" th:field="*{price}" class="form-control">
</div>
<div class="form-group">
<label for="description" class="h3 text-success">Description:</label>
<textarea class="form-control" rows="5" th:field="*{description}" id="description"></textarea>
</div>
<div class="form-group">
<label for="image" class="h3 text-success">Image:</label>
<input id="image" type="file" th:field="*{multipartFile}" accept="image/**" class="form-control">
</div>
<div class="form-group">
<label for="channel" class="h2 text-secondary">Channels:</label>
<ul class="list-inline">
<li class="list-inline-item" th:each="c : ${channels}">
<input id="channel" type="checkbox" th:field="*{channelIds}" th:value="${c.id}">
<label th:text="${c.name}"></label>
</li>
</ul>
</div>
<button type="submit" class="btn btn-success btn-lg mr-2">Add</button>
</form>
The http request GET /packet/modify is not being handled in your controller and you are redirecting your POST method to that http request:
return "redirect:/packet/modify";
To solve this you need to do one of the following:
Change the redirect request in your POST to an endpoint that is being handled:
return "redirect:/packet/modify/" + packetDto.getPacketId();
Or, handle that GET endpoint:
#GetMapping("/modify/")
public String retrievePacket(...) { ... }
Hope this helps.

java spring - post request with additional value

I have implemented a registration process where you can send user data to the controller via post request.
The post request works fine, however now I want to pass another value (role, Long) from the form to the controller that is not an attribute of the user model.
That part is not working.
Does anyone know why?
HTML:
<form action="add_user" method="post" class="form-horizontal" th:object="${user}">
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<input th:field="*{username}" class="form-control" placeholder="Person ID" type="text" name="id" id="id"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<input th:field="*{firstName}" class="form-control" placeholder="First Name" type="text" name="firstname" id="firstname"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<input th:field="*{lastName}" class="form-control" placeholder="Last Name" type="text" name="lastname" id="lastname"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<input th:field="*{password}" class="form-control" placeholder="Password" type="password" name="password" id="password"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<select th:field="${role}" class="form-control" id="role">
<option value="1">Admin</option>
<option value="2" >User</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<button type="submit" class="btn btn-success" value="Submit">Save</button>
</div>
</div>
</form>
Controller:
#RequestMapping(value = "/users", method = RequestMethod.GET)
public String showUsers(Model model)
model.addAttribute("user", new User());
model.addAttribute("role", new Long(2));
return "users";
}
And:
#RequestMapping(value = "/add_user", method = RequestMethod.POST)
public String handleNewUser(#ModelAttribute("user") User user, BindingResult bindingResult, Model model, long role) {
if (user != null) {
System.out.println(role);
userService.save(user);
}
return "redirect:/users";
}
th:field="${role}" means name of field in the model object, not its value. You probably want to write th:value="${role}" instead of this.

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

sending multiple row data (table) from HTML to Spring controller using thymeleaf

I am working on application using html, thymeleaf, Spring MVC, I wanted to send table data to spring controller but in when I clicked on save button of the application, getting an error on console:
java.lang.IllegalStateException: Neither BindingResult nor plain
target object for bean name 'salesProduct[0]' available as request
attribute
at org.springframework.web.servlet.support.BindStatus.(BindStatus.java:144)
at org.thymeleaf.spring4.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:396)
Browser Error:
HTTP Status 500 - Request processing failed; nested exception is
org.thymeleaf.exceptions.TemplateProcessingException: Error during
execution of processor
'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor'
(sales:290)
I have added three attributes to controller like salesBean, paymentBean and salesProductFormBean, you can see in below spring controller code that is the reason in html I have not added th:object="${...}" in the form tag.
HTML
Sales.html
<form th:action="#{/salesForm}" method="post" class="mainData"
id="form">
<div class="buttonBar" id="mainbutton">
<div>
<button class="btn" id="save" type="submit">
<img th:src="#{/resources/images/save.svg}" /> Save
</button>
<button class="btn" id="reset" onclick="clearForm()" type="reset">
<img th:src="#{/resources/images/reset.svg}" /> Reset
</button>
<button type="button" class="btn" id="clientNew">
<img th:src="#{/resources/images/notebook.svg}" /> Client Creation
</button>
</div>
</div>
<div class="container">
<div class="mp-pusher" id="mp-pusher">
<nav id="mp-menu" class="mp-menu"></nav>
<div class="scroller-inner"></div>
<div class="containerMain">
<div class="mainArea">
<div class="inputArea">
<div class="ccode">
<lable class="lable">Client code</lable>
<input type="text" class="inputfield" id="ccode"
th:field="*{salesBean.client.clientId}" />
<button type="button" class="inputbutton" id="clientData"></button>
</div>
<div>
<ul class="tabs" data-persist="true">
<li>Basic data</li>
<li>Payment</li>
</ul>
<div class="tabcontents">
<div id="tab1">
<div class="invNo">
<lable class="lable">Invoice number</lable>
<input type="text" id="invNo" th:field="*{salesBean.salesId}"
name="salesId" class="inputfield disabled"
readonly="readonly" />
</div>
<div class="invdate calendar">
<lable class="lable">Invoice date</lable>
<input type="date" class="inputfield" id="invdate"
th:field="*{salesBean.invoiceDate}" /> <span
class="calendar"><img
th:src="#{/resources/images/calendar.svg}" /></span>
</div>
<div class="txtChallan">
<lable class="lable">Challan number</lable>
<input type="text" class="inputfield" id="txtChallan"
th:field="*{salesBean.challanNumber}" />
</div>
<div class="txtChallDt calendar">
<lable class="lable">Date</lable>
<input type="date" class="inputfield" id="txtChallDt"
th:field="*{salesBean.challanDate}" /> <span
class="calendar"><img
th:src="#{/resources/images/calendar.svg}" /></span>
</div>
<div class="txtPO">
<lable class="lable">P. O. ID</lable>
<input type="text" class="inputfield" id="txtPO"
th:field="*{salesBean.purchaseOrderId}" />
</div>
<div class="txtPoDt calendar">
<lable class="lable">Date</lable>
<input type="date" class="inputfield" id="txtPoDt"
th:field="*{salesBean.purchaseOrderDate}" /> <span
class="calendar"><img
th:src="#{/resources/images/calendar.svg}" /></span>
</div>
</div>
<div id="tab2">
<div class="txtCash">
<lable class="lable">Cash</lable>
<input type="number" class="inputfield" id="txtCash"
th:field="*{paymentBean.cash}" />
</div>
</div>
</div>
<!-- tabcontents -->
</div>
<!-- blank -->
<!-- for autocomplete -->
<div class="ui-widget" id="autocomplete_desc">
<div class="tableArea">
<div class="tablePanel">
<div class="tableButtonBar">Material entry</div>
<section class="tableHolder">
<table id="invoicetable" class="transactionTable table"
cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>Serial</th>
<th>Description</th>
<th>Nos.</th>
<th>Quantity</th>
<th>Rate</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr
th:each="salesProduct, stat: *{salesProductFormBean.salesProducts}">
<td th:text="${stat.count}">1</td>
<td><input type="text"
**Line no: 290** th:field="*{salesProduct[__${stat.index}__].numbers}" /></td>
<td><select type="select" class="selectfield"
id="product"
th:field="*{salesProduct[__${stat.index}__].product.productId}">
<option value="Select"></option>
<option th:each="prdList : ${productList}"
th:value="${prdList.productId}"
th:text="${prdList.productName}"></option>
</select></td>
<td><input type="number"
th:field="*{salesProduct[__${stat.index}__].quantity}" /></td>
<td><input type="number"
th:field="*{salesProduct[__${stat.index}__].rate}" /></td>
<td><input type="number"
th:field="*{salesProduct[__${stat.index}__].amount}" /></td>
</tr>
</tbody>
</table>
</section>
</div>
<!-- tablePanel -->
</div>
<!-- tableArea -->
</div>
</div>
<!-- inputArea -->
</div>
<!-- mainArea -->
</div>
<!-- containerMain -->
</div>
<!-- /container -->
</div>
</form>
Controller
#Autowired
private List<SalesProduct> salesProducts= new ArrayList<SalesProduct>();
#ModelAttribute("salesProducts")
public List<SalesProduct> salesProducts() {
return salesProducts;
}
#RequestMapping(value= "/sales", method = RequestMethod.GET)
public String salesInvoicePage(final ModelMap model) {
String userName = LoginController.getPrincipal();
model.addAttribute("user", userName);
model.addAttribute("salesBean", new Sales());
model.addAttribute("paymentBean", new Payment());
SalesProductForm salesProductForm = new SalesProductForm();
SalesProduct salesProduct= new SalesProduct();
salesProducts.add(salesProduct);
salesProductForm.setSalesProducts(salesProducts);
model.addAttribute("salesProductFormBean", salesProductForm);
//model.addAttribute("salesProducts", salesProducts);
List<Product> productList= productService.list();
model.addAttribute("productList", productList);
return "sales";
}
Model
public class SalesProduct implements java.io.Serializable {
private Integer salesProductId;
private Product product;
private UserDetail userDetailByModifiedBy;
private UserDetail userDetailByCreatedBy;
private Date createdDate;
private Date modifiedDate;
private String numbers;
private Float quantity;
private Float rate;
private Float amount;
private Set<Sales> saleses = new HashSet<Sales>(0);
//Setter and Getters
}
public class SalesProductForm {
private List<SalesProduct> salesProducts;
public List<SalesProduct> getSalesProducts() {
return salesProducts;
}
public void setSalesProducts(List<SalesProduct> salesProducts) {
this.salesProducts = salesProducts;
}
}
I got stuck in this issue but dont know what am I missing. Does anyone knows what am I doing wrong?

Redirect to same tab on page upon Form submission - Spring MVC

I am using Spring MVC. I have a jsp page with multiple tabs. Each tab has a form. All these tabs are in a single jsp page called admin.jsp
I want to redirect the tab to itself upon POST to show errors or success message of transaction(Validation of input). What view should I return from the controller for each tab.
Controller:
#RequestMapping(value="/register", method = RequestMethod.POST)
public String registerDevice(#ModelAttribute("deviceMaster") #Validated DeviceMaster deviceMaster, BindingResult result, Model model, Locale locale) {
try {
if(result.hasErrors()){
return "admin";
}
/*CODE*/
}
#RequestMapping(value="/lock", method = RequestMethod.POST)
public #ResponseBody Status lockDevice(#ModelAttribute("adminTransaction") #Validated AdminTransaction adminTransaction, BindingResult result, Model model, Locale locale,Map<String, Object> map, HttpServletRequest request, #RequestParam #DateTimeFormat(pattern="yyyy-MM-dd") Date dueDate) {
try {
if(result.hasErrors()){
return "admin";
}
/*CODE*/
}
#RequestMapping(value="/unlock", method = RequestMethod.POST)
public #ResponseBody Status unlockDevice(#ModelAttribute("adminTransaction") #Validated AdminTransaction adminTransaction, BindingResult result, Model model, Locale locale,Map<String, Object> map, HttpServletRequest request) {
try {
if(result.hasErrors()){
return "admin";
}
/*CODE*/
}
admin.jsp
<div class="tabs" align="center">
<div class="list-center">
<ul class="tab-links">
<li class="active">Register</li>
<li>Lock</li>
<li>Unlock</li>
</ul>
</div>
<div class="tab-content">
<div id="tab1" class="tab active">
<div class="devices">
<form:form method="post" id="registerForm" modelAttribute="deviceMaster" action="/DeviceManager/admin/register">
<form:errors path="*" cssClass="plErroMessage" element="div" />
<br>
<c:if test="${not empty serverError}">
<div id="serverError" class="plErroMessage">${serverError}</div>
</c:if>
<div>
<div class="plLabelSearch">Device Id:</div>
<div class="plinput"><form:input path="deviceId" type="text" size="29"/></div>
</div>
<div>
<div class="plLabelSearch">Home Whse:</div>
<div class="plselect">
<form:select path="warehouseHome">
<form:option value="NONE" label="------- Select One -------"/>
<form:option value="TR" label="TRAINING"/>
<form:options items="${homeWhseList}" itemValue="warehouseCode" itemLabel="warehouseCode"/>
</form:select>
</div>
</div>
<br>
<br>
<div>
<div class="plLabelSearch"> </div>
<div class="plinput"><a id="btnRegister" class="abutton">Register</a></div>
<div class="plinput"><a id="btnCancel1" class="abutton">Cancel</a></div>
</div>
</form:form>
</div>
</div>
<div id="tab2" class="tab">
<div class="devices" >
<form:form method="post" id="lockForm" modelAttribute="adminTransaction" action="/DeviceManager/admin/lock">
<form:errors path="*" cssClass="plErroMessage" element="div" />
<br>
<c:if test="${not empty serverError}">
<div id="serverError" class="plErroMessage">${serverError}</div>
</c:if>
<div>
<div class="plLabelSearch">Device Id:</div>
<div class="plinput"><form:input path="deviceId" size="29"/></div>
</div>
<div>
<div class="plLabelSearch">Reason Code:</div>
<div class="plselect">
<form:select path="reasonCodeForeignKey">
<form:option value="NONE" label="------- Select One -------" />
<form:options items="${reasonList}" itemValue="reasonCode" itemLabel="reasonDesc"/>
</form:select>
</div>
</div>
<div class="hidden" >
<div>
<div class="plLabelSearch">Away Whse:</div>
<div class="plselect">
<form:select path="awayWarehouse">
<form:option value="NONE" label="------- Select One -------" />
<form:options items="${homeWhseList}" itemValue="warehouseCode" itemLabel="warehouseCode"/>
</form:select>
</div>
</div>
<div>
<div class="plLabelSearch">Due Date:</div>
<div class="plinput"><form:input id="datepicker" path="dueDate" placeholder="yyyy-mm-dd"/></div>
</div>
<div>
<div class="plLabelSearch">IT Ticket:</div>
<div class="plinput"><form:input path="itTicket" value="" size="29"/></div>
</div>
</div>
<br>
<br>
<div>
<div class="plLabelSearch"> </div>
<div class="plinput"><a id="btnLock" class="abutton">Lock</a></div>
<div class="plinput"><a id="btnCancel2" class="abutton">Cancel</a></div>
</div>
</form:form>
</div>
</div>
<div id="tab3" class="tab">
<div class="devices" >
<form:form method="post" id="unlockForm" modelAttribute="adminTransaction" action="/DeviceManager/admin/unlock">
<form:errors path="*" cssClass="plErroMessage" element="div" />
<br>
<c:if test="${not empty serverError}">
<div id="serverError" class="plErroMessage">${serverError}</div>
</c:if>
<div>
<div class="plLabelSearch">Device Id:</div>
<div class="plinput"><form:input path="deviceId" size="29"/></div>
</div>
<br>
<br>
<div>
<div class="plLabelSearch"> </div>
<div class="plinput"><a id="btnUnlock" class="abutton">Unlock</a></div>
<div class="plinput"><a id="btnCancel3" class="abutton">Cancel</a></div>
</div>
</form:form>
</div>
</div>
Handled it using jQuery and kept selected tab active on refresh with Bootstrap 3
$(document).ready(function() {
var activeTab = localStorage.getItem('activeTab');
if(activeTab){
$('.tab-links a[href="' + activeTab + '"]').tab('show');
}
$('.tabs .tab-links a').on('click', function(e) {
var currentAttrValue = jQuery(this).attr('href');
localStorage.setItem('activeTab', currentAttrValue);
jQuery('.tabs ' + currentAttrValue).siblings().slideUp(400);
jQuery('.tabs ' + currentAttrValue).delay(400).slideDown(400);
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
});

Categories