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")
Related
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.
So I'm a little unclear on how to properly use #PathVariable in the context I'm trying to here. Let me explain.
I have a JSP page with a table. The table contains all the records in a table in my database. That all works fine.
At the bottom of the table, there are buttons. Add, Edit, Delete. They are all using separate forms because I want to have separate URL paths/ HTTP Methods for each.
To accomplish this, I'm using JQuery so that when I hit submit on the form, it retrieves the ID value of the currently selected record. All of that works perfectly, and is not what I'm asking about.
Here is the form where the submit action is taking place:
<form:form id="editForm" action="./${courseId}.html" path="courseId" method="get">
<input type="hidden" id="editCourseId" name="courseId"/>
<input class="btn btn-lg btn-default btn-shadow" type="submit"
value="Edit"/>
</form:form>
So, what I want is for this form to call a URL with courseId as the #PathVariable value. The value of courseId is contained in the hidden input field with the name courseId. Again, that input field's value is set by JQuery code, and I've already tested that and it seems to be working perfectly.
What I want is to use courseId as the #PathVariable, and have it work in the following controller method:
#RequestMapping (value="/{courseId}", method=RequestMethod.GET)
public String editCourse(Model model,
#PathVariable ("courseId") String courseId){
System.out.println("CourseID: " + courseId);
return "course-form";
}
Obviously that method is still in the early stages, just trying to get confirmation that it works.
So, what do I have to do to make this happen? Again, I want to pass the value of courseId in the URL, as a RESTful style URL command, using it as a #PathVariable. How do I do this?
Thanks so much.
You can get a very clear explanation here
#RequestMapping (path="/{courseId}", method=RequestMethod.GET)
public String editCourse(Model model,
#PathVariable String courseId){
System.out.println("CourseID: " + courseId);
return "course-form";
}
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 am trying to receive simple text input from a form generated by a freemarker template. The correct method is being invoked, but the model is empty, where I am expecting it to be populated.
I am working in the context of a pre-existing application, or I would have tossed this combination aside long ago and gone to a straight Spring MVC/JSP implementation.
I have been through every tutorial on the web, and many postings on this very topic in stackoverflow, and I am still failing to grasp something. Whatever I am missing may be so elementary that no one bothers to post it.
The examples from within the application are not very helpful because they are constructed with sufficient indirection that I can't see how they work at all.
Freemarker template
<#import "/spring.ftl" as spring />
<#spring.bind "model"/>
<form name="model" method="post">
<input type="text" name="user" id="user" value="${model.user}"/>
<input type="hidden" id="submission" name="submission"/>
<input type="submit" name="test" id="test" value="Test" onclick="document.getElementById('submission').value = 'test'"/>
</form>
Controller code:
#RequestMapping(value = "/config", method = RequestMethod.POST)
public ModelMap postConfig(#ModelAttribute("model") ModelMap model) {
logger.debug("User name was {}", model.get("user")); // Why is model empty here?
return model;
}
In the end, I was unable to use the ModelMap as an input. What I believe is the reason is that, while Spring has a million ways to accomplish any given task, the freemarker integration is not as robust as the jsp integration.
There is a little known but widely used feature of spring that resolves form elements to method parameters by name. Based on other people's comments I don't believe it is well documented. But, since it is core to the Groovy on Grails framework, I believe it is safe to consider it to be core to Spring.
The solution I finally used is this:
#RequestMapping(value = "/config", method = RequestMethod.POST)
public ModelMap postConfig(String user) {
logger.debug("User name was {}", user); // Why is model empty here?
// ... snip ...
model.put("user", user);
return model;
}
Spring resolves form entities to the controller method parameters by type and name. It's a bit inconvenient for my intention, but it gets the data where I can work with it.
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.