I'm currently developing an online banking application where you can buy stocks. It is being built with spring boot and the front-end is html/css.
I am using the YahooFinance API to get stock quotes but I need to refresh my page to get the live stock quotes, how can I automatically update the page every 30 seconds to get the new prices for each stock?
Also, is there a way I could implement this using Threads?
Banking Controller
#GetMapping("/banking/stocks")
public String stocks(Model model) {
model.addAttribute("stock", new StockDto());
try {
List<Stock> stocks = stockService.getDefaultStocks();
model.addAttribute("stocks", stocks);
} catch (IOException e) {
e.printStackTrace();
}
return "stocks.html";
}
StockServiceImpl:
#Service
public class StockServiceImpl implements StockService {
private String[] startingStocks = { "AAPL", "BABA", "MSFT", "AXP", "BA", "AMD", "TSLA", "MA", "SHOP", "GOOGL",
"KL" };
#Override
public Stock getStock(String stockName) throws IOException {
Stock stock = YahooFinance.get(stockName);
return stock;
}
#Override
public Map<String, Stock> getStock(String[] s) throws IOException {
Map<String, Stock> stocks = YahooFinance.get(s);
return stocks;
}
#Override
public List<Stock> getDefaultStocks() throws IOException {
Map<String, Stock> stocks = YahooFinance.get(startingStocks);
List<Stock> stockList = new ArrayList<Stock>();
for(String s : startingStocks) {
stockList.add(stocks.get(s));
}
return stockList;
}
}
HTML Page For Displaying Stocks:
<main class='main-content bgc-grey-100'>
<div id='mainContent'>
<div class="container-fluid">
<br>
<h4 class="c-grey-900 mT-10 mB-30">Stock Table</h4>
<form action="#" th:object="${stock}" th:action="#{/banking/stock-search}"
method="POST" class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search"
th:field="*{name}" placeholder="Search Stock"
aria-label="Search">
<button class="btn btn-outline-primary my-2 my-sm-0" type="submit">Search</button>
</form>
<br>
<div class="row">
<div class="col-md-12">
<div class="bgc-white bd bdrs-3 p-20 mB-20">
<table id="dataTable" class="table table-striped table-bordered"
cellspacing="0" width="100%">
<thead>
<tr>
<th>Ticker</th>
<th>Trade</th>
<th>Name</th>
<th>Price</th>
<th>(%) Change</th>
<th>Div Yield (%)</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Ticker</th>
<th>Trade</th>
<th>Name</th>
<th>Price</th>
<th>(%) Change</th>
<th>Div Yield (%)</th>
</tr>
</tfoot>
<tbody>
<tr th:each="stock : ${stocks}">
<td th:text="${stock.getSymbol()}"></td>
<td>
<form action="#" th:action="#{/banking/stocks/} + ${stock.symbol}" method="get">
<button class="btn btn-outline-success my-2 my-sm-0" th:id="'table_entry_childs_button_' + ${stock.symbol}" type="submit">
<i>Trade</i>
</button>
</form>
</td>
<td th:text="${stock.getName()}"></td>
<td th:text="${stock.getQuote().getPrice()}"></td>
<td th:class="${stock.getQuote().getChangeInPercent() > 0 ? 'text-success' : 'text-danger'}" th:text="${stock.getQuote().getChangeInPercent() + '%'} "></td>
<td th:if="${stock.getDividend().getAnnualYield() != null}" th:text="${stock.getDividend().getAnnualYield() + '%'}">0.00%</td>
<td th:if="${stock.getDividend().getAnnualYield() == null}" >0.00%</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</main>
You can exploit STOMP protocol and web sockets using spring boot.
For reference:
https://www.baeldung.com/spring-websockets-send-message-to-user
on back end side you can use
#Autowired
SimpMessagingTemplate messagetemplate;
public void somemethod(String strParam){
while (true){
// build string or json whatever you need to send
messagetemplate.convertAndSend("/blabla/blabla",strParam);
Thread.sleep(30*1000);
}
}
on front end side you have to use stomp.js
<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.js">
<script type="text/javascript">
function load(){
var stompClient = Stomp.client("ws://localhost:8080/ws");
stompClient.connect({}, function (frame) {
stompClient.subscribe('/blabla/blabla', function (message) {
// do something here
});
});
}
lastly, part of html where you want to call on load
<html>
<body onload="load()">
</body>
</html>
You can create an #Scheduled method that can call this API request every 30 seconds to get data and update your Front-End.
#Scheduled(fixedRate = 30000)
public void updateStocksElement() {
//Call your /banking/stocks rest endpoint
}
https://spring.io/guides/gs/scheduling-tasks/
Related
In the first form I enter a number that will call a service and then return the data on the same page.
The first part works fine but the problem lies when I want to display the data obtained on the screen.
Sorry if my English is hard to understand
Here a consultation Page.
<wicket:extend>
<div>
<form wicket:id="form" class="flex-1 flex-column">
<div class="field">
<label for="service">Ingrese numero de tramite</label>
<input type="text" name="tramite" id="service" wicket:id="tramite" required>
</div>
<div >
<a wicket:id="service" class="ui button" type="submit">Invocar servicio</a>
</div>
</form>
</div>
<div>
<table>
<tr wicket:id="item">
<td wicket:id="tributo">Tributo</td>
<td wicket:id="cuenta">Cuenta</td>
<td wicket:id="tipoDoc">TipoDoc</td>
<td wicket:id="nroDoc">NroDoc</td>
</tr>
</table>
</div>
</wicket:extend>
Fragment of java class PaginaPruebaServicioTitularAsociado which extends from WebPage:
private void addForm() {
modelTramite = new Model<>();
Form form = new Form<>("form");
form.add(new TextField<>("tramite",modelTramite));
AjaxSubmitLink guardarLink = new AjaxSubmitLink("service") {
#Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
try {
List<TitularAsociado>list1= consultaTitularesAsociados(modelTramite.getObject());
addDatos(list1);
}
catch (DfeErpException e) {
throw new RuntimeException(e.getMessage());
}
}
};
guardarLink.setOutputMarkupId(true);
form.add(guardarLink);
add(form);
}
private void addDatos(List<TitularAsociado>list1){
add(new ListView<TitularAsociado>("item", list1) {
protected void populateItem(final ListItem<TitularAsociado> listItem){
listItem.add(new Label("tributo", listItem.getModelObject().getTributo()));
listItem.add(new Label("cuenta", listItem.getModelObject().getCuenta()));
listItem.add(new Label("tipoDoc", listItem.getModelObject().getTipoDocumento()));
listItem.add(new Label("nroDoc", listItem.getModelObject().getNroDocumento()));
listItem.add(new Label("codRelacion", listItem.getModelObject().getCodigoRelacion()));
}
});
}
LOGS:
Handling the following exception
org.apache.wicket.markup.MarkupNotFoundException: Can not determine Markup. Component is not yet connected to a parent. [Page class = webapp.PaginaPruebaServicioTitularAsociado, id = 3, render count = 1]
at org.apache.wicket.Component.getMarkup(Component.java:750)
(First time asking a question here) I created a rest api on java that returns all the cars available in the table Cars from my db. I found a way to get one of the cars with an specific Id and can show it on my page, but it can't understand how to show all the cars in the same page. Basically i don't understand how to show the arraylist that I get from my Rest Api and show it. I see the whole array in the console but not on my html. I not asking for the whole architecture of angular, just want to know how to show on my app-component when I click a button all the items that my rest has.
My rest:
#GET
#Produces({ "application/json" })
public List<CarDto> getCars() {
Car macchina;
// CarDao trasform1 = new CarDao();
CarDto trasform2;
// java 8+ lambda function, Stream (per divertimento)
List<Car> listaMac = carDao.getCars();
List<CarDto> listaMacAgg = new ArrayList<>();
for (int i = 0; i < listaMac.size(); i++) {
trasform2 = new CarDto(listaMac.get(i));
listaMacAgg.add(trasform2);
}
return listaMacAgg;
}
The class from my app component that gets the response from my rest:
import { Component } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'rest agency test';
caid: string = "";
response: any;
response2:any;
constructor(private http: HttpClient){}
ngOnInit(){
}
search(){
this.http.get('http://localhost:8080/rest_agency/rest/hello/'+this.caid)
.subscribe((response) => {
this.response = response;
console.log(this.response);
})
}
allCars(){
this.http.get('http://localhost:8080/rest_agency/rest/hello')
.subscribe((response2) => {
this.response = response2;
console.log(this.response);
})
}
}
my app.component.html
<div style="text-align:center">
<h1>
Welcome to {{ title }}!
</h1>
<p><button (click)="allCars()"> All Cars</button></p>
<p>Search id:<input type="text" [(ngModel)]="caid">
<button (click)="search()">Search</button></p>
<div *ngIf="response2">
<table>
<ul class="heroes">
<tr>
<td>ID</td>
<td>Brand</td>
<td>Color</td>
<td>Year</td>
<td>Price</td>
<td>Sold</td>
</tr>
<tr>
<div *ngFor="let all of response | keyvalue">
<td><li>{{response.caId}}</li></td>
<td><li>{{response?.brand}}</li></td>
<td><li>{{response?.color}}</li></td>
<td><li>{{response?.year}}</li></td>
<td><li>{{response?.price}}</li></td>
<td><li>{{response?.sold}}</li></td>
</div>
</tr>
</ul>
</table>
</div>
<div *ngIf="response"> {{response.caid}}
<table>
<ul class="heroes">
<tr>
<td>ID</td>
<td>Brand</td>
<td>Color</td>
<td>Year</td>
<td>Price</td>
<td>Sold</td>
</tr>
<tr>
<td><li>{{response?.caId}}</li></td>
<td><li>{{response?.brand}}</li></td>
<td><li>{{response?.color}}</li></td>
<td><li>{{response?.year}}</li></td>
<td><li>{{response?.price}}</li></td>
<td><li>{{response?.sold}}</li></td>
</tr>
</ul>
</table>
</div>
</div>
I was expecting the result of all the info of the arraylist that comes from the rest
here is what it shows calling one id : https://imgur.com/FHX4aiO
and here's what happens when call the whole list: https://imgur.com/pdjg4aq)
You say <div *ngIf="response2"> but you never store anything in response2. As a result this block is never shown. Please change to
allCars(){
this.http.get('http://localhost:8080/rest_agency/rest/hello')
.subscribe((response2) => {
this.response2 = response2;
console.log(this.response);
})
}
--
<div *ngIf="response2">
<table>
<ul class="heroes">
<tr>
<td>ID</td>
<td>Brand</td>
<td>Color</td>
<td>Year</td>
<td>Price</td>
<td>Sold</td>
</tr>
<tr>
<div *ngFor="let all of response2 | keyvalue">
<td><li>{{all.caId}}</li></td>
<td><li>{{all.brand}}</li></td>
<td><li>{{all.color}}</li></td>
<td><li>{{all.year}}</li></td>
<td><li>{{all.price}}</li></td>
<td><li>{{all.sold}}</li></td>
</div>
</tr>
</ul>
</table>
</div>
Is the keyvalue really necesary? I highly recommend to type your stuff, avoid any
PS.: Your Lamba function likely looks like this (much shorter)
#GET
#Produces({ "application/json" })
public List<CarDto> getCars() {
return carDao.getCars().stream().map(car => new CarDto(car)).collect(Collectors.toList());
}
Here is error
<div *ngFor="let all of response2 | keyvalue">
change to
<div *ngIf="response">
<table>
<ul class="heroes">
<tr>
<td>ID</td>
<td>Brand</td>
<td>Color</td>
<td>Year</td>
<td>Price</td>
<td>Sold</td>
</tr>
<tr>
<div *ngFor="let respone_one of response | keyvalue">
<td><li>{{respone_one?.caId}}</li></td>
<td><li>{{respone_one?.brand}}</li></td>
<td><li>{{respone_one?.color}}</li></td>
<td><li>{{respone_one?.year}}</li></td>
<td><li>{{respone_one?.price}}</li></td>
<td><li>{{respone_one?.sold}}</li></td>
</div>
</tr>
</ul>
</table>
</div>
Your issue comes from the ngFor let all of response | keyvalue. The values you are looking for are in the all reference, not response.
Try this:
<div *ngFor="let all of response | keyvalue">
<td><li>{{all?.caId}}</li></td>
<td><li>{{all?.brand}}</li></td>
<td><li>{{all?.color}}</li></td>
<td><li>{{all?.year}}</li></td>
<td><li>{{all?.price}}</li></td>
<td><li>{{all?.sold}}</li></td>
</div>
In my jsp page there have a table with nested list value, i want to send that table value to the container, The outer table value were sent but the inner table value not sent to the container, I am new here please let me know how to over come this situation,
My jsp
<script>
function rowAdded(rowElement) {
//clear the imput fields for the row
$(rowElement).find("input").val('');
//may want to reset <select> options etc
//in fact you may want to submit the form
saveNeeded();
}
function rowRemoved(rowElement) {
saveNeeded();
}
function saveNeeded() {
$('#submit').css('color','red');
$('#submit').css('font-weight','bold');
if( $('#submit').val().indexOf('!') != 0 ) {
$('#submit').val( '!' + $('#submit').val() );
}
}
function beforeSubmit() {
alert('script Working');
return true;
}
$(document).ready( function() {
var config = {
rowClass : 'rule',
addRowId : 'addRule',
removeRowClass : 'removeRule',
formId : 'ruleListForm',
rowContainerId : 'ruleListContainer',
indexedPropertyName : 'ruleList',
indexedPropertyMemberNames : 'id,ruleName,parameterName,overwriteValue',
rowAddedListener : rowAdded,
rowRemovedListener : rowRemoved,
beforeSubmit : beforeSubmit
};
new DynamicListHelper(config);
});
</script>
<html>
<form:form action="/update" method="post" id="ruleListForm" modelAttribute="ruleListContainer">
<table border="1">
<thead>
<h3 align="center">Selected Rule</h3>
<tr>
<th data-field="id" width="25">ID </th>
<th data-field="details" width="20">RuleName </th>
<th data-field="parameter" width="240">Parameter </th>
</tr>
</thead>
<tbody id="ruleListContainer">
<c:forEach items="${List2}" var="as">
<tr class="rule">
<td><input type="hidden" name="ruleList[].id" value="${as.rule.id}" /> ${as.rule.id}</td>
<td><input type="hidden" name="ruleList[].ruleName" value="${as.rule.ruleName}" /> ${as.rule.ruleName}</td>
<td> <input id="one" class="datepicker" type="text" name="ruleList[].startDate" size="11" height="0.10"></td>
<td> <input id="two" class="datepicker" type="text" name="ruleList[].endDate" size="11" height="0.10"></td>
<td>
<table border="1">
<c:forEach items="${as.ruleAssignmentParameter}" var="asss">
<tr>
<td><input type="hidden" name="ruleList[].parameterName"value="${asss.parameterName}" > ${asss.parameterName}</td>
<td><input type="hidden" name="ruleList[].overwriteValue" value="${asss.overwriteValue}" /> ${asss.overwriteValue}</td>
</tr>
</c:forEach>
</table>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<br>
<input type="submit" value="Update">
</form:form>
</html>
Here is my model class
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import com.demo.app.model.RuleAssignmentParameter;
public class RuleAssUI {
private int id;
private String ruleName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRuleName() {
return ruleName;
}
public void setRuleName(String ruleName) {
this.ruleName = ruleName;
}
private List<RuleAssignmentParameter> ruleAssignmentParameter = new LinkedList<RuleAssignmentParameter>();
public List<RuleAssignmentParameter> getRuleAssignmentParameter() {
return ruleAssignmentParameter;
}
public void setRuleAssignmentParameter(List<RuleAssignmentParameter> ruleAssignmentParameter) {
this.ruleAssignmentParameter = ruleAssignmentParameter;
}
public RuleAssUI(){
}
public RuleAssUI(int id,String ruleName){
this.id=id;
this.ruleName=ruleName;
}
}
My container where i store the list value
import java.util.LinkedList;
import java.util.List;
public class RuleListContainer {
private List<RuleAssUI> ruleList = new LinkedList<RuleAssUI>();
public RuleListContainer() {
}
public RuleListContainer(List<RuleAssUI> ruleList) {
this.ruleList = ruleList;
}
public List<RuleAssUI> getRuleList() {
return ruleList;
}
public void setRuleList(List<RuleAssUI> ruleList) {
this.ruleList = ruleList;
}
Controller
#RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(#ModelAttribute("SpringWeb") RuleListContainer ruleListContainer, HttpSession session, ModelMap model) {
ruleListContainer.getRuleList().size();
for (RuleAssUI rul1 : ruleListContainer.getRuleList()) {
System.out.println("Id: " + rul1.getId());
System.out.println("RuleName: " + rul1.getRuleName());
for (RuleAssignmentParameter rul2 : rul1.getRuleAssignmentParameter()) {
System.out.println("ParameterName: " + rul2.getParameterName());
System.out.println("ParameterValue: " + rul2.getOverwriteValue());
}
}
session.setAttribute("ruleListContainer", ruleListContainer);
return "hello";
}
I am trying so many time but unable to fixed the issue, And browse also but did't get any proper help, so please help to do items
I NEED HELP PLEASE SOME BODY HELP ME...!
Thank you in advance
I think the problem is in your jsp file.
You need to set the index of each list element.
<c:forEach items="${List2}" var="as" varStatus="vs">
<tr class="rule">
<td><input type="hidden" name="ruleList[${vs.index}].id" value="${as.rule.id}" /> ${as.rule.id}</td>
<td><input type="hidden" name="ruleList[${vs.index}].ruleName" value="${as.rule.ruleName}" /> ${as.rule.ruleName}</td>
<td> <input id="one" class="datepicker" type="text" name="ruleList[${vs.index}].startDate" size="11" height="0.10"></td>
<td> <input id="two" class="datepicker" type="text" name="ruleList[${vs.index}].endDate" size="11" height="0.10"></td>
<td>
<table border="1">
<c:forEach items="${as.ruleAssignmentParameter}" var="asss" varStatus="assignments">
<tr>
<td><input type="hidden" name="ruleList[${vs.index}].ruleAssignmentParameter[${assignments.index}].parameterName" value="${asss.parameterName}" > ${asss.parameterName}</td>
<td><input type="hidden" name="ruleList[${vs.index}].ruleAssignmentParameter[${assignments.index}].overwriteValue" value="${asss.overwriteValue}" /> ${asss.overwriteValue}</td>
</tr>
</c:forEach>
</table>
</td>
</tr>
</c:forEach>
Also in your controller (POST method) you are trying to get the object identified by "SpringWeb" but should be "ruleListContainer", same name you have in your form tag
The problem was you had a list into RuleAssUI and you was not accesing correctly, you need 2 loops and indexes, one for each list.
Here is the key:
ruleList[${vs.index}].ruleAssignmentParameter[${assignments.index}].parameterName
I am developing an application with AngularJS and Spring MVC. Everything is working fine but my object is going as null to the Spring Controller so it's returning null. I just don`t know how to make the AngularJS populates the object.
I will post the code here.
AngularJS
<%#taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core'%>
<%#taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!doctype html>
<html>
<head>
<title>Settings</title>
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/workflow.css">
<link rel="stylesheet" href="css/upload.css">
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<link rel="shortcut icon" href="images/logo-small.png" />
</head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('formSubmit', []);
app.controller('FormSubmitController', function($scope, $http) {
$scope.formData = {};
$scope.headerText = 'AngularJS Post Form Spring MVC example: Submit below form';
$scope.submit = function() {
var formData = {
"name1" : "nome 1",
"name2" : "nome 2",
"name3" : "nome 3",
};
var response = $http.post('http://localhost:8080/fire-fatca-web/SubmitMock.html', formData); //passing mockForm
response.success(function(data, status, headers, config) {
/* alert('Success!' + JSON.stringify({
data: $scope.formData //used formData model here
}) ); */
$scope.mockForm = data;
$scope.formData.push(data);
});
response.error(function(data, status, headers, config) {
alert("Exception details: " + JSON.stringify({
data: $scope.formData //used formData model here
}));
})
};
});
</script>
<style>
input.ng-invalid {
border: 2px red solid;
}
</style>
<body data-ng-app="formSubmit">
<div class="container">
<div class="col-sm-8 col-sm-offset-2">
<form data-ng-submit="submit()" name="myForm" data-ng-controller="FormSubmitController">
<!-- novalidate prevents HTML5 validation since we will be validating ourselves -->
<table border="1">
<tr>
<td colspan="2">
<label>Name Line 1:</label>
</td>
</tr>
<tr>
<td colspan="2">
<div class="form-group">
<input type="text" name="name1" class="form-control" data-ng-model="formData.name1" required ng-Maxlength="40">
<p ng-show="myForm.name1.$error.required" class="help-block">Name is required.</p>
<p ng-show="myForm.name1.$error.maxlength" class="help-block">Maximum 40 characters</p>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<label>Name Line 2:</label>
</td>
</tr>
<tr>
<td colspan="2">
<div class="form-group">
<input type="text" name="name2" class="form-control" data-ng-model="formData.name2" ng-Maxlength="40">
<p ng-show="myForm.name2.$error.maxlength" class="help-block">Maximum 40 characters</p>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<label>Name Line 3:</label>
</td>
</tr>
<tr>
<td colspan="2">
<div class="form-group">
<input type="text" name="name3" class="form-control" data-ng-model="formData.name3" ng-Maxlength="40">
<p ng-show="myForm.name3.$error.maxlength" class="help-block">Maximum 40 characters</p>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<h4>You submitted below data through post:</h4>
<pre>Form data ={{formData}}</pre>
</td>
</tr>
<tr>
<td colspan="2">
<p>Response: {{mockForm}}</p>
</td>
</tr>
<tr>
<td colspan="2">
<!-- SUBMIT BUTTON -->
<button type="submit" class="btn btn-primary" ng-disabled="myForm.$invalid">Submit</button>
</td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html>
Spring Controller
#Controller
public class MockController {
private Logger log = LoggerFactory.getLogger(MockController.class);
#RequestMapping("/mock")
public String getSettingsPage(){
return "mock";
}
#RequestMapping(value = "/SubmitMock", method = RequestMethod.POST)
public #ResponseBody String getMock(#RequestBody MockForm mockForm){
StringBuilder reponseData = new StringBuilder();
reponseData.append("Name1: "+ mockForm.getName1()+" ");
reponseData.append("Name2: "+ mockForm.getName2()+" ");
reponseData.append("Name3: "+ mockForm.getName3());
log.debug(reponseData.toString());
return reponseData.toString();
}
The return is aways: Name1: null, Name2: null and Name3: null
I know that I need to populate my mockForm with my formData. It was suggested me to do this:
var response = $http.post('http://localhost:8080/fire-fatca-web/SubmitMock.html', {mockform: formData});
But when I use that piece of code above my Controller Stops responding, I don't know why, maybe Sintaxe Error, I have no idea. Any help?
EDIT:
MockForm.java
package com.opessoftware.beans;
public class MockForm {
private String name1;
private String name2;
private String name3;
public String getName1() {
return name1;
}
public void setName1(String name1) {
this.name1 = name1;
}
public String getName2() {
return name2;
}
public void setName2(String name2) {
this.name2 = name2;
}
public String getName3() {
return name3;
}
public void setName3(String name3) {
this.name3 = name3;
}
}
EDIT 2:
Finally I solve the problem. my ng-data-model was formData.name1, formData.name2 and formData.name3. I changed for name1, name2 and name3. Problem solved. Thank you all!
I have got a html page (with Thymeleaf):
<form action="#" th:action="#{/changeme}">
<fieldset>
<table style="width: 500px">
<tr th:each="esfield : ${esfields}">
<td>
<div>
<div class="checkbox">
<input type="checkbox" name="optionsMulti"
th:text="${esfield}" />
</div>
</div>
</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td>
<button type="submit"
class="btn btn-xs btn-primary margin10-right paddingNew"
name="save">Calculate!</button>
</td>
<td></td>
</tr>
</table>
</fieldset>
</form>
When I click Calculate! it goes to my controller
#RequestMapping(value = "/changeme", params = { "save" })
public String save(final ModelMap m) {
m.addAttribute("centers", /*params*/);
return "clustering";
}
I would like to get information about checked boxes in my controller?
How can I do that?
Thank you in advance
You have basically two options :
either you use a different name for each checkbox
or you use spring tag <form:checkbox> instead of native <checkbox>
If you don't posted data will not allow you to know exactly what boxes were actually checked (excepted in cases all and none)
With the approach, you should use in your controller a #ModelAttribute annotated object containing a List<Boolean> and spring will automagically populate it with the values of your checkboxes.
#RequestMapping(value = "/changeme", params = { "save" })
public String save(#ModelAttribute BoxesForm form, final ModelMap m) {
// do what you need with form.getCheckboxes() ...
m.addAttribute("centers", /*params*/);
return "clustering";
}
public class BoxesForm {
List<Boolean> checkboxes;
// getter and setter omitted ...
}