HTML file not posting GET parameters in a GET request - html

I am trying a simple program with Java Servlet wherein a HTML page with a text box and a submit button will be displayed. Once the user enters the data and submits it, the next page will display a Hello . Calling the servlet URL with the GET parameter directly shows that it works fine. But when I open the HTML file and submit data from there, the GET request isn't formed properly, i.e. the parameters are not getting passed in the address of the 'action' URL.
Here is the HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
</head>
<body>
<form action="/TestServlt/TestClass" name="myform" method="get">
Enter your name: <input type="text name="username">
<br />
<input type="submit" value="Go">
</form>
</body>
</html>
and the servlet code:
package in.lguruprasad;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestClass extends HttpServlet implements Servlet {
static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter output = response.getWriter();
response.setContentType("text/html");
String name = request.getParameter("username");
output.println("Hello "+name+"!");
output.flush();
output.close();
}
}
The servlet is mapped to /TestServlt/TestClass URL and the form submit redirects http://localhost:8080/TestServlt/TestClass instead of http://localhost:8080/TestServlt/TestClass?username=<user input> which would work fine. The output I get is 'Hello null!'.
In all the browsers the form submits without the get parameter. I tried writing a similar doPost method, but that didn't work as well.
What is the issue here and how to fix it?
I am using Eclipse 3.1.2, Apache Tomcat 5.5, JDK 1.6.25 if that helps.

You are missing a quote in the html input:
Enter your name: <input type="text name="username">
should be
Enter your name: <input type="text" name="username">

Related

Call a jsp function by submitting a form

I want to execute a jsp function when a submit button is clicked. Here's what I'm trying to do:
<form>
<input type="text" id="input">
<input type="submit" onClick="(I want the function to be here)">
</form>
<#!
public static void get(){
String s = request.getParameter("input");
System.out.println(s);
}
(I have simplified the code, if you don't understand please let me know.)
I don't really know if this is possible in anyway, I have been searching and I have seen suggestions on similar cases of using AJAX, but I'm not familiar with it and if there is a simpler solution it would be so much easier.
Edit: I just wanted to specify that the function I'm trying to call isn't this simple, I simplified. The actual function uses code that only Java can run (using a Java library).
This is how you can make a simple ajax request from your jsp file to some java code:
Returning String as plain text
The jsp page:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 4112686</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).on("click", "#somebutton", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
$.get("someservlet", function(responseText) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
$("#somediv").text(responseText); // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
});
});
</script>
</head>
<body>
<button id="somebutton">press here</button>
<div id="somediv"></div>
</body>
</html>
Servlet doGet() method:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String text = "some text";
//you can write whatever java code you want to have here, and you can pass the results to the jsp file through the response writer. (text) This will only work from simple strings. If you want to pass more complicated information like lists or objects you will need to convert it to a json object
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
response.getWriter().write(text); // Write response body.
}
If you want to do it in a form you can do it like this:
Ajaxifying an existing form
<form id="someform" action="someservlet" method="post">
<input type="text" name="foo" />
<input type="text" name="bar" />
<input type="text" name="baz" />
<input type="submit" name="submit" value="Submit" />
</form>
<script>
$(document).on("submit", "#someform", function(event) {
var $form = $(this);
$.post($form.attr("action"), $form.serialize(), function(response) {
// ...
});
event.preventDefault(); // Important! Prevents submitting the form.
});
</script>
Servlet:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String foo = request.getParameter("foo");
String bar = request.getParameter("bar");
String baz = request.getParameter("baz");
//do some java stuff here
//then return whatever you want
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8"); /
response.getWriter().write("hello world");
}
Examples taken from: How to use Servlets and Ajax
The onClick() function is meant to be used for JavaScript or JavaScript frameworks, you can do what you are trying to do with JS.
In JS create a function with a parameter, then, the onClick() will look like this
onClick="(myFunction(variableName))"
Inside myFunction(variableName) should look like this
myFunction(variableName){
alert("The variable is: " +variableName);
}
alert("The variable is: " +variableName); will create like a pop up at the top of the webpage showing your variable value.
You can try with this code:
if(request.getParameter("btnSubmit")!=null) //btnSubmit is the name of your button, not id of that button.
{
java.util.Date d = new java.util.Date();
System.out.println(d.toString());
}
<input type="submit" id="btnSubmit" name="btnSubmit" value="Execute Test"/>
Source: onClick function call using scriptlet

Grails No signature of method: org.apache.catalina.core.ApplicationHttpRequest.getFile()

I keep on getting this error message when I go to open the upload page of my Grails application:
No signature of method: org.apache.catalina.core.ApplicationHttpRequest.getFile()
is applicable for argument types: (java.lang.String) values: [file]
Possible solutions: getXML(), getPart(java.lang.String), getAt(java.lang.String),
getAt(java.lang.String), getLocale(), getInfo()
Here's my html code :
<html>
<head>
<meta name="layout" content="main"/>
<title></title>
<style type="text/css">
label{
float:left;
width:65px;
}
</style>
</head>
<body>
<g:uploadForm action="upload">
<input type="file" name="file">
<g:submitButton name="upload" value="Upload"/>
</g:uploadForm>
</body>
</html>
And the corresponding controller class
package org.example.test
class AdminAccessController {
def upload() {
def f = request.getFile('file')
def allLines= f.inputStream.toCsvReader().readAll()
}
}
I've tried importing quite a ton of various libraries to fix the problem, but I haven't figured out what is going on. As you can probably tell, I will end up writing this file into a csv reader. I followed this document on the official Grails GitHub exactly: http://grails.github.io/grails-doc/latest/guide/theWebLayer.html#uploadingFiles, but nothing seems to be working.
Can anyone help me out?
Thanks.
The instance of the request arriving to your controller is an ApplicationHttpRequest which has no getFile method.
You need to change the type of your request to DefaultMultipartHttpServletRequest.
That can be done by changing the enctype in your uploadForm to multipart/form-data like this:
<g:uploadForm action="upload" enctype='multipart/form-data'>
<input type="file" name="file">
<g:submitButton name="upload" value="Upload"/>
</g:uploadForm>
Forgot about getFile(). You receive it how parameter with type MultiPartFile, so you can use its implementations:
params.file.getInputStream().toCsvReader().readAll()

