MVC Spring Controller, display dbData in HTML file - java

If I write a Spring MVC Controller, how can I display the DBData in my HTML file.
e.g. I have db.table called Setting and I want to display the IDs from that table in my HTML file as a Dropdown list.
#Controller
public class CustomChannelController {
private Setting setting;
private Diagram diagram;
private Channel channel;
#RequestMapping(value = "/customchannel", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
public #ResponseBody Setting getId() {
return this.setting;
}
<table>
<tr>
<td>
<label class="col-md-12 control-label"> <%=language['UI.reportSetting.channel']%> : </label>
</td>
<td>
<select id="selectReportChannel" class="form-control">
<option value="0" ><%=setting[ID]%></option>
</select>
</td>
</tr>
</table>

Well it depends on how you retrieve data... do you use AJAX calls? Or do you need them when page is loaded?
Let's see the 2 scenarios
Note: in boths scenarios we assume you are returning a list of object like this:
public class Option{
private String value;
private String text;
//getter and setter
}
AJAX CALL: for this I assume we are using JQuery; in this case you will have in your JS or JSP file something like this:
$.ajax({
url : 'customchannel',
dataType : 'json',
contentType : 'application/json; charset=UTF-8',
type : 'GET',
success : function(items) {
$.each(items, function (i, item) {
$('#selectReportChannel').append($('<option>', {
value: item.value,
text : item.text
}));
});
},
error : function(data) {
}
});
<select id="selectReportChannel" class="form-control">
</select>
Page loaded In this case in your controller who will render the HTML page you can do something like this:
#Controller
public class CustomChannelController {
private Setting setting;
private Diagram diagram;
private Channel channel;
#RequestMapping(value = "/customchannel", method = RequestMethod.GET)
public ModelAndView getId(Model uiModel) {
uiModel.add("options", this.setting);
return new ModelAndView("yourPage", uiModel) ;
}
Then in the HTML page you can use JSTL in this way:
<table>
<tr>
<td>
<label class="col-md-12 control-label"> <%=language['UI.reportSetting.channel']%> : </label>
</td>
<td>
<select id="selectReportChannel" class="form-control">
<c:forEach items="${options}" var="option">
<option value="${option.value}">${option.text}</option>
</c:forEach>
</select>
</td>
</tr>
</table>

Ok, I have found a solution. First a need to create a Spring MVC Controller then a Service and link then the Controller to the Backbone model file.

Related

JQuery to update a <c:forEach> in Spring MVC

I сreated a jsp page with the table. I would like to refresh table after click the button using Jquery.
But in result i see two views at the same time. How to avoid this problem ?
My Controller
#Controller
#RequestMapping("/")
public class HelloController {
private final Logger log = LoggerFactory.getLogger(getClass());
#Autowired
private UserServiceDao userServiceDao;
#RequestMapping(method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
model.addAttribute("Message","first");
model.addAttribute("list",userServiceDao.findAll());
log.trace("NUMBER:::::::::::::::::::::"+userServiceDao.findAll().size());
return "main";
}
#RequestMapping("/table")
public ModelAndView renderTable(HttpServletRequest request) {
String name = request.getParameter("nameSearch");
log.trace("1: "+name);
List<User> people = userServiceDao.find(name);
log.trace("2: "+people.size());
return new ModelAndView("main", "list", people);
}
}
MY view with the Jquery script
<body>
<div class="sear">
<input class=" int datasearch" type="search" value="an" id="dataSearch">
<input class="int search" type="button" value="Search" id="search">
<input class="int create" type="button" id="err" value="Create user">
</div>
<h1>List of users: </h1>
<div class="table" >
<c:forEach var="item" items="${list}">
<div class="row" >
<div id="tabl" class="cell" style="width:300px;"><c:out value="${item.name}"/>></div>
<div class="cell" style="width:100px;" ><input class="delete" type="button" value="Delete user"></div>
<div class="cell"><input class="edit" type="button" value="Edit user"></div>
</div>
</c:forEach>
</div>
<script type="text/javascript">
$('#err').click(function(){
window.location.href='/registration';
})
$('#search').click(function(){
$(function() {
var myTableContainer = $("#tabl");
var renderTable = function(container) {
var data = $('#dataSearch').val();
var postReqData = {}; // Create an empty object
postReqData['nameSearch'] = data;
$.get("/table",postReqData, function(data) {
container.empty().html(data);
})
};
/* This is called on document ready */
renderTable(myTableContainer);
/* Use the same renderTable function when the refresh button is clicked */
$("#search").click(function() {
renderTable(myTableContainer);
});
})
})
Ok, this might be a bit too long for comments.
Your main problem is that both #RequestMapping(method = RequestMethod.GET) and #RequestMapping("/table") render the same view.
That is: the view containing all your search inputs, <c:forEach> table and javascript.
So when you do the search and when the ajax call returns, you replace contents of div#tabl with all those search inputs, <c:forEach> and javascript.
You end up with two pieces of everything nested in the wrong way.
My advice would be to do one RequestMapping that renders the basic jsp, and the other one that renders only the search results (or even returns json and render it as html in javascript).

