How to display values from controller inside jsp body - java

Currently when I click on Refund button the ${messages} and ${changes} are displayed on the url instead of inside the jsp body.
the url looks like this localhost:8080/name/?messages=Nice+Try%21&changes=Quarters%3A+0+%7C+Nickels%3A+0%0ADimes%3A+0+%7C+Pennies%3A+0
And nothing show up inside the jsp body at all.
I tried c:out value="${changes}", it didn't work.
I have also tried to change requestMethod into POST, no luck.
Blockquote
JSP
<div class='row text-center' id='change-display'>
<div id="change">
${changes} <---- should display the string, but nothing shows up here.
</div>
</div>
<div class='row text-center' id='getChangeButtonDiv'>
<a href="Money/refund">
<button class='btn btn-purchase' type='button' id='refund-button'>
<p>Refund</p> <------- refund button
</button>
</a>
</div>
#RequestMapping(value="/refund", method=RequestMethod.GET)
public String refund(Model model) throws PersistenceException{
BigDecimal zero = new BigDecimal(0);
BigDecimal total = service.calculateInsertedTotal();
int quarterInt=0, dimeInt=0, nickelInt=0, pennyInt=0;
String message="Here is your refund!";
if(total.compareTo(zero) != 1){
message="Nice Try!";
}else{
while(total.compareTo(quarter)==0||total.compareTo(quarter)== 1){
quarterInt ++;
total = total.subtract(quarter);
}
while(total.compareTo(dime)==0||total.compareTo(dime)== 1){
dimeInt ++;
total = total.subtract(dime);
}
while(total.compareTo(nickel)==0||total.compareTo(nickel)== 1){
nickelInt ++;
total = total.subtract(nickel);
}
while(total.compareTo(nickel)==0||total.compareTo(nickel)== 1){
nickelInt ++;
total = total.subtract(nickel);
}
}
String quarterString = "Quarters: "+ quarterInt;
String dimeString = "Dimes: "+ dimeInt;
String nickelString = "Nickels: "+ nickelInt;
String pennyString = "Pennies: "+ pennyInt;
String changes = quarterString + " | " + nickelString
+"\n"+dimeString + " | " + pennyString;
service.removeMoney();
model.addAttribute("messages", message);
model.addAttribute("changes", changes);
return "redirect:/";
}

Actually your attributes are being lost because you are using redirect:/ instead of forward, when you redirect from one request to another one a new http request is created hence the model attached to the old request will be lost which means your attributes messages and changes will be lost too, so to solve this you have to save your attributes inside RedirectAttributes :
#RequestMapping(value="/refund", method=RequestMethod.GET)
public String refund(Model model, RedirectAttributes redirectModel) throws PersistenceException{
//...
redirectModel.addFlashAttribute("messages", message);
redirectModel.addFlashAttribute("changes", changes);
return "redirect:/";
}

Related

How to send data from input id in Form to RequestMapping and PathVariable in Spring?