HTML file not working within a GWT/GXT project

The following code is working fine when I run it by itself but when I run it from within a widget in my project the alert does not show up. Am I doing something wrong or forgetting to do something?
<html>
<head>
<title>Upload</title>
<script>
function test() {
alert("Works");
}
</script>
</head>
<body>
<input type='file' size='30' id='fileDiag' maxlength='45'
name='fileDiag'>
<input type="button" onclick="test()" value="TEST" />
</body>
</html>
Try replacing the content of your widget's HTML with just this:
<input type='file' size='30' id='fileDiag' maxlength='45' name='fileDiag'>
<input type="button" onclick="test()" value="TEST" />
<script>
function test() {
alert("Works");
}
</script>
You also shouldn't place JavaScript function directly in your widget's html. You can either create it using a UiBinder and specify a handler using #UiHandler in your UiBinder class, or create a class that extends a Composite and then use a XTemplates as follows:
public interface WidgetTemplates extends XTemplates {
#XTemplate(source = "content.html")
SafeHtml content();
}
Then in your widget's constructor you can add the template's content:
WidgetTemplates templates = GWT.create(WidgetTemplates.class);
public class MyWidget extends Composite {
public MyWidget() {
HTMLPanel rootPanel = new HTMLPanel(templates.content());
initWidget(rootPanel);
sinkEvents(Event.ONCLICK);
}
public void onBrowserEvent(Event evt) {
// handler for all events
}
}
I didn't fully test the above code, but you might get the general idea. You want to code the GWT way, not to circumvent it.

Very simple spring MVC button click

I have the following code in my SampleController;
#Controller
public class SampleController {
#RequestMapping("home")
public String loadHomePage(Model m) {
m.addAttribute("name", "CodeTutr");
return "home";
}
#RequestMapping(value="/test", method=RequestMethod.GET)
public String handlePost(#RequestParam String action, Model m) {
if( action.equals("save") ){
//handle save
}
else if( action.equals("renew") ){
//handle renew
}
m.addAttribute("name", "change");
return "home";
}
}
on page load the attribute I set it successful shown on the web page. I am trying to get my head around button clicks on spring mvc below is my jsp code;
<!DOCTYPE HTML>
<html>
<head>
<title>Sample Application</title>
</head>
<body>
<h1>Hello, ${name}!</h1>
<input type="submit" name="action" value="save" />
</body>
</html>
My input does not do anything, the method handlePost is never hit. I was trying to change the attribute "name" to the word "change", I am not sure what I am doing incorrectly.
Your issue isn't with Spring, it's with HTML. You cannot submit a button. You can only submit a <form>.
Wrap your <input> element in a <form>
<form action="<c:url value="/test" />" method="GET">
<input type="submit" name="action" value="save" />
</form>
Where <c:url> is the url tag of the core taglib. Now, when you click the button, the browser will serialize your <input> elements as url-encoded form parameters and send them. They will appear as request parameters to your server/web application. Spring will deserialize them by name and inject them as arguments where you have a #RequestParam method parameter.
There needs to be a form encapsulating your input.
General FYI: Your "save" and "renew" use cases should be separate controller actions.
Also consider removing "POST" from your action name. Seeing as the action is decorated with GET, and the html is saying its GET

Send post request on click of href in JSP

If we write something as follow:
Link
It will call GET method of that servlet. Can I send post request on click of a tag? Is it possible?
I know how to do this with Javascript but want to know if this could be done without JavaScript.
The solution is to surround the anchor in a form, which has the post method and the action you wish to execute. On the anchor put a javascript to submit the form
<form name="submitForm" method="POST" action="/servlet/ServletName">
<input type="hidden" name="param1" value="param1Value">
Click Me
</form>
edit
I think I should mention that this isn't a good idea.
Links take you to pages, that's what users understand them to do. To break the users assumptions and cause a link to POST, to do an irrevocable thing, is generally considered a bad idea.
Use a button, label it semantically, then your user knows that clicking this does something.
second edit
I really need to emphasise that this isn't a good idea at all.
This breaks the internet.
Only with javascript: create a <form action="MyServlet"> and submit it with form.submit()
You can also send POST with ajax (with jQuery: $.post("MyServlet", {param:param}))
But think about the semantics. With POST you should post data. And links are usually simply getting resources. (It's another story if your link is actually a button in disguise)
Code for Login.jsp page:
<%# 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>Login Page</title>
</head>
<body>
<form action="LoginServlet" method="post" name="credential">
Please enter userName :
<input type="text" name="un"><br>
Please enter PassWord :
<input type="text" name="pw"><br>
<input type="submit" value="Submit">
</form>
<form action="registerUser" name="registerUserForm" method="post">
If no user name and password then get a new one by clicking here
</form>
</body>
</html>
code for registerUser servlet::
package examplePackage;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/registerUser")
public class registerUser extends HttpServlet {
private static final long serialVersionUID = 1L;
public registerUser() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("registerUser");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}