I am trying to make a redirection once a transaction is performed, though the transaction never gets executed. The most surprising thing is that when I click a submit button I do get this cloaked URL redirection which I do not understand why?
My controller code:
#RequestMapping("/saveCyclosUsers")
public ModelAndView saveCyclosUsersCredentials(#ModelAttribute("cyclosUsers") CyclosUsers cyclosUsers, BindingResult bindingResult)
{
cyclosUsersService.saveCyclosUsers(cyclosUsers);
System.out.println("Cyclos Users List:");
return new ModelAndView("redirect/cyclosUsersList.html");
}
My JSP page:
<c:url var="userRegistration" value="saveCyclosUsers.html"/>
<form:form id="registerForm" modelAttribute="cyclosUsers" method="post" action="${userRegistration}">
The DAO code:
#Override
public void saveCyclosUsers(CyclosUsers cyclosUsers) {
//sessionFactory.getCurrentSession().save(cyclosUsers);
sessionFactory.getCurrentSession().createSQLQuery("INSERT INTO lower_credit WHERE" +"WEB-INF.views.Register.ownerName.selectedItem =" + "owner_name");
}
Once i click on the submit button this is what error I do get:
type Status report
message /CyclosProjectOnOverdraft/WEB-INF/views/redirect/cyclosUsersList.html.jsp
description The requested resource is not available.
The extensions is the problem "cyclosUsersList.html.jsp" , html.jsp. I think it's weird. What am I doing wrong?
Use:
return new ModelAndView("redirect:cyclosUsersList.html"); // Not redirect/cyclosUsersList.html
You probably have a ViewResolver in your spring mvc applicationContext with the suffix set to '.jsp'.
So spring by default appends '.jsp' to your view name.
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
To avoid using a view resolver you could directly return a 'View' object, then no view resolver is used. You could also use #ResponseBody, then view resolver is bypassed.
Related
I am new to spring. What i want is i will be having various jsp pages and i will map user request to those JSP pages.My question is "can we map user requests to jsp pages when request url and jsp names are same using spring controller mapping".I searched and not found anything.
like without writing controller
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
Maybe I mis-read the question, but if you wanted to map a URL to a JSP directly (e.g. without having to define a controller & method) then that can be done pretty easily (as you would hope)
XML config:
<mvc:view-controller path="/help-page" view-name="helpPage"/>
or if you are using Java Config (extending WebMvcConfigurerAdapter):
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/help-page").setViewName("helpPage");
}
Using either of the above, if you visit /help-page then it will render the /WEB-INF/jsp/helpPage.jsp
By default Spring MVC registeres a DefaultRequestToViewNameTranslator which will translate the request into a view name similar to your requirements.
Simply use Map as a return type and the translation commences.
Returning a Map will expose it as the model for the view.
You can also return void but you'll have to make sure no HttpServletResponse is declared as an argument.
#RequestMapping("/registration/form")
public ModelMap form(ModelMap model) {
model.addAttribute("form", new FormObject());
return model;
}
Will translate to view name: "registration/form"
I want to put controller name (class name or bean name) as dir name when SpringMVC is resolving view name.
I defined prefix param in UrlBasedViewResolver like /WEB-INF/admin/${controller}/, but it doesn't work, of course.
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="prefix" value="/WEB-INF/admin/${controller}/"/>
<property name="suffix" value=".jsp"/>
<property name="viewClass" value="org.springframework.web.servlet.view.InternalResourceView"/>
</bean>
Obviously, it doesn't work because UrlBasedViewResolver just simple attach view prefix to view name (like view.setUrl(getPrefix() + viewName + getSuffix());).
What's the easiest way to implement this issue?
Or what's the easiest way to get controller name in resolver to overried buildView method in UrlBasedViewResolver subclass?
You can try to create a HandlerInterceptor and modify view name property of ModelAndView in its postHandle() method (it's invoked after execution of controller but before rendering a view). This method also receives instance of the controller as handle.
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")
My starting problem is this error message:
Problem accessing /segment.htm.
Reason:
Neither BindingResult nor plain target object for bean name
'acceptCorrected' available as request
attribute
The top-level description of what I'm working on is this:
Form1 solicits some input from the user. When form1 submits, I need to push that data through some processing, and then present form2, containing the results of the processing. I am trying to communicate the results of form1 to form2 via the model returned by form1's controller's onSubmit.
There's reason to believe that this is verboten.
But, if it is, how do I get the data from1 to be available when rendering the JSP page for form2?
<bean name="/segment.htm" class="com.basistech.rseharvest.SegmentFormController">
<property name="sessionForm" value="true"/>
<property name="commandName" value="segment"/>
<property name="commandClass" value="com.basistech.rseharvest.Segment"/>
<property name="validator">
<bean class="com.basistech.rseharvest.SegmentValidator"/>
</property>
<property name="formView" value="segment"/>
<property name="successView" value="showSegmented"/>
<property name="segmenter" ref="segmenter"/>
</bean>
<!-- the page to enter text -->
<bean name="/showSegmented.htm" class="com.basistech.rseharvest.AcceptCorrectedFormController">
<property name="sessionForm" value="true"/>
<property name="commandName" value="acceptCorrected"/>
<property name="commandClass" value="com.basistech.rseharvest.AcceptCorrected"/>
<property name="validator">
<bean class="com.basistech.rseharvest.CorrectionsValidator"/>
</property>
<property name="formView" value="showSegmented"/>
<property name="successView" value="segment"/>
<property name="data" ref="data"/>
</bean>
The onSubmit of the first form returns a ModelAndView pointing to the second form, by naming the same view as you see as the formView of the second form.
Can you explain a little further what this means? Is the "segment" view rendering HTML that contains a <form> that POSTs to /showSegmented.htm?
formBackingObject() is only called on the initial GET request to the page.
Do you want /segmented.htm to display the form and /showSegmented.htm to handle the processing of the input values?
If so, this isn't really the intended usage of AbstractFormController. This class is intended to be used in situations where you want the same controller to handle 1) the presentation of the form and 2) the processing of it's submission.
Hours of messing around seem to have left me with an answer. I'm not sure it's perfect, but it might help other people. There are tons of people frustrated out there with the error message at the top of this question.
In Spring 2.5.6, there is either a bug or a strange limitation, as follows. If a SimpleFormController specifies, as its successView, another page with a SimpleFormController, the second one will fail as in the question. The post data from the first form seems to interfere with what happens on the second form. There seems to be an assumption that the next view after a form is submitted is always a non-form.
If the first page uses a RedirectView to hand off to the second page, all is well.
There are many conflicting pieces of advice, in some cases coming from conflicting heavy-hitters at on the Spring forums, about this. All I know is I made the error posted in the question go away by switching to a redirect. Now the browser does a plain GET of the page for the successView, and the model sets up correctly, and all is well.
Note in passing that the argument to RedirectView is the 'outside' URL (in the tutorial, something like blah.htm) and not the simple token that the mapper maps to JSP pages.
I have a basic Java EE Spring (MVC) application setup that displays a home page with dynamic content. I am completely new to Spring and am confused how to proceed at this point and add more pages to my application. Do I need to create a new controller for each url on my site? Right now I have the following mapping in my ..-servlet.xml file:
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>
/index.html=homeController
</value>
</property>
</bean>
So if I now have a new page at /login, would I add a mapping to /login/index.html? I get even more confused because I am trying to integrate Spring-security to handle the login page...
I would take a look at annotated Controllers:
http://static.springsource.org/spring/docs/2.5.6/reference/mvc.html
http://static.springsource.org/spring/docs/2.5.6/api/org/springframework/web/bind/annotation/RequestMapping.html
Example:
#Controller
public class TestController {
#RequestMapping(value="/login/index.html")
public String login() {
return "login";
}
#RequestMapping(value="/somethingelse/index.html")
public String login() {
return "somethingelse";
}
}
When you set up your View Resolver, the Strings that are returned would correspond to to a literal page, i.e. somethingelse could be directed to /jsp/somethingelse.jsp if that's how you've set up the resolver in your Spring config. Hint...you need to scan for annotations to auto wire.
Spring-Security is handled in a somewhat similar fashion, but has nothing to do with Spring MVC per say. If done correctly, the only resource you need to provide in order to configure security is the simple login page, which you would configure in your Spring config. Check out this security example:
http://www.mularien.com/blog/2008/07/07/5-minute-guide-to-spring-security/
If you are using spring security, you don't need a controller for showing the login form. You can use any jsp page for that purpose and as spring posts it to j_spring_secutity_check, you don't need a controller to handle it too. Check the spring documentation how you can add multiple methods in controller, You may need to use the beanNmaeMapping kind of configuration. Also the better way now is using annotation based config, which helps you configure any pojo as controller with #Controller annotation
You could use something like:
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/vehicleSearch">vehicleSearchController</prop>
</props>
</property>
</bean>
If there was a file /WEB-INF/jsp/vehicleSearch.jsp it would be mapped to the vehicleSearchController. In this case JSP files are being used for the view but you could adapt it to your view technology.
Configuring it this way you would still need to write a mapping for every file. A better way (as Teja suggested) is probably to annotate the mappings in your controller and do away with the XML configuration.
e.g.
#Controller
#RequestMapping("/vehicleSearch")
public class VehicleSearchController {