how to get some value from url using jstl - java

I have two forms those have same-url for action, the following form is on page http://www.domain.com/pre-foo-url, which is
<form:form commandName="some" class="form" action="/app/same-url">
<form:input path="title"/>
<input type="hidden" name="redirect" value="foo"/>
<button>OK</button>
</form:form>
and the other form is on http://www.domain.com/bar/{id}
<form:form commandName="some" class="form" action="/app/same-url">
<form:input path="tile"/>
<input type="hidden" name="redirect" value="bar"/>
<button>OK</button>
</form:form>
two methods in my controller, one for deciding to redirect to
#RequestMapping(value = "/same-url", method = RequestMethod.POST)
public String handleRedirect(#RequestParam("redirect") String redirect) {
if (redirect.equals("foo")) {
return "redirect:/foo";
} else {
return "redirect:/bar/{id}"; // this {id} must get the value from http://www.domain.com/bar/{id}<-- Here
}
}
other method for getting the value of id from return "redirect:/bar/{id}"; and goto /bar/{id} request mapping
#RequestMapping(value = "/bar/{id}", method = RequestMethod.GET)
public String handleBar(#PathVariable Integer id) {
// some logic here
return "go-any-where";
}
Now how can I get value from http://www.domain.com/bar/{id} and set that when I redirect it to redirect:/bar/{id},

I have a solution for your need, first I must point out your need then I will write my answer.
First:
-You need to get the /{id} from http://www.domain.com/bar/{id}, it means you want to get the value of last part of url.
you can get that value adding following code on page http://www.domain.com/bar/{id}
<c:set var="currentPage" value="${requestScope['javax.servlet.forward.request_uri']}"/> <!--This will give you the path to current page eg- http://www.domain.com/bar/360 -->
<c:set var="splitURI" value="${fn:split(currentPage, '/')}"/> <!--This will split the path of current page -->
<c:set var="lastValue" value="${splitURI[fn:length(splitURI)-1]}"/><!--This will give you the last value of url "360" in this case -->
<c:out value="${lastValue}"></c:out> <!--use this to make sure you are getting correct value(for testing only) -->
Scond:
-You have to pass value of /{id} which is got from http://www.domain.com/bar/{id}.
pass this using the form as.
<form:form commandName="some" class="form" action="/app/same-url">
<form:input path="title"/>
<input type="hidden" name="redirect" value="bar"/>
<input type="hidden" name="path-var" value="${lastValue}"/>
<button>OK</button>
<form:form>
At Last:
-You want to be redirected to redirect:/bar/{id}".
this could be done using the method below.
#RequestMapping(value = "/add-category", method = RequestMethod.POST)
public String handleRedirect(#RequestParam("redirect") String redirect, #RequestParam("path-var") String pathVar) {
if (redirect.equals("foo")) {
return "redirect:/foo";
} else {
return "redirect:/bar/" + pathVar;
}
}
Important
This is not the Last/Best solution for the problem above.
there may be other/better solutions to this one.
Add this tag lib <%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>, when using any jstl function just as fn:length().
Hope this will work for you.

Related

Is it possible to have an input path for variables in Thymeleaf

I know the title might be misleading but here my question: In Thymeleaf we set request params with the input (in HTML). Is it possible to have an input field that sets the path variable. For example I have an method like this:
#PostMapping("/house/{id}/rent")
public String rentHouse(#RequestParam Date startDate, #PathVariable("id") long id, Model model) {
House h = new House();
h.setId(id);
r.setStartDate(startDate);
Rents rents = rentsService.createNewRent(h, id);
model.addAttribute("rent", rents);
return "House";
}
And in House.html I want something like this:
<form th:action="#{/house/${id}/rent/}" method="post">
<label for="startDate">start Date:</label><br>
<input type="datetime-local" id="startDate" th:name="startDate" placeholder="startDate"><br>
<label for="id">house id:</label><br>
<input type="number" id="id" th:name="id" placeholder="id"><br>
<br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
So that when I input something then the result url should be looking like this (I know start Date has false format):
localhost:8080/House/12/rents?startDate=02.21.22
And is it also possible to pass request body in Thymeleaf, I searched for similar questions but they all solved it by manually putting the path variable in the url.
Thanks in advance

java httpservlet getparameter from html returning null

