How to display TABLE dynamically in JSP using SPRING MVC - java

I want to create a table dynamically in such a way that no of headers and data i can pass from JAVA class and on no. basis, jsp should create a table accordingly.
I have controller class in which i am returning model object which is my bean class. In that i have a list attribute in which i have hardcoded some values.These values should be by header names in the JSP table.
When i am rendering this model object to jsp then i am not able to retrieve the headers info. Plz suggest.
My contrller class loooks like this:
#RequestMapping
public ModelAndView getHeaders(PortletRequest portlestRequest, PortletResponse portletResponse){
ModelAndView mv = new ModelAndView();
TableDAO dao = new TableDAO();
List<String> headersList = dao.getHeaders();
TableView tableView = new TableView();
tableView.setTableHeaders(headersList);
mv.addObject("tableView",tableView);
mv.setView("tableView");
return mv;
}
My jsp:
<table>
<c:forEach var = "listValue" items = "${tableView.tableHeaders}">
<tr>
<%for(int i = 0;i<5;i++){ %>
<td>
<%=${listValue.get(i)} %>
</td>
<%} %>
</tr>
</c:forEach>
</table>
Someone plz help me on this.

Why are you looking over the list of headers twice? You dont need that scriptlet code.
Since tableView.tableHeaders returns a list of strings, you just need :
<table>
<tr>
<c:forEach var = "listValue" items = "${tableView.tableHeaders}">
<td>
<c:out value="${listValue}"/>
</td>
</c:forEach>
</tr>
</table>

Related

How to delete an elements from a list in spring mvc

In workers.jsp I have:
....
<form action="/workers" id="personForm" method="post" >
<c:forEach items="${page.content}" var="row" varStatus="status">
<tr>
<td><input type="checkbox"/></td>
<td>${row.name}</td>
...
<td>
<input type='image' src='/pages/img/del.png' />
<input type='hidden' name="removeid" value='${row.id}'/>
</td>
</tr>
</c:forEach>
</form>
When I click on input, ${row.id} goes to:
#RequestMapping(value = "/workers", method = RequestMethod.POST)
public ModelAndView getAllByPage(#ModelAttribute("removeid") Long removeid, Model uiModel, Pageable pageable) {
if(removeid!=null) {
userService.remove(removeid);
}
...
}
But removeid in this case is always the first, that was added to the jsp page.
Besides that, how to get the array of ids, using jsp to remove many items?
Help me, please.
You can write 1 separate REST end point for deleting multiple items.
Example:
public List<Long> deleteMultiple(List<Long> toBeDeleted){
deleteService(toBeDeleted);
return toBeDeleted;
}
You can call this End point via AJAX with multiple ides & refresh your page.

Java Spring Thymeleaf DataTable not working

I want to use dandelion datatables with thymeleaf.My html file is below:
<table id="myTableId"
dt:table="true"
dt:url="#{/dataTable}"
dt:serverside="true"
dt:processing="true"
dt:deferLoading="10">
<thead>
<tr>
<th dt:property="id">Id</th>
<th dt:property="name" dt:default="My default value !">name</th>
<th dt:property="state">state</th>
</tr>
</thead>
</table>
Controller :
#RequestMapping(value="/dataTable")
public #ResponseBody DatatablesResponse<ApplicationItem> allAppForTable(#DatatablesParams DatatablesCriterias criterias){
List<Application> appList=service.listApplications();
List<ApplicationItem> aa=new ArrayList<>();
for(Application a:appList){
ApplicationItem ai= new ApplicationItem();
ai.setId(a.getId());
ai.setName(a.getName());
ai.setState(a.getState());
aa.add(ai);
}
Long count=(long)appList.size();
DataSet<ApplicationItem> dataSet=new DataSet<ApplicationItem>(aa, count,null);
return DatatablesResponse.build(dataSet, criterias);
}
But when I enter this page ,table is empty.How can I initialize table when it loading first time.
According to documentation dt:deferLoadgin attribute:
... allows you to instruct DataTables to not make that initial request, rather it will use the data already on the page (no sorting etc will be applied to it).
Try to remove dt:deferLoading="10" attribute from deffinition of table.

How to get value of SelectBox when using AppEngine in Java, JavaScript and HTML

