JSP not re-instantiating - java

This is an online library website I am trying to make. For advanced search which can take multiple inputs, I start of with an array of all publications then I remove items which don't match the user input. This works fine for the first time, where the array gets shortened to just the correct array. So if someone typed "programming" all of the publications which have programming in their title will be shown. Now, if the user clicks on the "Advance Search" button again on the NavBar (as shown in welcome.jsp) and inputs say "UML" my code will perform a search for UML on the shortened array which contains results for only "programming". I have put a print statement above
SearchResult sr = new SearchResult();
sr.searchContains = publications;
(In control servlet) and it prints for both inputs UML and programming, but it seems to either not create a new array with all publications?
searchResult.jsp:
<c:forEach var="current" items="${sr.searchContains}">
Title: ${current.title}
</c:forEach>
ControllerServlet.java:
if (action.equals("advSearch")) {
SearchResult sr = new SearchResult();
sr.searchContains = publications;
nextPage = "searchResult.jsp";
String titleString = request.getParameter("titleString");
if (!titleString.equals("")){
ArrayList<Publication> toRemove = new ArrayList<Publication>();
for (Publication p : sr.searchContains){
if (!p.title.contains(titleString)){
toRemove.add(p);
}
}
sr.searchContains.removeAll(toRemove);
}
request.getSession().setAttribute("sr", sr);
RequestDispatcher rd = request.getRequestDispatcher("/"+searchResult.jsp);
rd.forward(request, response);
welcome.jsp:
<ul class="nav navbar-nav">
<li class="active">Advance Search <span class="sr-only">(current)</span></li>
</ul>
advancedSearch.jsp:
<form action="controller" method="POST">
<div class="form-group">
<label for="title">Title:</label>
<input type="text" class="form-control" name="titleString">
<input type="hidden" name="action" value="advSearch" />
</div>
<button type="submit" class="btn btn-default">Advanced Search</button>
</form>
SearchResult.jsp:
public class SearchResult {
public ArrayList<Publication> searchContains = new ArrayList<Publication>();
public ArrayList<Publication> getSearchContains (){
return this.searchContains;
}
}

Found the solution, the problem was in controlservlet
SearchResult sr = new SearchResult();
sr.searchContains = publications;
This means sr.searchContains is the same reference as publications, the main array.

Related

Problem while passing binded list of objects in Spring 5

Good Morning,
I am developing a system which can accept multiple object at the same time, technology used are:
Spring 5.2.5.RELEASE For the backend,
Jsp for Front layer.
The main goal is to let the user put 16 (predefined number, so it is not dynamic the lenght of the array) records of a "Delta P" data with only one form.
As the "nome_operatore" and "data_operazione_delta_p" are equal in all the records, they are submitted only ones and then replicated in the controller for all records submitted.
Since now I came out with the subsequent classes following various tutorials here on SO and over the net.
In general, the view is correctly displayed (I scanned the code generated by Spring and it is correct as far as I know) and the GetMapping to display the form page works correctly as well (I debugged to see if some data were not correct, but I found no errors).
The only problem is that when I submit the form, the page freezes and after a while Chrome display an advise saying that is impossibile to load the page.
The server is still running, as the server keeps logging correctly, but the line
logger.info("submitted form to create multiple Delta P data");
is never reached.
No errors are displayed either in Chrome console.
If this is not the correct way to upload multiple items at one time, how this could be done in Spring 5?
EDIT
After investigation I found chrome giving a RESULT_CODE_HUNG error, but on the net I found nothing useful to fix it, only people complaining about "chrome killing pages", can someone explain what this error means at least? I tried to document myself but with no success. The same error shows up also in Edge and Firefox.
List wrapper
package com.entsorgafin.dto;
import com.entsorgafin.model.Dato_delta_p;
import java.util.ArrayList;
import java.util.List;
public class DeltaPListWrapper
{
private List<Dato_delta_p> deltaPList;
public DeltaPListWrapper()
{
this.deltaPList = new ArrayList<>();
}
public List<Dato_delta_p> getDeltaPList()
{
return deltaPList;
}
public void setDeltaPList(List<Dato_delta_p> deltaPList)
{
this.deltaPList = deltaPList;
}
public void add(Dato_delta_p dato_delta_p)
{
this.deltaPList.add(dato_delta_p);
}
}
Controller methods
/**
* Shows the form to insert a new delta p data series in the system.
* <p>
* Returns the form page.
*
* #param model ModelMap of the UI
* #return The form page to insert one record for each sector
*/
#GetMapping("/addDeltaP")
public String addDeltaP(ModelMap model)
{
logger.info("adding Delta P data");
logger.debug("finding infos for front end representation");
//finding users to relate the records with
List<Utente> users = utentiService.findAllUsers();
logger.debug("found " + users.size() + " users");
Map<Integer, String> userForFE = new HashMap<>();
for(Utente utente : users)
{
userForFE.put(utente.getId_utente(), utente.getNome() + " " + utente.getCognome());
}
model.addAttribute("users", userForFE);
//finding active sectors
List<Settore> activeSectors = new ArrayList<>();
activeSectors.addAll(settoriService.findActiveSectorForPhase("act"));
activeSectors.addAll(settoriService.findActiveSectorForPhase("cur"));
logger.debug("found " + activeSectors.size() + " active sectors");
//creating wrapper which contains multiple Delta P records
DeltaPListWrapper listWrapper = new DeltaPListWrapper();
//Pre-filling sector field for delta P data
for(Settore sect : activeSectors)
{
Dato_delta_p dato_delta_p = new Dato_delta_p();
dato_delta_p.setSettore(sect);
listWrapper.add(dato_delta_p);
}
model.addAttribute("deltaPData", listWrapper);
model.addAttribute("activeSectorNumber", activeSectors.size());
return "uploadDeltaPData";
}
/**
* Saves a new series of data record in the database.
*
* #param listWrapper List of Delta p data to create
* #return Returns the homepage
*/
#PostMapping("/addDeltaP")
public String addDeltaP(#ModelAttribute("deltaPData") DeltaPListWrapper listWrapper)
{
logger.info("submitted form to create multiple Delta P data");
/*
getting Date of the first record, operations are performed on the same date, so
every record will have the same property for data_operazione
The same stands for the user who performed the operations
*/
LocalDate dataOperazione = listWrapper.getDeltaPList().get(0).getData_operazione_delta_p();
Utente idUtente = listWrapper.getDeltaPList().get(0).getUtente_id_utente();
/*
Filling delta P data with active batch for the sector they are from
*/
for(Dato_delta_p dato_delta_p : listWrapper.getDeltaPList())
{
dato_delta_p.setUtente_id_utente(idUtente);
dato_delta_p.setData_operazione_delta_p(dataOperazione);
String phase;
Settore used = settoriService.findSectorById(dato_delta_p.getSettore().getId_settore());
if(used.getFase().equals("act"))
{
phase = "act";
} else
{
phase = "cur";
}
Lotto referencedLotto = lottoService
.findActiveBatchInSectorAndDate(dato_delta_p.getData_operazione_delta_p(), dato_delta_p
.getSettore(), phase);
logger.debug("found Lotto with ID " + referencedLotto.getId_lotto() + " for Delta P record");
dato_delta_p.setLotto_id_lotto(referencedLotto);
//creating the data
dati_delta_pService.createDeltaPData(dato_delta_p);
logger.info("Delta P data created correctly");
}
return "redirect:/entsorgafin/home";
}
JSP view
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<jsp:include page="header.jsp"/>
<div class="container">
<h1>Inserisci i dati delta P</h1>
<form:form method="post" modelAttribute="deltaPData" onsubmit="enableFields(${activeSectorNumber})">
<div class="row">
<div class="form-group col">
<label for="utente_id_utente">Nome dell'operatore</label>
<form:select class="form-control" id="utente_id_utente" path="${deltaPList[0].utente_id_utente.id_utente}" required="required">
<form:option value="" />
<form:options items="${users}" />
</form:select>
</div>
<div class="form-group col">
<label for="data_operazione_delta_p">Data dell'operazione</label>
<form:input path="${deltaPList[0].data_operazione_delta_p}" type="date" class="form-control" id="data_operazione_delta_p" required="required" />
</div>
</div>
<div class="row text-center">
<div class="col my-auto">Numero del settore</div>
<div class="col my-auto">Valore deltaP rilevato</div>
<div class="col my-auto">Velocità ventilatore</div>
<div class="col my-auto">Settore pieno</div>
<div class="col my-auto">Settore in caricamento</div>
</div>
<c:forEach items="${deltaPData.deltaPList}" varStatus="i">
<form:input path="deltaPList[${i.index}].id_dato_delta_p" type="hidden" id="id_dati_delta_p" />
<div class="row text-center">
<div class="form-group col">
<form:input path="deltaPList[${i.index}].settore.id_settore" class="form-control text-center" id="settore${i.index}" required="required" disabled="true"/>
</div>
<div class="form-group col">
<form:input path="deltaPList[${i.index}].valore_delta_p" type="number" step="0.01" class="form-control" id="valore_delta_p" required="required" />
</div>
<div class="form-group col">
<form:input path="deltaPList[${i.index}].velocita_ventilatore" type="number" step="0.01" class="form-control" id="velocita_ventilatore" required="required" />
</div>
<div class="form-group col my-auto">
<form:checkbox path="deltaPList[${i.index}].stato_settore_pieno" id="stato_settore_pieno${i.index}" value="true" onclick="disableSettoreCaricoBox(${i.index})"/>
</div>
<div class="form-group col my-auto">
<form:checkbox path="deltaPList[${i.index}].stato_settore_carico" id="stato_settore_carico${i.index}" value="true" onclick="disableSettorePienoBox(${i.index})"/>
</div>
</div>
</c:forEach>
<input type="submit" value="create" class="btn btn-primary btn-sm">
</form:form>
</div>
<jsp:include page="footer.jsp"/>
<script>
function disableSettoreCaricoBox(i)
{
const checked = document.getElementById('stato_settore_pieno' + i).checked;
document.getElementById("stato_settore_carico" + i).disabled = !!checked;
}
function disableSettorePienoBox(i)
{
const checked = document.getElementById('stato_settore_carico' + i).checked;
document.getElementById("stato_settore_pieno" + i).disabled = !!checked;
}
function enableFields(i)
{
for(let x = 0; x < i; x++)
{
document.getElementById("settore" + x).disabled = false;
}
}
</script>
I actually feel kind of an idiot for not noticing it before, after focusing on Spring possible errors I lost a minor point in the code where the error actually is: Javascript function.
function enableFields(i)
{
for(let x = 0; x < i; i++)
{
document.getElementById("settore" + x).disabled = false;
}
}
should be
function enableFields(i)
{
for(let x = 0; x < i; x++)
{
document.getElementById("settore" + x).disabled = false;
}
}
I'll correct the quetion code, hope this could anyway help someone who's searching an example of multi row submitting in Spring 5.

In Spring Boot Thymeleaf , how to pass list of object to th:value ??? I would like to create tag input

Here is my form html
<div class="card-body">
<form action="#{/orgCategoryTag/create}" method="POST">
<div class="form-group">
<label for="form-tags-1" class="text-dark font-bold">Add new tags</label>
<input id="form-tags-1" name="tags-1" type="text" th:value="${tags}">
</div>
<a
type="button"
class="btn btn-success" href="#"
data-placement="top" title="Tooltip on top">Add
</a>
</form>
</div>
Here is Get mapping for rendering form
#GetMapping(value = "/form")
public String categoryForm(Model model, BindingResult result) {
Long testId = (long)1;
OrgCategory orgCategory = new OrgCategory();
List<OrgCategoryTagModel> orgCategoryTags = orgCategoryTagRestController.getAllByCategoryId(testId);
model.addAttribute("category", orgCategory);
model.addAttribute("tags", orgCategoryTags);
model.addAttribute("add", true);
return "orgCategoryForm";
}
For displaying a list of options (tags in your context), please use a combo-box, they are better suited to display a list of options.
<select>
<option
th:each="tag: ${tags}"
th:text="${tag.name}"
th:value="${tag.id}"
/>
</select>
<select> is the tag for creating a combobox and <option> are the different options available in the combobox. I have used a for each loop to create different options for the combobox where tag represents your object OrgCategoryTagModel.
I do not know your object OrgCategoryTagModel, but I am assuming you want to display the name of the tag (tag.name) and use the id of OrgCategoryTagModel (tag.id) as the value to be saved when making a selection.

I am not able to get the value form JSP page to Controller Class on Submit

This code is wriiten in Liferay 6.1 platform.
Description: I have one drop down menu by name "Store Name". I will select any one of the value from drop down and pass that value to javascript function "getStoreDetails" onchange. The sent value from this function will be checked in the javascript array "lNames", If value is present in this array then index will be obtained and using index we obtain value from "fNames" array and add to span class "FirstName". I am able to do this and code is working fine.
Problem:I am not able to get FirstName value from jsp file to Controller Class of submitIssue method.
This is my Controller class
public class IssueController{
public String handleRenderRequest(RenderRequest request, RenderResponse response, Model model) throws Exception {
HttpServletRequest httpRequest = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(request));
User user = PortalUtil.getUser(httpRequest);
model.addAttribute("my_user", user);
/*Some code goes here to set user attributes like department and organization using model object */
return "issue"; /*This is my jsp file mentioned below*/
}
#ActionMapping
public void submitIssue(#ModelAttribute IssueForm submitIssueForm, ActionRequest request, ActionResponse response) throws PortalException, SystemException, IOException, PortletException {
String First_Name=request.getParameter("FirstName");
System.out.println("First Name while submitting is :\t"+First_Name);
/* here i am not able to obtain value of First_Name */
}
}
The below code is my issue.jsp file
<div class="large-4 medium-8 small-12 columns">
Store Name <select
class="no-highlight" id="StoreName_dropdown"
name="storeName"
onchange="getStoreDetails(this.value);"
<%
String stores[] = new String[] {"1021","1022","1023","1024","1025","1026","1027","1028","1029","1030"};
for(int i=0;i<stores.length;i++){%>
<option value="<%=stores[i]%>"><%=stores[i]%></option>
<%}%>
</select>
</div>
<%
String fNames[] = new String[] {"John1021","wilson1022","test1023","test1024","test1025","test1026","test1027","test1028","test1029","test1030"};
StringBuffer bufferfNames = new StringBuffer();
bufferfNames.append("[");
for(int i=0; i<fNames.length; i++){
bufferfNames.append("\"").append(fNames[i]).append("\"");
if(i+1 < fNames.length){
bufferfNames.append(",");
}
}
bufferfNames.append("]");
String First_Name=bufferfNames.toString();
String lNames[] = new String[] {"1021","1022","1023","1024","1025","1026","1027","1028","1029","1030"};
StringBuffer bufferlNames = new StringBuffer();
bufferlNames.append("[");
for(int i=0; i<lNames.length; i++){
bufferlNames.append("\"").append(lNames[i]).append("\"");
if(i+1 < lNames.length){
bufferlNames.append(",");
}
}
bufferlNames.append("]");
String Last_Name=bufferlNames.toString();
%>
<div class="row ">
<div class="large-3 medium-4 columns">
<span class="firstName">First Name : <span
class="hide-for-medium-up"><b>"dynamically name added"</b></span></span>
<div class="hide-for-small" id="FirstName" >
<b>"dynamically name added"</b>
</div>
</div>
</div>
<div class="row ">
<div class="large-2 medium-3 columns">
<button class="submitIssue submit_button"
id="submitIssue" tabIndex=9>
Submit
</button>
</div>
</div>
<script>
function getStoreDetails(store) {
var fNames=<%=First_Name%>;
var lNames=<%=Last_Name%>;
var index;
index=lNames.indexOf(store);
if (index > -1) {
document.getElementById("FirstName").innerHTML = fNames[index];
}
else{
alert("Store is not present in lNames !!");
}
}
</script>
My javascript program in separate file submitIssue.js
$( document ).ready(function() {
$('button.submitIssue').click(function(){
$('#submitIssueForm').submit();
});
});
Can anyone suggest me to get this value. Please comment in case if you have not understood my problem statement. thanks in advance.
Are you able to see "FirstName" printed in your jsp? If yes, you need to pass this value in input tag, so that you can expect this value to come in your controller. Hope this helps!!

Javascript: Form element values to a Collection

I have a HTML page with dinamycally changing number of select elements.
<script>
function getValues() {
var selects = document.getElementsByTagName('select'),
arr = Array.prototype.slice.call(selects),
selectValues = arr.map(function (select) {
return select.value;
});
return selectValues;
}
</script>
<script type='text/javascript'>
function moreSelect() {
for (i = 0; i < number; i++) {
// Append a node with a random text
container.appendChild(document.createTextNode("Name " + (i+1) + ": "));
// Create an <input> element, set its type and name attributes
var input = document.createElement("select");
input.name = "name" + (i+1);
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement("br"));
}
</script>
<form action="action"method="POST" onsubmit="return getValues;">
More selects (max. 9):<br>
<p>
<input type="number" id="name" name="name" value="0"
min="0" max="9"><br />
<button type="button" onclick="moreSelect()">Add</button>
<br>
<p>
<br>
<div id="container" /></div>
<p>
<br> <br> <input type="submit" value="Go">
</form>
I want to collect this values to a List or an Array before the POST method and give this parameter list to my Java controller like this:
#RequestParam("allValues") List<String> allValues
Edit: I edited it, but doesn't works.
Get all selects, transform them to a real Array by Array.prototype.slice. Now you can use map to get all values. getElementsByTagName returns a HTMLCollection, that does not support map(), etc.
var selects = document.getElementsByTagName('select'),
arr = Array.prototype.slice.call(selects),
selectValues = arr.map(function (select) {
return select.value;
});
Now selectValues is an Array of the select values.
You can add one hidden form parameter say with name "allValues" and using javascript before posting Form, you can add all select values in that parameter.

jsp fill in field on dropdown item changed

I'm trying to make it so that when an option from the combobox is selected it fills out some of the later input fields. current code (below) doesnt give anny errors just simply does not give output on item changed.
my question being how can I make it so that when selected item changes it fills in some fields.
<div>
options:<select id="optionbox" onchange="Change()">
<option value="op1">option1</option>
<option value="op2">option2</option></select><br>
<form action="KlusServlet.do" method="post"> //not relevant i think used for servlets later on
<input id="description" type="text"></input>
</form>
<script type="text/javascript">
function Change() {
var e = document.getElementById("optionbox");
var selOption = e.options[e.selectedIndex].value;
document.getElementById("description").innerHTML = "selected: " + selOption;
}
</script>
</div>
for textboxes you need to use .value not innerHTML like below
document.getElementById("description").value = "selected: " + selOption;
you can use jquery code $('#selector').val(value); for that
Working Code
<div>
options:<select id="optionbox" onchange="Change()">
<option value="op1">option1</option>
<option value="op2">option2</option></select><br>
<form action="KlusServlet.do" method="post"> //not relevant i think used for servlets later on
<input id="description" type="text"></input>
</form>
<script type="text/javascript">
function Change() {
var e = document.getElementById("optionbox");
var selOption = document.getElementById("optionbox").value;
alert(selOption);
$('#description').val(selOption);
}
</script>
</div>

Categories

Resources