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"
Related
In my UI code, i have a link to a css stylesheet with href="url for spring controller".
I want the Spring Controller to return the CSS file which the UI page uses for styling.
First i was wondering, if this was even possible?, and secondly what the Spring Controller needs to return? Do i need to return a byte[] representation of the css file and put it in a ResponseEntity, or use some kind of outputstream on the Servlet response?
Something like?
#RequestMapping(value = "/getCSS/{userId}", method= RequestMethod.GET, produces={"text/css"})
#ResponseStatus(HttpStatus.OK)
public ??? getCSS(){
}
The UI code and Spring app which has the controller are not part of the same project.
Different users have different stylings, and the Spring app, gets the users css file from a database. Therefore, the css file cannot simply be put into the /static folder or /resources folder as there will be different css files for different users.
You can put static resources (if they don't have to be secured) in your webapp folder. For example webapp/static/style.css
Your can get this file with : localhost:8080/applicationName/static/style.css
controler
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class WebController {
#RequestMapping(value = "/staticPage", method = RequestMethod.GET)
public String redirect() {
return "redirect:/static/final.css";
}
}
Webservlet.xml
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/static/" />
<property name="suffix" value=".css" />
</bean>
<mvc:resources mapping="/static/**" location="/WEB-INF/static/" />
<mvc:annotation-driven/>
Also you can return page like html,jsp
if the resources are in different project you can store the name of that project in applicationContext and refer to it like this from your view ${applicationScope.resourcesProject} like this
<link href="/${applicationScope.resourcesProject}/resources/css/style.css" rel="stylesheet" type="text/css"/>
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.
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.
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 {