I am trying to create a way of filtering data that is stored within the datastore. The method I am using for this is a mixture of HTML, Javascript and Java Servlets. A form is made that allows data that is input into the Web Application to be sent to the Java Servlet. The Servlet then does the required actions and sends the user back to the page with the updated data. My problem is I have to use a SelectBox within this form that allows the user to select the atribute they wish to filter by, e.g. title, author. When the submit button is pressed, the value of the SelectBox is not sent as a parameter. This means a ERROR 500 appears as there isn't enough parameters to perform the function. I need to:-
Get the value of the SelectBox.
Pass it to the function with the parameter value in a text field. (Almost Completed)
Set the value of idvBook to equal the List that is sent back to the Webb Application.
Firstly, this is how I am creating the form with the SelectBox, TextInput and ButonInput:-
<div class="headline">Filter the DataStore</div>
<div class="info">To view individual records, select the attribute
you'd like to filter by and enter the value you'd like to find. Click
the button to generate the table based on your search criteria.</div>
<script type="text/javascript">
function filter(){
document.filterBooks.action="/get";
var idvBook = document.filterBooks.submit();
}
</script>
<form name="filterBooks">
<table>
<tr>
<td valign="top"><label for="attribute">Attribute</label></td>
<td>
<select id="attributeSelect">
<option value="void">Select Attribute</option>
<option value="id">ID</option>
<option value="title">Title</option>
<option value="author">Author</option>
<option value="publisher">Publisher</option>
</select>
</td>
</tr>
<tr>
<td valign="top"><label for="value">Value</label></td>
<td><input type="text" name="value" id="value"></input></td>
</tr>
<tr>
<td colspan="2" align="right"><input type="submit" value="Filter" onclick="filter()"></td>
</tr>
</table>
</form>
<table>
<tr>
<th>Book ID</th>
<th>Title</th>
<th>Description</th>
<th>Author</th>
<th>Publisher</th>
<th>Publish Date</th>
<th>Remove Book</th>
</tr>
<%
for (Book book : idvBook) {
%>
<tr>
<td><%=book.getId()%></td>
<td><%=book.getTitle()%></td>
<td><%=book.getDescription()%></td>
<td><%=book.getAuthor()%></td>
<td><%=book.getPublisher()%></td>
<td><%=book.getPublishDate()%></td>
<td><a class="done" href="/done?id=<%=book.getId()%>">Remove</a></td>
</tr>
<%
}
%>
</table>
</div>
Once this has been made, it is then placed in the HTML table located below the form (shown in the code above).
This sends the parameters to this servlet:-
public class ServletGetBooks extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse resp) throws IOException
{
resp.setContentType("text/plain");
resp.getWriter().println("Hello, world");
String attribute = request.getParameter("attributeSelect").toString();
String param = request.getParameter("value");
Dao.INSTANCE.getBooks(attribute, param);
resp.sendRedirect("/TodoApplication.jsp");
}
}
You can see another function is ran here. This function looks like this:-
public List<Book> getBooks(String attribute, String param) {
EntityManager em = EMFService.get().createEntityManager();
Query q = null;
if(attribute.equals("id"))
{
q = em.createQuery("select b from Book b where b.id = :id");
q.setParameter("id", param);
}
else if(attribute.equals("title"))
{
q = em.createQuery("select b from Book b where b.title = :title");
q.setParameter("title", param);
}
else if(attribute.equals("author"))
{
q = em.createQuery("select b from Book b where b.author = :author");
q.setParameter("author", param);
}
else if(attribute.equals("publisher"))
{
q = em.createQuery("select b from Book b where b.publisher = :publisher");
q.setParameter("publisher", param);
}
List<Book> books = q.getResultList();
return books;
}
How can i get it so that i can get the value of the SelectBox, run the function and set the result of this to equal idvBook?
EDIT-------------------------------------------------------------------------------------------------
I'll simplify things. I need this within <% ... %> tags:-
List<Book> idvBook = new ArrayList<Book>();
idvBook = dao.getBook("Value in SelectBox","Value in TextInput");
Your select box does not have a name attribute and its value is thus not sent with the form data.

submit onchange using request mapping in spring mvc

