I have made a simple servlet in Eclipse running on Tomcat server.
I am running a simple java application which passes a string message=20
to the servlet. The servlet gets the data. I am using
String name= request.getParameter("message");
to get the passed string. When I return the name value back to the application, I am able to get it back. But when I try to process the string name:
int val=Integer.parseInt(name);
I get NumberFormatException
. I cannot figure out what the problem is. I have been able to get the value of name variable back from the servlet, but why can't I use it?
The Code I am using is as follows:
CLIENT SIDE CODE
URL url = new URL("http://localhost:8080/DemoServer/demoservelet");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
BufferedWriter out = new BufferedWriter( new OutputStreamWriter( conn.getOutputStream() ) );
out.write("message=20");
SERVLET CODE
String username = request.getParameter("message").toString();
int val=Integer.parseInt(username); //get error msg on this line
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Passed val :"+ username+username.length());
}
I am getting error on the conversion. One more thing on return I am getting a length value of 4 which also does not make any sense?
Please help me regarding this.
Are you trying to use GET-style parameter passing or PUSH-style parameter passing?
GET-style passing tacks the parameter on the end of the URL like so:
http://localhost:8080/DemoServer/demoservelet?value=20
A URL like this can be assembled fairly easily. You only need to change your URL-creation line, and can remove the two lines related to opening a BufferedWriter:
URL url = new URL(String.format("http://localhost:8080/DemoServer/demoservelet?value=%d", 20));
POST-style passing has to abide by the HTTP protocol, which is fairly similar to what you're using so far, save for the fact that all parameters must have a trailing newline character. Using your example:
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
out.writeln("message=20");
You could also use a PrintStream, which would make formatting your parameters a little easier to handle if you need to change them:
PrintStream out = new PrintStream(conn.getOutputStream());
out.printf("message=%d\n", 20);
Whether you use GET-style or PUSH-style is up to you, though it depends on the type of data you're passing along.
you must to check if name is a valid numbre. name.match("^-?\\d+$"); it returns true if it is a number
我相信您必须将参数写为参数才能被检测为一个。
out.write("<param name=\"message\" value=\"20\">");
您具有输出名称的值,在调试检查值时确定名称是一个数字。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.