I am running a .jsp file on a server and trying to send user input form data to the "doPost" method in the HttpServlet.
When I try to print the vals of user input in doPost, they are null.
I am trying to get the vals by their html ID, but that's not working for some reason. There could be a simple issue in the HTML.
The submit button seems to be working as it is routing properly back to the .java file I am trying to parse the user input data with. It is only the vals that are null.
Here is my code.
Thank you! :)
<%#page import="java.util.Date"%>
<%# page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Binary Encoder</title>
</head>
<body>
<h2>Binary Encoding: Encode any number from 0 to 65535</h2> <br>
<h3>Date=<%= new Date() %>
</h3>
<!-- in this form I need to figure out how to get user input into Binaryencoder.java-->
<form action="../Binaryencoder" method="post">
Input number you want to encode (0 to 65536):<br>
<input type="number" id="toencode"><br>
Input first number for encoding (0 to 255) :<br>
<input type="number" id="mask1"><br><br>
Input second number for encoding (0 to 255) :<br>
<input type="number" id="mask2"><br><br>
<input type="submit" id="submit" value="Submit">
</form>
</body>
</html>
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
//code to process the form...
String toencode = request.getParameter("toencode");
String mask1 = request.getParameter("mask1");
String mask2 = request.getParameter("mask2");
//response is the thing that goes back to HTML page
PrintWriter out = response.getWriter();
String output = String.format("Number to encode is: %s", toencode);
String op1 = String.format("Mask1 is: %s", mask1);
String op2 = String.format("Mask2 is: %s", mask2);
out.println(output);
out.println(op1);
out.println(op2);
}
The issue is with these tags, e.g.,: <input type="number" id="toencode"> The tag needs a name attribute, like this: name="mynumber"
The servlet receives the name-value pairs of the request parameters from the JSP. In your JSP the name is missing. The correct way to code your JSP is: <input type="number" id="toencode" name="mynumber">
In the servlet program access the posted parameter and its value as follows in the doPost method:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String myNumber = request.getParameter("mynumber");
getServletContext().log("# My Number: " + myNumber); // this prints in the log file
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("My Number: " + myNumber); // this prints on the browser page
}
This should show the number you had entered in the JSP in the browser page, like: My Number: 999. You can also refer the server logs.
Add name attribute to your input like below:
<input type="number" name="toencode" id="toencode">
<input type="number" name="mask1" id="mask1">
<input type="number" name="mask2" id="mask2">
request.getParameter does not recognize id attributes.
The type of three input should be text, not number . try it.
In the three form input fields, use the name attribute instead of or in addition to id. Only the values of these input fields are included in the request as parameters.
Your form seems to be missing the name attribute for all the fields.
Try changing this:
<input type="number" id="toencode">
to this (adding the name attribute to the toencode field):
<input type="number" id="toencode" name="toencode">
Obviously, for the other fields (mask1, mask2) the names value would be matching their ids

Set a checkbox in Javascript dynamically