I'm using Spring to parse data Json when send request and find a phone number by parameter mobilePhoneNumber.
I want to input phone number in text box, and submit data and send to controller by PathVariable parameter to search phone number in JSON data:
this is my format json request:
{
"sessionKey": "2022111723",
"fiCode": "B100000022",
"code": "0011524",
"appNumber": "APPL000000000000999",
"customerNumber": "12345678",
"mobilePhoneNumber": "0988567896"
}
this is my code in JSP:
<form id="insBasicForm" name="insBasicForm" action="${pageContext.request.contextPath}/api/v1/checkPhoneNumber/$mobilePhoneNumber" method="POST">
<input type="text" id="mobilePhoneNumber" name="mobilePhoneNumber" maxlength="10" title="" placeholder="Telephone Number (Mobile- 10 Digits)" class="w100p" />
<input type="submit" name="" value="Check CCP" class="btn">
</form>
this is my class:
#RequestMapping("/api/v1/checkPhoneNumber/{mobilePhoneNumber}")
#ResponseBody
public ResponseEntity<ReturnMessage> checkCCPHistoryCustomerPoint(#PathVariable("mobilePhoneNumber") String mobilePhoneNumber,
#RequestParam Map<String, Object> params, ModelMap model) throws Exception {
ReturnMessage message = new ReturnMessage();
RestTemplate restTemplate = new RestTemplate();
String url = "https://localhost:8080/VR2_REQUEST";
String token = AppConstants.TOKEN;
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
int recordSuccess = 0 , recordFail = 0;
try {
String sessionKey = "2022111723";
String fiCode = "B100000022";
String code = "0011524";
String appNumber = "APPL000000000000999";
String customerNumber = "12345678"; // "customerNumber": "12345678",
// String mobilePhoneNumber = "0988567896"; // "0988567896"
System.out.println("String URL: " + url);
jsonObject.put("sessionKey", sessionKey);
jsonObject.put("fiCode", fiCode);
jsonObject.put("code", code);
jsonObject.put("appNumber", appNumber);
jsonObject.put("customerNumber", customerNumber);
jsonObject.put("mobilePhoneNumber", mobilePhoneNumber);
jsonArray.put(jsonObject);
System.out.println("params -> {}" + jsonObject);
}
catch(HttpClientErrorException exception) {
// TODO Auto-generated catch block
essage.setMessage(e.toString());
e.printStackTrace();
return ResponseEntity.ok(message);
}
}
when i run program, it seem return null value and there is an exception following as:
2022-07-15 15:37:45,839 WARN [org.springframework.web.servlet.PageNotFound] No mapping found for HTTP request with URI [/api/v1/checkPhoneNumber/] in DispatcherServlet with name 'servlet'
So how to send data from input id in Form to RequestMapping and PathVariable ?
Hii I have tried different methods to send data from input to URL but it is not working then I have tried using javascript if you have no restrictions to use js you can do like this but it will work only if you have one data to send so if you use to model the work will be done quickly or you can try like this.
<form id="insBasicForm" name="insBasicForm" method="post">
<input type="text" id="mobilePhoneNumber" name="mobilePhoneNumber" maxlength="10" placeholder="Telephone Number (Mobile- 10 Digits)" class="w100p" />
<input type="button" name="" value="submit" class="btn" onclick="createUrl()">
<script type="text/javascript">
function createUrl(){
let mobilePhoneNumber = document.getElementById("mobilePhoneNumber").value;
window.location = "/api/v1/checkPhoneNumber/"+mobilePhoneNumber;
}
I have tried all the possible ways to get the input value inside form through the PathVariable but it seems to not work.
I assume you already know about this below.
If your requirement is to get the number into the controller, You can directly use #ModelAttribute(mobilePhoneNumber) String mobilePhoneNumber instead of using a path variable and string to fetch the number through #PathVariable.
In this case the
action="${pageContext.request.contextPath}/api/v1/checkPhoneNumber"
and controller will be like
public ResponseEntity<ReturnMessage> checkCCPHistoryCustomerPoint(#ModelAttribute("mobilePhoneNumber") String mobilePhoneNumber,
#RequestParam Map<String, Object> params, ModelMap model) throws Exception
I assume you already know this. Thankyou

How to pass dynamically added textbox to spring MVC controller java

$("#addButton").click(function () {
if(counter > 3){
alert("Only 3 textboxes allowed");
return false;
}
var selectfield = $('#selectcolumnlist option:selected').val();
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv');
newTextBoxDiv.after().html('<input type="text" name="textbox_' + selectfield + '" class="form-control" id="textbox_'+selectfield+'" placeholder="' + selectfield + '" value="" style="width: 400px;"/><input type="button" value="Remove Field" class="remove_this" id="removeid" accessKey="'+selectfield+'"/>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
$('#selectcolumnlist option:selected').remove();
counter++;
});
$("#TextBoxesGroup").on('click', '#removeid', (function() {
var a = $(this).attr('accessKey');
alert(a);
$(this).parent('div').remove();
$('#selectcolumnlist').append(new Option(a,a));
counter--;
}));
Above code is adding a textbox based on the dropdown select option. It can add a maximum of 3 textboxes.
How do I pass this textbox value to spring MVC controller.
It appears that you are using JQuery to build the UI. Assuming that you have a Spring MVC endpoint exposed at POST http://localhost:8080/api/boxes you can use jQuery.ajax() method:
$.ajax({
method: "POST",
url: "http://localhost:8080/api/boxes",
data: { textbox: "value" }
})
.done(function(msg) {
alert("Saved: " + msg);
});

How to put a maximum limit on file amount being uploaded using Spring MVC?

I'm allowing the upload of JPG files in my program. What I want to do is to set a limit of the amount of photos, let's say 15.
So I got the following in my JSP file:
<td class="upload-pic"><input class="file-submit" type="file" name="fileUpload" size="50" multiple="multiple" accept=".jpg"/></td>
And here's a part of my controller. This works fine and I could obviously check here or make the program not to upload if there are more than 15 photos, BUT what I want to do is to send the user a message letting him know that he can't upload more than 15 photos.
#RequestMapping(value = "publish4" ,method = RequestMethod.POST)
public ModelAndView publish4(#Valid #ModelAttribute("fourthPublicationForm") final FourthPublicationForm form, final BindingResult errors,
#RequestParam("type") String type, #RequestParam("operation") String operation , #RequestParam CommonsMultipartFile[] fileUpload) {
if (errors.hasErrors()) {
//return publish4();
}
long userid = us.findByUsername(SecurityContextHolder.getContext().getAuthentication().getName()).getUserId();
Publication aux = ps.create(form.getTitle(), form.getAddress(), operation, form.getPrice(), form.getDescription(),
type, form.getBedrooms(), form.getBathrooms(), form.getFloorSize(), form.getParking(),userid);
if (fileUpload != null && fileUpload.length > 0) {
for (CommonsMultipartFile aFile : fileUpload){
System.out.println("Saving file: " + aFile.getOriginalFilename());
UploadFile uploadFile = new UploadFile();
uploadFile.setId((int) (Math.random()*1000000));
uploadFile.setPublicationId(Long.toString(aux.getPublicationid()));
uploadFile.setData(aFile.getBytes());
final long limit = 20 * 1024 * 1024; //10MB
System.out.println("I'm about to save with id: " + uploadFile.getId());
if(aFile.getSize() < limit && uploadFile.getData().length > 0) {
if(aFile.getOriginalFilename().contains(".jpg")) {
fileUploadImpl.save(uploadFile);
}else {
System.out.println("Sth went wrong with file format");
}
}else {
System.out.println("File is too big or it's empty");
}
}
}
return new ModelAndView("redirect:/meinHaus/home");
}
As you see I declared this in my controller
#Valid #ModelAttribute("fourthPublicationForm") final FourthPublicationForm form
But I'm not sure how to get the amount of files from there and then show a message? Right now that class is empty.
I am not sure I understood the query correctly; if you want to check the number of files uploaded, then in your code, fileUpload.length would give you that. And then send a warning message to your jsp (view) from controller something like this
attributes.addFlashAttribute("errorMsg", "Not more than 15 files allowed!");
Check out this link https://howtodoinjava.com/spring-mvc/spring-mvc-multi-file-upload-example/ (might not open in Chrome) he's done a similar thing but using List of MultipartFile for images instead of an array.
Also, with RequestParam, you can check the size with min and max limits, see this link for String https://www.javaquery.com/2018/02/passing-and-validating-requestparam-in.html. But, I don't know if it will work for an array of objects in your case.

How to reload a JSP with request.getAttribute values

I have this application where i want to populate a text file on the basis of entries entered from user interface.
I chose Struts1 for this and i have been able to complete most of the functionalities.But the part of keeping on populating the
text file on the basis of user entries in my JSP is something i am struggling with. The following are the flow of pages on user interface
1.'Accept user entries' http://www.image-share.com/ijpg-1178-104.html
2.'Ask for scan data on the basis of entries in page1' http://www.image-share.com/ijpg-1178-105.html
3.'Submit after entering the scandata. ' http://www.image-share.com/ijpg-1178-106.html
(I have been able to straighten the null values in the images via session variables. Thanks to Dave)
message is seen with null entries like this Post validation.
My questions is:
What should be used so that there is a scenario that the users enter the Scan Data on page 2 and can continue to enter
more scan data values by falling back on the same JSP . I was thinking on the lines of reloading the page using JavaScript
on the button click. Is it the right approach?
The relevant code for this is
<html:form action="txtwriter">
<% String itemname = (String)session.getAttribute("itemname"); %>
<% String lotnumber = (String)session.getAttribute("lotnumber"); %>
<% String godownname = (String)session.getAttribute("godownname"); %>
<br/>
<% String message = (String)session.getAttribute("message");
session.setAttribute( "theFileName", message ); %>
Filename : <%= message %>
<br/> Item Name :<%= itemname %>
<br/> Lot Number :<%= lotnumber %>
<br/> Godown Name :<%= godownname %>
<br/> <bean:message key="label.scandata"/>
<html:text property="scanData" ></html:text>
<html:errors property="scanData"/>
<br/>
<html:submit/>
/* How should the submit button handle the onClick event so that when the users click
after entering the text.
1. The entered text must be populated in the text file using a different action class. (I have this part working)
2.They must be on the same jsp with the scanData text box cleared waiting for the next user entry into that text
box so that this subsequest entry can also be entered into the text file.
Is there a way i can empty the 'scanData' textbox by accessing it by name inside my action so that i can empty it from my action class?
(I am looking for this answer)
*/
I used this inside the LoginAction.java
HttpSession session = request.getSession();
session.setAttribute("message", textFile);
session.setAttribute("itemname",loginForm.getItemName().trim());
session.setAttribute("lotnumber",loginForm.getLotNumber().trim());
session.setAttribute("godownname",loginForm.getStockGodown().trim());
(Not an answer; refactored but untested code for others trying to help.)
This is a refactored action, making it easier to see what's actually going on; the original code is difficult to reason about. The trim() functionality is moved to action form setters to avoid redundancy.
public class LoginAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
LoginForm loginForm = (LoginForm) form;
if (invalidForm(loginForm)) {
return mapping.findForward("failure");
}
String fileName = createFile(loginForm);
request.setAttribute("message", fileName);
request.setAttribute("itemname", loginForm.getItemName());
request.setAttribute("lotnumber", loginForm.getLotNumber());
request.setAttribute("godownname", loginForm.getStockGodown());
return mapping.findForward("success");
}
private String createFile(LoginForm loginForm) throws IOException {
ServletContext context = getServlet().getServletContext();
String driveName = context.getInitParameter("drive").trim();
String folderName = context.getInitParameter("foldername").trim();
String pathName = driveName + ":/" + folderName;
new File(pathName).mkdirs();
String fileNamePath = pathName + createFileName(loginForm);
ensureFileExists(fileNamePath);
return fileNamePath;
}
private void ensureFileExists(String fileNamePath) throws IOException {
boolean fileExists = new File(fileNamePath).exists();
if (!fileExists) {
File file = new File(fileNamePath);
file.createNewFile();
}
}
private boolean invalidForm(LoginForm loginForm) {
return loginForm.getItemName().equals("")
|| loginForm.getLotNumber().equals("")
|| loginForm.getStockGodown().equals("");
}
private String createFileName(LoginForm loginForm) {
return loginForm.getItemName() + "_"
+ loginForm.getLotNumber() + "_"
+ loginForm.getStockGodown() + "_"
+ createFileNameTimeStamp() + ".txt";
}
private String createFileNameTimeStamp() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd G 'at' hh.mm.ss z");
String dateTime = sdf.format(Calendar.getInstance().getTime());
String[] tempDateStore = dateTime.split("AD at");
return tempDateStore[0].trim() + "_" + tempDateStore[1].trim();
}
}

