I am trying to read an input field data on click of submit on my controller.
My login.scala.html
<form action="#routes.HomeController.email_auth()" method="post">
Enter your email address :<input type="text" name="username"> <br>
<input type="submit" value="Login">
</form>
Added this to routes,
POST /email_auth controllers.HomeController.email_auth
Reading it on HomeController,
public Result email_auth() {
DynamicForm form = formFactory.form().bindFromRequest();
// if (form.data().size() == 0) {
// return badRequest("Expceting some data");
// } else {
String response = form.get("username");
System.out.println(response);
// }
return ok(email_auth.render());
}
Also, trying to render a different view.How to do this using java
The first thing i see is that your route is defined as a GET request but you send your form with a post request. So Play will not find your route or take another one it can fit on your request. Your route should look like this:
POST /email_auth controllers.HomeController.email_auth
To render a different view you only neet to import it into your Controller and call its render method in your return method. If you want to render a view called my_view.scala.html you need to return ok(my_view.render());.
I also tried your code and the parameter gets printed to the console. So the email you want is already saved to the variable response.
Related
I have a simple form in my Spring MVC project that handles a file upload.
form.jsp
<form method="POST" enctype="multipart/form-data" action="/upload" id="form">
<input id="file" type="file" name="file"><br />
<input type="submit" value="Upload">
<input type="reset" value="Reset">
</form>
Because of the form's action however, I am redirected to localhost:8080/myApp/upload rather than localhost:8080/myApp/form as specified in my #Controller
#RequestMapping(method = RequestMethod.POST, value = "${context}/upload", headers = "content-type=multipart/*")
public String uploadFile(#RequestParam("file") MultipartFile file, Model model) {
//do some upload stuff
model.addAttribute("uploadSuccess", "Upload Successful.");
return "/form";
}
Is it possible to prevent only the form action's redirection, but still retain the value ${context}/upload so that my Controller method gets called? I need my page to land back on myApp/form because this particualr url makes a call to a separate Controller method that retrieves some data
Note that I don't wish to rename my jsp file to 'upload.jsp' and I don't want to make an AJAX Post (Thanks for nothing IE9). Any thoughts mates?
Found the answer for my exact case on 17.5.3 Redirecting to views from Spring's Docs
It is sometimes desirable to issue an HTTP redirect back to the
client, before the view is rendered. This is desirable, for example,
when one controller has been called with POST data, and the response
is actually a delegation to another controller (for example on a
successful form submission). In this case, a normal internal forward
will mean that the other controller will also see the same POST data,
which is potentially problematic if it can confuse it with other
expected data.
This can be done with the following:
return "redirect:/form";
A nice benefit to the redirect is that it prevents the user from accidentally re-POSTing the same data by performing a refresh. The refresh forces a GET of the result page, not a resend of the initial POST data.
UPDATE:
The default redirect:/view will append your model attributes to your URL as query params. This may be undesirable in some cases as it could expose sensitive information to the user. Utilize RedirectAttributes addFlashAttribute(String attributeName, Object attributeValue) method to in order to store Flash Attributes that will be used to store attributes when redirected from one URL to another (Success/Failure messages, etc.)
I have my form below:
<form id="form1" name="form1">
<fieldset>
<ol>
<li>
<label>Project:</label>
<select id="project" name="project" required></select>
</li>
</ol>
<input type="button" onclick="request();">
</fieldset>
</form>
I created a request() function on the onclick event of the input button. I changed the input type to button because I didn't want the page to reload.
The request function uses the RestEasy REST.Request class to create a custom rest request. I used setEntity on the REST.Request object but I don't know how to access that information on the server side.
Below is the request function:
request: function() {
var myRequest = new REST.Request();
var form1 = document.forms["form1"];
var projectTxt = form1.elements["project"].value;
myRequest.setURI(REST.apiURL + "/request/item");
myRequest.setMethod("GET");
myRequest.setEntity({project:projectTxt});
myRequest.execute(function(status, request, entity) {
if (status === 200 && request.readyState === 4) {
// entity is always null
sessionStorage.setItem("project", entity);
console.log("entity=" + entity);
}
});
},
In the above code, entity in the function passed to myRequest.execute() is always null.
Here is the Java code:
#Path("item")
#GET
public String itemFormatRequest(#FormParam("project") String project)
{
// project is always null
return "blarg!!! project is " + project;
}
In the above code, project is null. I've tried using #QueryParam and that doesn't work either. Am I just using this incorrectly or is there something else I'm missing? I've done much trial and error by changing #GET to #POST in both the javascript and java codes. Have also tried adding #Consumes("application/x-www-form-urlencoded") in the java code and that didn't work.
The only thing I did get to work is adding query parameters to the REST.request object like this:
myRequest.addQueryParameter("project", projectTxt);
And then I'm able to retrieve this using (#QueryParam("project") String project).
Thanks!
You are using GET as request method. A GET is intended to retrieve data and so you don't pass an entity. If you just want to read data of a selected project you can use a GET in conjunction with a #QueryParam. But then you don't pass an entity. Just add the queryParameter:
myRequest.addQueryParameter('project', projectTxt);
If you want to pass data to the server you should change the method of the request to POST (in the client and the server code). Also your entity is JSON but your server code expects a #FormParam. The REST.Request object has a addForm and add addFormParameter method. So one of the following should also work (untested):
myRequest.addForm('form1', form1);
or
myRequest.addFormParameter('project', projectTxt);
I'm trying to send a JSON object to a JSP to parse. The JavaScript code is:
function sendData(field1, oper1, value1, field2, oper2, value2, field3, oper3, value3){
var formData = {"field1":field1, "oper1":oper1, "value1":value1, "field2":field2, "oper2":oper2, "value2":value2, "field3":field3, "oper3":oper3, "value3":value3};
$.post("<%=request.getRequestURL().toString()%>getInfo.jsp", {formData:formData}, function(response){alertHere(response)});
}
function alertHere(){
window.alert("Post Successful!")
}
My submit button is:
<input type="submit" value="SEARCH" name="submit" class="srchbutton" onclick="sendData(document.getElementById('field1').value, document.getElementById('oper1').value>
There are several more fields passed in the JavaScript button on click, I just didn't want to post that long of a line.
When I try to post with text data in the form, my web developer console flashes the path to my JSP really quickly then disappears. It's too fast to see the error. If there's no data, the post is successful, as my alertHere function in $.post() is called correctly. I'm not sure if I'm missing something.
Assuming you have a servlet on the server side which handles the data you are sending from the jsp page you could create a pseudo-class using javascript, then parses it to json and finally sends it to the server. for example:
javascript and jQuery
function SomeClass (){
this.field1 = $("#field1").val();
this.oper1 = $("#oper1").val();
this.value1 = $("#value1").val();
// etc. for every field you want to send
}
note: i'm assuming every field have an id.
function alertHere(){
window.alert("Post Successful!")
}
jQuery and ajax
$("#someID").click(function(){
event.preventDefault(); <-------- if you replace the submit button for a simple button,
you don't need to do this.
var formData = new SomeClass();
$.ajax({
url:"ServletName",
data: JSON.stringify(formData),
dataType:"json",
}).done(function(response){
alertHere(response);
});
});
html
<input type="submit" value="SEARCH" id="someID" name="submit" class="srchbutton">
Try changing this line of code
$.post("<%=request.getRequestURL().toString()%>getInfo.jsp", {formData:formData}
To
$.post("<%=request.getRequestURL().toString()%>getInfo.jsp", {formData:Json.stringify(formData)}
Not entirely sure if this would work, Just a suggestion.
Figured it out. The problem was that I wasn't passing my "response" to my success function, so:
function alertHere(){
window.alert("Post Successful!")
}
should have been:
function alertHere(response){
window.alert("Post Successful!")
}
It was probably posting correctly, but I wasn't getting a success because the response wasn't getting passed.
I'm doing web-application. And I have a problem when I edit data
I want to create smth like this
I hope you can help me to find way to do this. I found next variant but I don't know as people usually do this.
Multiply submit in one form.
More than 1 submit in one form.
Or more then one form in 1 JSP
And I should't use any framework. And without javascript.
Thanks
OK, If It helps to understand what I want to get on servlet
I show some part of selvlet
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String page = new String();
Command command = CommandFactory.getCommand(request);
page = command.execute(request);
if (page != null) {
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(page);
dispatcher.forward(request, response);
}
....
}
And CommandFactory
public static Command getCommand(HttpServletRequest request){
Command current = new NoCommand();
String action = request.getParameter("command");
if(action == null || action.isEmpty()){
return current;
}
try{
CommandEnum currentState = CommandEnum.valueOf(action.toUpperCase());
current = currentState.getCurrentCommand();
}
...
}
And CommandEnum
public enum CommandEnum {
EDIT_QUESTION {
{
this.command = new EditQuestionCommand();
}
};
}
And in particular command I do some business logic
Please, help me to find way getting from jsp value as command="delete". With single submit I use hidden field. How we can do the same for several button?
You can use any number of submit buttons in a single form. But name them uniquely so that you can identify easily which button is clicked. Server will not receive name, value pair of buttons that are not clicked. It becomes easy for you to find which button clicked is available as request parameter. Using that you can implement your requirement.
Sample HTML:
<form>
<input type="submit" name="s1" value="S1"/><br/>
<input type="submit" name="s2" value="S2"/>
</form>
On clicking any of these buttons you will see query string as either ?s1=S1 or ?s2=S2
UPDATE 1:
You can have same name for all submit buttons and to identify uniquely, they MUST have different values.
<input type="submit" name="modeOfAction" value="Delete"/><br/>
<input type="submit" name="modeOfAction" value="Update"/>
UPDATE 2:
If you really don't care what the value of each button, then it would be better using unique names for each of the submit buttons.
<input type="submit" name="delete" value="Удалить (Err! I don't know what this text is!)"/><br/>
<input type="submit" name="update" value="Update"/>
There was a time when indeed the optional JavaScript meant: gracefully accept when no JavaScript is present. With the small devices one might think this position might be strengthened again, but:
HTML forms are limited in their usage, as shown above a bit.
DOM usage, like AJAX calls updating part of the page, need JS.
JavaScript user interface possibilities (effects, table sorting, paging, themes, validation) with libraries like jQuery.
I still now a way to get a command=edit: write a servlet filter that translates request parameters. For instance translate a parameter command-NAME = TEXT into command=NAME.
In Spring 3.0
if i have a jsp page with two different links each calling different method on MultiActionController
<form:form method="POST">
Add
Delete
</form:form>
on the MultiActionController i get request parameter as null so cannot validate the values
String username=request.getParameter("username");
String password=request.getParameter("password");
i also tried uing a button and changed it to look like a link but in case of button click add method is called twice once with requestparameter as null and second time with correct values, but this twice entry is creating a mess in the code also to make this work i am using form action which will not work in case of two different method calls
<form:form action="user.htm?action=add method="POST">
<input type="submit" value="I have info"/>"> ---> should call delete method
<input type="submit" value="Click to send info"/> ---> should call add method
</form:form>
want to achieve this without javascript
I have also set param reslover in xml file with default method to call
let me explain my problem again forget the above code i was just giving some example
I have a jsp page which has two input text field and two links each should call different method of the controller both the method will validate the input and will get redirect to another page simple!!
The reason i have using MultiActionController.......
Unfortunately i have to continue using a controller which extends MultiActionController because the same jsp page also has paging which work absolutely fine
So all i wan to do is simply achieve server and client side validation once either of the link is clicked and redirect accordingly.
Please give me some example to move ahead in this...
i want to achieve this w/o javascript i got this example here
but my problem is why the requestParameter is Null
http://www.goospoos.com/2009/11/spri...oller-example/
Here's my code
<bean id="myExampleController" class="com.ui.controller.MyExampleController">
<property name="methodNameResolver">
<ref bean="paramResolver" />
</property>
<property name="validators" ref="myExampleValidator"/>
</bean>
<bean id="paramResolver"
class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="defaultMethodName" value="loadPage"></property>
<property name="paramName">
<value>action</value>
</property>
</bean>
<bean id="myExampleValidator" class="com.validator.MyExampleValidator" />
Controller
public ModelAndView validateValues(HttpServletRequest request, HttpServletResponse response) throws Exception{
ModelAndView mav=null;
----> this is null ???
String value1=request.getParameter("textvalue1");
String value2=request.getParameter("textvalue2");
mav = new ModelAndView("myexample");
mav=getPageData(request, false);
return mav;
}
JSP page
<form action="myexample.htm" method="post">
input type="text" name="textvalue1" size="20" />
input type="text" name="textvalue2" size="20" />
</form>
click to validate
----------> what's wrong with this if the above mentioned site can call a method and works fine ,why i cannot get request parameters
You should consider re-working your controller. Your desired operations should contextually fall under a semantic identifier. For CRUD (create, read, update, delete) operations for a User entity, one my set up the RequestMappings like:
/user (root user index page, lists all users)
/user/add (create a new user)
/user/delete/{id} (delete a user by id)
/user/{id} (find a user by id)
At the controller level, you would accomplish this by:
#RequestMapping(value="/user")
public class UserController
{
#RequestMapping(method=RequestMethod.GET)
public String getListUsers() // default page that is resolved by /user
{
return "user/list"; // used by view resolver
}
#RequestMapping(value="/add.html" method=RequestMethod.GET)
public String getAddUser(Model model)
{
//add person form backing entity to model
return "user/add"; // used by view resolver to locate view
}
#RequestMapping(value="/add.html" method=RequestMethod.POST)
public String postAddUser(#ModelAttribute person) // other objects for errors, etc.
{
// add person, validate person, etc.
return "redirect:/user"; // redirects to index
}
}
et cetera...you'd follow those patterns for the other URIs
Then below works for me
UI
<form:form action="user.htm?action=add method="POST">
<input type="submit" name="add"/>
server side
(WebUtils.hasSubmitParameter(request, "add")