Can someone please tell me how to set a checkbox dynamically in Javascript?
function displayResults(html){
var v = html.split(",");
document.getElementById('fsystemName').value = v[0];
if (v[1] == "true"){
document.getElementById('fUpdateActiveFlag').checked = true;
}
}
So I am passing some values from my controller separated by commas. For the checkbox, when the value is true I want it to tick the box.
EDIT:
When a value is changed from a dropdown box it calls this displayResults method as its return statement:
$('#uINewsSystemList').change(function() {
$.get("/live-application/SystemById", {systemid: $("#systemList").val()}, displayResults, "html");
I want it to update some other values such as textboxes and checkboxes. I can get the fsystemName to populate with the appropriate value but the fUpdateActiveFlag always stays unchecked.
In your question, you posted a javascript example, not JSP.
In JSP you can use a for loop to write the checkbox like this:
<% for (Element element : elementList) { %>
<input type="checkbox" name="<%=element.getName() %>" value="<%=element.getValue() %>" <%=element.getChecked() ? "checked" : "" %> />
<% } %>
Will result in:
<input type="checkbox" name="option1" value="Milk"> Milk<br>
<input type="checkbox" name="option2" value="Butter" checked> Butter<br>
<input type="checkbox" name="option3" value="Cheese"> Cheese<br>

POST array of values to java servlet

I want to place the following form:
<input type="hidden" name="MPK[]" value="x" class="MPK"/>
<input type="hidden" name="MPK[]" value="y" class="MPK"/>
<input type="hidden" name="MPK[]" value="z" class="MPK"/>
...
and POST it to servlet or JSP page.
How to get values of these inputs in one array in servlet?
request.getParameterValues("MPK");
doesn't work even if i remove [] from names.
You have to get the values from array by parsing it.
String[] mpk;
mpk= request.getParameterValues("mpk");
for(int i = 0; i < mpk.length; i++)
{
System.out.println(mpk[i]);
}
Remove "[]" from you parameter name.
e.g.
<input type="hidden" name="MPK" value="x" class="MPK"/>

Change Value Of A Field On Submit Using Javascript

I would like to add some JavaScript to do the following.
I would have 3 fields like this.
<input type="text" name="a" />
<input type="text" name="b" />
<input type="hidden" name="c" />
say if I entered 100 in the first field and 19 in the second field.
it would divide 100 by 19 and round it up to no decimal places, and then replace the value of the third hidden field by the answer, so in the case it would be (100/19) 5.26... rounded up to 6
however I am not sure how to actually implement this.
Say your form looks like this;
<form id="myForm" method="POST">
<input type="text" name="a" />
<input type="text" name="b" />
<input type="hidden" name="c" />
</form>
You can access the form like this;
function doAction(action)
{
var frm = document.forms.myForm;
frm.c.value = frm.a.value/frm.b.value;
}
You can trigger the action by adding a button that can be clicked, or setting the form's submit action.
Edit: Doesn't round up, not sure how to do that :(
A nice easy method is to pass the form to a function, and allow that function to do the calculation.
The form should look like:
<form>
<input type="text" name="a" />
<input type="text" name="b" />
<input type="hidden" name="c" />
<input type="button" value="Click" onClick="doCalculate(this.form)" />
</form>
and the javascript:
function doCalculate(theForm){
var aVal = parseFloat(theForm.a.value);
var bVal = parseFloat(theForm.b.value);
var cVal = 0;
if(!isNaN(aVal) && !isNaN(bVal)){
cVal = Math.ceil(aVal/bVal);
}
theForm.c.value = cVal;
}
Working example here --> http://jsfiddle.net/azajs/
Edit: This can also be done when the form is submitting by having a similar call in the onsubmit of the form:
<form onsubmit="doCalculate(this);" >
...
</form>
A dumbed-down way, which assumes your form is document.forms[0]:
<input type="text" name="a" onchange="myFunction" />
<input type="text" name="b" onchange="myFunction" />
<input type="hidden" name="c" />
function myFunction() {
var inpA = document.forms[0].a;
var inpB = document.forms[0].b;
var aVal = parseFloat(inpA.value);
var bVal = parseFloat(inpB.value);
if (!isNaN(aVal) && !isNaN(bVal) && bVal !== 0) {
document.forms[0].c.value = Math.ceil(aVal/ bVal);
}
}
EDIT: Math.round => Math.ceil
After the form elements:
<script type="text/javascript">
(function() {
var a= document.getElementsByName('a')[0];
var b= document.getElementsByName('b')[0];
var c= document.getElementsByName('c')[0];
a.onchange=b.onchange=a.onkeyup=b.onkeyup= function() {
c.value= Math.ceil(a.value/b.value);
};
})();
</script>
This recalculates on each key press, remove the keyup binding if you don't want that.
Add a unique id to each input and use document.getElementById to avoid any ambiguity with name. If this form is never going to be submitted you can omit name entirely.
Math.ceil() will return NaN if either value cannot be read as a number, or Infinity if you divide by zero. You may wish to check for these conditions and write a different value.
You do this by binding an eventlistner to the from element. You either create your own (Javascript native event handlers) or use your favorit javascript framework. My example is for using the jQuery jQuery bind method javascript framework.
/* first set and id to your input hidden and form element so you can reach it in fast way */
<form id="myForm"><input type="hidden" id="total" name="c" /></form>
/* Javascript code using jquery */
$('#form').bind('submit', function () {
$('#total').val(function () {
var num = parseFloat($('#form input[name=a]').val()) / parseFloat($('#form input[name=b]').val());
return Math.floor(num) === num ? num : Math.floor(num) + 1;
});
});

Categories

Resources