Generating dynamic checkboxes through servlets?

I am using RestfbApi to fetch my friends' names and display on a web page. I also want a corresponding checkbox to each friend, since from the use of table tag , I have friend's name as well as corresponding checkbox.
As I generated checkboxes dynamically , how to make sure which checkboxes are checked when my app runs. The scenario is if I checked five friends and press post to wall button, a wall should be post to all five friends. I know how to post a wall just want to know how to map user selected friends(checked ones) to java code.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException
{
User user = facebookClient.fetchObject("me", User.class);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>Hello</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1></H1>\n" +
"</BODY></HTML>");
JsonObject accounts = facebookClient.fetchObject("me/friends",JsonObject.class);
JsonArray data = accounts.getJsonArray("data");
for(int i = 0; i < data.length(); i++)
{
String id = data.getJsonObject(i).getString("id");
Double int1 = Double.parseDouble(id);
String strName = data.getJsonObject(i).getString("name");
out.println("<table>");
out.println("<tr><td> <input type='checkbox' name='wahtevername' value='"+int1 +"'>"+strName+" </td></tr>");
out.println("</table>" );
}
}
out.println(docType +"<form method=\"GET\">"+"<input type=\"submit\" value=\"Post to wall\" name=\"option\">"+"</form>");
Use request.gatParameterValues("whatevername") to get an array of the values of selected checkboxes.
(Btw, it would be better to place the html code in JSP. Set the list as request attribute and then use JSTL's <c:forEach> to iterate)

Categories

Resources