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
Related
I obviously am missing something here. I have a web app where the input for a form may be in English or, after a keyboard switch, Russian. The meta tag for the page is specifying that the page is UTF-8. That does not seem to matter.
If I type in "вв", two of the unicode character: CYRILLIC SMALL LETTER VE
What do I get? A string. I call getCodePoints().toArray() and I get:
[208, 178, 208, 178]
If I call chars().toArray[], I get the same.
What the heck?
I am completely in control of the web page, but of course there will be different browsers. But how can I get something back from the web page that will let me get the proper cyrillic characters?
This is on java 1.8.0_312. I can upgrade some, but not all the way to the latest java.
The page is this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title>Cards</title>
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity = "sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin = "anonymous" />
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity = "sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin = "anonymous" />
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity = "sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin = "anonymous">
</script>
<meta http-equiv = "Content-Type" content = "text/html; charset=UTF-8" />
<style>.table-nonfluid { width: auto !important; }</style>
</head>
<body>
<div style = "padding: 25px 25px 25px 25px;">
<h2 align = "center">Cards</h2>
<div style = "white-space: nowrap;">
Home
<div>
<form name="f_3_1" method="post" action="/cgi-bin/WebObjects/app.woa/wo/ee67KCNaHEiW1WdpdA8JIM/2.3.1">
<table class = "table" border = "1" style = "max-width: 50%; font-size: 300%; text-align: center;">
<tr>
<td>to go</td>
</tr>
<tr>
<td><input size="25" type="text" name="3.1.5.3.3" /></td>
</tr>
<td>
<input type="submit" value="Submit" name="3.1.5.3.5" /> Skip
</td>
</table>
<input type="hidden" name="wosid" value="ee67KCNaHEiW1WdpdA8JIM" />
</form>
</div>
</div>
</div>
</body>
</html>
Hm. Well, here is at least part of the story.
I have this code:
System.out.println("start: " + start);
int[] points = start.chars().toArray();
byte[] next = new byte[points.length];
int idx = 0;
System.out.print("fixed: ");
for (int p : points) {
next[idx] = (byte)(p & 0xff);
System.out.print(Integer.toHexString(next[idx]) + " ");
idx++;
}
System.out.println("");
The output is:
start: вв
fixed: ffffffd0 ffffffb2 ffffffd0 ffffffb2
And the UTF-8 value for "В", in hex, is d0b2.
So, there it is. The question is, why is this not more easily accessible? Do I really have to put this together byte-pair by byte-pair?
If the string is already in UTF-8, as I think we can see it is, why does the codePoints() method not give us, you know, the codePoints?
Ok, so now I do:
new String(next, StandardCharsets.UTF_8);
and I get the proper string. But it still seems strange that codePoints() gives me an IntStream, but if you use these things as int values, it is broken.
It was a problem with the frameworks I was using. I thought I was setting the request and response content type to utf-8 but I was not.
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.
I am developing a web application in which I which I have a JavaScript array and I want this array in my JSP page and iterate it save the data in database.
var value = response;
for (var key in value) {
if (value.hasOwnProperty(key)) {
alert(key + " -> " + value[key]);
var sample = new Array();
sample=value[key];
console.log(sample);
// document.getElementById('');
}
}
});
I want this data on my JSP page is it possible. If it is possible, then how?
You can have javascript in jsp but that will always execute on client side. So if you want to save some stuff on trigger of some event inside browser you can do that by making ajax call or form submission. Ajax is preferred way because its faster and better experience for user
But if you have intention of execution of javascript on server side thats not possible
Java script client side script whereas jsp is server side script so you can't simply do this.
What you can do is submit the calculated variable from javascript to server by form-submission, or using URL parameter or using AJAX calls and then you can make it available on server to store in database.
Client Side:
<script type="text/javascript">
var n = document.getElementById("data");
var f=new Array( "apple", "orange", "mango" );
n.value = f;
</script>
<form action="Your_JSP.jsp" method="POST">
<input type="hidden" id="data" name="data" value="" />
<input type="submit" />
</form>
Server Side:
<%
String val = request.getParameter("data");
String aa[]=val.split(",");
for(String x : aa )
out.println(x);
//now hereyou can use aa array tostore in database or do whatever you want
%>
Try this if you have two different jsp:
first.jsp
<script>
var response = [];
...
var put = function(form) {
form.resp.value = response.join(','); //using comma as separator
};
</script>
<form onsubmit='put(this)' method='next.jsp' method='post'>
<input type='hidden' name='resp' />
<button>Submit</button>
</form>
next.jsp
<%
String[] resp = request.getParameter("resp").split(",");
%>
Response is: ${param.resp} <!-- debugging -->
yes , its possible to do that. you can show array in HTML tag
<!DOCTYPE html>
<html>
<head>
<script>
var value=response;
for (var key in value) {
if (value.hasOwnProperty(key)) {
alert(key + " -> " + value[key]);
var sample = new Array();
sample=value[key];
console.log(sample);
// do here as
document.getElementById("array").innerHTML = sample;
// here array is <p> tag in html and sample is array which will be shown in jsp page.
}
}
</script>
</head>
<body>
<form action="get.jsp" method="POST">
<p id="array" name="array" type="hidden"></p>
<input type="submit" />
</body>
</html>
in get.jsp you will able to get value from array as:
<%
String []array = request.getParameter("array").split(",");
//this String array you can use to store data in DB
%>
This question already has answers here:
Generate an HTML Response in a Java Servlet
(3 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I want to pass some parameters from my java servlet to my html form to be shown. I have read some things about jsp but I was wondering if I can do it directly, using something like this :
<script> var temp = "${param['CookieServlet0.First_Name']}"; </script>
<input type = "text" name = "First_Name" id = "First_Name" value = "temp" > <br>
where First_Name is a parameter of my servlet CookieServlet0. I know that the code example is wrong, is there a way to fix it so that I won't have to use jsp?
EDIT : ok since there is no way around I am starting with jsp, I've checked what you guys sent about JSTL and I do not need the extras that it offers so I am trying to keep it simple since I am just starting. So I have written the code below but I get java.lang.NullPointerException. It must be something really obvious but I cannot see what I do wrong...all the tutorials I have seen use the exact same commands...
java servlet :
public void doGet( HttpServletRequest request, // reaction to the reception of GET
HttpServletResponse response )
throws ServletException, IOException
{
String First_Name = request.getParameter("First_Name");
String Last_Name = request.getParameter("Last_Name");
String Phone_Number = request.getParameter("Phone_Number");
String Address = request.getParameter("Address");
PrintWriter output;
Cookie cookies[];
cookies = request.getCookies(); // get client's cookies
if ( cookies.length != 0 ) {
String departure = cookies[0].getValue();
String destination = cookies[1].getValue();
}
request.setAttribute("First_Name",First_Name);
String strViewPage="formB.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(strViewPage);
dispatcher.forward(request, response);
}
formB.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<label for = "First Name"> First Name </label>
<input type = "text" name = "First_Name" id = "First1_Name" value = "${First_Name}"
"> <br>
</body>
</html>
No, you can't do it directly, unless you write your own parser/injector.
However, using beans gets as close as you can get. Just use the <jsp:useBean> and replace the html with the values of the bean's attributes.
A quick google search yielded this site which contains examples on how to use the beans and jsp: http://www.roseindia.net/jsp/simple-jsp-example/UsingBeanScopeApplication.shtml
If you want to use JSTL, as Luiggi mentioned, here is a good website: http://www.journaldev.com/2090/jstl-tutorial-with-examples-jstl-core-tags
Try Using:
RequestDispatcher dispatcher = request.getRequestDispatcher(strViewPage);
Instead of:
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(strViewPage);
I am creating small web apps and I am facing the following problem. I have 2 JSPs and when I click the submit button, it repeats the value every time. What I want is that when I click on the submit button it should give only the corresponding value.
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="java.io.*,java.util.*" %>
<!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=ISO-8859-1">
<title>Class Video</title>
</head>
<body>
<form action="second.jsp" method="post">
<table>
<%
File f=new File("C:/Users/SHAKTI/Desktop/video");
File[] list=f.listFiles();
if(list.length!=0){
String s[]=new String[list.length];
for(int i=0;i<list.length;i++){
s[i]=list[i].toString();
String fi=list[i].getName();
%>
<tr><td><%=fi %></td>
<td><input type="text" name="file" value="<%=s[i] %>">
</td>
<td><input type="submit" name="play" value="Play"></td>
</tr>
<%}}
else{
%>
<tr>
<td>There is no any files in the database...</td>
</tr>
<%
}
%>
</table>
</form>
</body>
</html>
second.jsp
<form action="" method="post">
<%
response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
String id=request.getParameter("file");
out.println("id = "+id);
%>
<input type="submit" name="submit" value="submit>
</form>
First Jsp : Set Value in First Page
request.setAttribute("name",somevalue);
Second Jsp : Retrieve it in Second page
request.getAttribute("name")
use queryString
URl: http://myaddress.com/xyz?name=jill&sex=f
String someName = request.getParameter("name") ;
String sex = request.getParameter("sex") ;
One way is to use session as described by javaBeginner.
you can also create a from on the fly and submit it.
write a function similar to this one and use it in your success:
function submitValues(url, params) {
var form = [ '<form method="POST" action="', url, '">' ];
for(var key in params)
form.push('<input type="hidden" name="', key, '" value="', params[key], '"/>');
form.push('</form>');
jQuery(form.join('')).appendTo('body')[0].submit();
}
There are many options to pass a value from one jsp to another, Here are some
1) Adding that as a hidden variable and specifying the value
<input name="file" type="hidden" value=""/>
2)Adding it to the session and retrieving the session variable
session.setAttribute("file", value);
3)Passing that as a queryParameter
http://......one.jsp?file=""
It is beacause you are iterating the loop here,
for(int i=0;i<list.length;i++){
s[i]=list[i].toString();
String fi=list[i].getName();
so it will print the last element from the loop, to get the name u clicked on the button try this .. Change this line as
<input type="text" name="file" value="<%=s[i] %>">
as,
<td><input type="button" class="btn" data-reqno=value="<%=s[i] %>" value="file name">
And handle it using jQuery like this , so that you can pass the value to next JSP,
<script type="text/javascript">
$(document).ready(function () {
$(".btn").click(
function() {
var selectedFileName = $(this).attr("data-reqno");
var urlToApprove = "/yourApp/req/filename?name=" + selectedFileName;
}
);
});
</script>
And also try to avoid Scriptlets in JSP , you can use JSTL or El for the same purpose .
Hope it helps !!
there are many method to pass variable such as
session.setAttribute()
session.getAttribute
action "xxx.jsp?variable=1"