How to get checked boxes in a Controller

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 ...
}

Refreshing the table columns in jsp page on click of refresh button at each row using ajax/javascript

Hi I have a JSP page as below,jsp page contains one table in which i am displaying data by iterating through the list from the action class.
each row of a table has refresh button at row level.jsp is as shown below.
<script type="text/javascript">
function refreshRecord(id)
{
$(document).ready(function(){
var fileId=id;
alert(fileId);
$.ajax({
type:"post",
url:"checkStatusAndNumRecs",
data: {fileId:fileId},
success:function(data){
alert("returned from action");
}
});
});
}
</script>
</head>
<body>
<%#include file="index1.html" %>
<div class="box2">
<div class="box3">
<s:property value="userId"/>
</div>
<center><h2>FILE STATUS</h2></center>
<center>
<form action="Upload" method="post" enctype="multipart/form-data">
<label for="myFile" class="text">Upload your file:</label>
<input type="hidden" name="upload" value="upload"/>
<input type="file" name="myFile" size="40" class="file"/>
<input type="submit" value="Upload" class="button"/>
<input type="submit" value="Refresh" class="button"/>
</form>
</center>
<center>
<table border="1" class="displaytab" id="rtable">
<s:if test="%{user.roles == 'admin'}">
<tr> <td colspan="10" style="background:#7395B8;color:white;font-size:18px;font-weight:bold;"><center>Admin</center></td></tr>
</s:if>
<tr>
<th>FileId</th><th>File Name</th><th>Upload Date</th><th>#Records</th><th>Status</th><th>Estimated Time</th><th>Processed Records</th><th>Generate Report</th><th></th><s:if test="%{user.roles == 'admin'}"><th>Controls</th></s:if>
</tr>
<s:iterator value="uploadList" var="m">
<tr>
<td><s:property value="%{#m.fileId}" /></td>
<td><s:property value="%{#m.fileName}" /></td>
<td><s:property value="%{#m.uploadDate}" /></td>
<td><s:property value="%{#m.numRecords}" /></td>
<td><s:property value="%{#m.status}" /></td>
<td>tbd</td>
<td><s:property value="%{#m.numRecords}" /></td>
<td><img src="images/generate.png" title="Generate Report"> </td>
<td><img src="images/refresh.png" title="Refresh" onclick="refreshRecord(<s:property value="%{#m.fileId}" />);"></td>
</tr>
</s:iterator>
</table>
</center>
at the refresh button onclick i am calling onclick="refreshRecord();"> this javascript method it will go to action class get the latest values of status and # records.
through ajax i am passing this fileId to action class checkStatusAndNumRecsAction.java to get the updated status and #records column values from database
my action class is as below
import com.mxui.db.api.PersistenceService;
import com.mxui.db.service.*;
import com.opensymphony.xwork2.ActionSupport;
public class checkStatusAndNumRecsAction extends ActionSupport
{
/**
*
*/
private static final long serialVersionUID = 6450400234448854648L;
private String status;
public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
private long numRecords;
public long getNumRecords()
{
return numRecords;
}
public void setNumRecords(long numRecords)
{
this.numRecords= numRecords;
}
private String fileId;
public String getFileId()
{
return fileId;
}
public void setFileId(String fileId)
{
this.fileId = fileId;
}
public String execute()
{
PersistenceService svc = PersistenceServiceImpl.getInstance();
status = svc.getStatusByFileId(fileId);
System.out.println("status is "+status);
numRecords = svc.getNumRecordsByFileId(fileId);
System.out.println("num records are "+numRecords);
return "SUCCESS";
}
}
this action get the values of status and #records from database
what i want to do is i should get the values of status and numRecords from action class to jsp using ajax and replace the tables of status and #records column with the new retrieved data from action class.on click of that row refresh button.
In the function defined in success: you will need to write javascript that replaces the contents of the <TD> for the record that has been refreshed. You can identify the <TD> by using the fileId. For example: <td id="%{#m.fileId}"><s:property value="%{#m.status}" /></td> and using jQuery search for this fileId and by using replaceWith substitute the new value of status. For example: $("td#fileId").replaceWith(newStatusData);
Depending of the format of the data returned to the AJAX call you might need to do some parsing in order to extract the data that you want.
EDIT: Just seen your comment. Can you control to format of the data returned to the AJAX call? If so you might like to format in JSON. Although a simple CSV format would be sufficient. Also can you post an example of the data sent back to the AJAX.
You appear to be missing a servlet that recuperates the values from the DB and sends then to the client. In your servlets doPost() method you need to call the methods that return the status of the record and number of records and return them to the client. I imagine servlet code something like this:
#WebServlet(checkStatusAndNumRecs)
class MyServlet extends HttpServlet
protected doPost(HttpServletRequest request, HttpServletResponse)
throws IOException, ServletException{
String fileId = request.getParameter("fileId");
String status = XXXXX.getStatus(fileId);
String numRec = XXXXX.getNumRecords();
String responseTxt = status + "," + numRec;
response.out.println(responseTxt);
response.getWriter().println(responseTxt);
}
XXXXX is the object that encapsulates the calls to the DB to retrieve the values of status and record number.
And also you need to change to jQuery AJAX to something like this:
$.ajax({
type: "post",
url: "checkStatusAndNumRecs",
data: "fileId=" + fileId,
success: function(data){
var rData = data.split(",");
$("td#fileId").replaceWith(rData[0]);
// Do the same for the record number data: rData[1]
}

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

FreeMarker Form for nested Object

I am trying to write freemarker template but could not able to parse with my object class.
My POJO is
public class Metrix {
#Id
String _id;
String loginId;
Date date;
List<MatrixDetail> headers;
//All getters and setters
}
public class MatrixDetail {
String header;
int time;
String detail;
//All getters and setters
}
//Controller after saving form
#RequestMapping(value = "/matrix/save", method = RequestMethod.POST)
public View saveMatrix(#ModelAttribute Metrix matrix, ModelMap model) {
System.out.println("Reachecd in matrix save" );
return new RedirectView("/TrackerApplication/header.html");
}
FTL template form part
<form name="matrix" action="matrix/save.html" method="post">
<table class="datatable" align:"center">
<tr>
<th>Login Id:</th> <th> <input type="text" name="loginId" value= ${matrixList.loginId} required /> </th>
</tr>
<tr> <td></td><td></td><td></td></tr>
<tr>
<th>Header</th> <th>Time</th> <th>Details</th>
</tr>
**// I am not getting how this nested object which is of type List<MatrixDetail>
// will get parse in my form.**
<#list matrixList.headers as header>
<spring:bind path = "MatrixDetail">
<tr>
<td> <input name = "header" value = ${header.header} /> </td>
<td> <input name = "time" value = ${header.time} /> </td>
<td> <input name = "detail" value = ${header.detail} /></td></tr>
</#list>
</table>
<input type="submit" value="Save" />
</form>
How can we write freemarker template for form processing of such kind of nested object?
I am getting issues in form submission.
I would strongly advise against this.
Forms might be displayable in email in some cases, but they may not always work in the email client, not to mention those that only ever read emails in text-only form won't be able to use them whatsoever.
If you need users to enter a form, link to a page on your site and have the form there instead.

Categories