Generating a Jasper report depending on the user selected values from drop down (have two drop downs).
JSP:
<form:form name="f" action="${flowExecutionUrl}" modelAttribute="simpleReportSelector">
<table class="search">
<tr><th colspan="3"><fmt:message key="report.someextract"/></th></tr>
<tr>
<td><b><fmt:message key="somereport.sortdate"/></b>
<select id="firstfield" name="localDate" onchange="this.form.reloadPage.value='true';submit()">
<c:forEach var="dl" items="${dateList}">
<c:if test="${dl.selected==false}">
<option value="${dl.itemValue}">${dl.itemLabel}</option>
</c:if>
<c:if test="${dl.selected==true}">
<option selected="selected" value="${dl.itemValue}">${dl.itemLabel}</option>
</c:if>
</c:forEach>
</select>
</td>
<td><input type="hidden" id="reloadPage" name="reloadPage" value=""/></td>
<td><b><fmt:message key="somereport.equipNumber"/></b>
<select id="uld" name="uldNumber">
<c:forEach var="u" items="${uldList}">
<option value="${u.itemValue}">${u.itemLabel}</option>
</c:forEach>
</select>
</td>
</tr>
<tr><td class="right" colspan="3"><button type="submit" name="_eventId_exportReport">Submit</button></td></tr>
<tr class="hide">
<td><input id="submithidden" type="submit" value="submithidden" name="_eventId_submitButton" /></td>
</tr>
</table>
</form:form>
When user selects this particular menu from header, page populates with datelist and uldlist. datelist will be defaulted to today date and uldlist with 'select'. When user selects a previous date or future date, uldlist supposed to populate with different list.
controller:
#Controller
#RequestMapping("/uldReport.do")
public class ULDReport {
#Transactional(readOnly=true)
#RequestMapping(value="/uldReport.do",method = RequestMethod.GET)
public String setupForm(Model model, HttpServletRequest request, HttpServletResponse response) {
//code to populate datelist and uld list(populates using present day)
}
#Transactional(readOnly=true)
#RequestMapping(params={"reloadPage='true'"}, value="/uldReport.do", method = RequestMethod.GET)
public String setUpUld(Model model, HttpServletRequest request, HttpServletResponse response) {
//this should populate the uld list by using the date seelcted by user
}
#Transactional(readOnly=true)
#RequestMapping(params={"reloadPage='false'"}, method = RequestMethod.POST)
public ModelAndView processSubmit(#ModelAttribute SimpleReportSelector simpleReportSelector, Model model, HttpServletRequest request, HttpServletResponse response) throws IOException{
//some code
}
}
First method works good, but when I change the date, app directs to an error page. I think may be something with #RequestMapping, if I remove params from second and third method in controller, app submits with processandsubmit. What am I doing wrong?
This could be happening because of the way the URL is constructed. The fact that the page is loading a blank page means that it can't find anything that matches the criteria you have set up, and so it's silently failing.
For it to work as you expect, chances are you need to have the url formatted something like this:
/uldReport.do?reloadPage=true
or
/uldReport.do/reloadPage/true
depending on your setup.
But the point is that it needs to be in the URL and not a submitted field in your form, which it seems like it is right now.

Return a list using JQuery

I am using the following JQuery, JSP and Controller to return list of cities upon changing the country drop down menu on my app JSP page, yet I think the dataType, success parameters in the JQuery are not correct as I am not getting back the list. So can someone please tell me what I am doing wrong here and how I can get the list of Cities to add them to the cities drop down menu upon changing the Country drop down menu?
Thanks for your time
<script type="text/javascript">
function loadCity(){
var countryData="countryId="+$(country).val();
$.ajax({
type: "POST",
url: "LoadCities.htm",
data:countryData,
dataType: "javascript",
success: function(cities){
loadCities(eval(cities))
}
});
}
function loadCities(citiesLst){
clearCitiesDD();
for(var i=0;i<citiesLst.length;i++){
var city=citiesLst[i];
appendCity(city.id,city.value);
}
}
function clearCitiesDD(){
$('#cityDD').find('option').remove();
}
function appendCity(id,cityName){
$('#cityDD').append($("<option id='"+id+"'>" + cityName + "</option>"));
}
}
</script>
and in my application controller I have the following code:
#RequestMapping(value = "/LoadCities.htm", method = RequestMethod.GET)
public #ResponseBody
List<City> getCityByCountryID(HttpServletRequest request, HttpServletResponse response)
throws Exception {
List<City> list=
icitys.getCitiesByCountry(Long.parseLong(request.getParameter("countryID")));
return list;
}
and in the JSP file I have the following City and country drop down menus:
<tr>
<td align="right">Country</td>
<td align="left">
<select id ="country" name="country" onchange="loadCity()">
<option value="0">--select--</option>
<c:forEach var="countrylst" items="${countriesList}">
<option value="${countrylst.id}">${countrylst.countryName}</option>
</c:forEach>
</select>
</td>
</tr>
<tr>
<td align="right">City</td>
<td align="left">
<select id="cityDD" name="cityDD">
<option value="0">--select--</option>
</select>
</td>
</tr>
Hope you got solution after changing $(country) to $('#country').
One more thing, you put dataType as "javascript" but avail data types are xml, json, script, or html.
Better try with html.
Good luck.
Should
var countryData="countryId="+$(country).val();
not be
var countryData="countryId="+$('#country').val();

Categories