Spring MVC - Redirect page - spring

I am new to Spring MVC. I started out with a login page. So far, I am succeeded in pulling username,password from pre-existing table in my db and validating user at login. Now I want to redirect the user(Who enters wrong credentials) back to same login page with an error message.
My login page is under "web-content" (Web-Content/index.jsp) and the page I access after successful login is under "WEB-INF/views/". But whenever user enters a wrong credential in index.jsp shud b redirected to same page with an error message.
The problem is that the view resolver will resolve the request to page under("WEB-INF/views"). So how can i redirect to page under "web-content" ... Please help.
Thank you so much

Add default-target-url in your spring config xml file (change login page as per your login page name / URL)
like given below
<form-login login-page="/index" default-target-url='/homePage'
authentication-failure-url="/index?login_error=1"
always-use-default-target="true" />
In Controller add this
#RequestMapping(value="/homePage", method = RequestMethod.GET)
public String printWelcome( ) {
return "home";
}
Add a jsp page inside views folder as you have view resolver with prefix as WEB-INF/views and (assuming that prefix as jsp)
viewResolver for reference
<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/views/" />
<property name="suffix" value=".jsp" />
</bean>

Related

Spring MVC:- how to redirect a user to some specific content pages in my application? [duplicate]

I have a Spring 2.5 application that contains a Flash banner. I don't have the source for the Flash component but it has links hardcoded to certain pages that end in .html I want to be able to redirect those .html pages to existing jsp pages. How can I have Spring resolve a few .html pages to .jsp pages?
My project looks like:
WebContent
|
-sample.jsp
-another.jsp
WEB-INF
|
-myapp-servlet.xml
-web.xml
I want localhost:8080/offers.html to redirect to localhost:8080/sample.jsp
Can I do this with Spring? I already have a SimpleUrlHandlerMapping and UrlFilenameViewController defined in the myapp-servlet.xml that has to continue serving the pages it already is.
In my web.xml, I have
<servlet-mapping>
<servlet-name>myapp</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
Update
Here is the URL mapper. If I add a controller, how do I return the jsp view that is in the WebContent directory as the view resolver includes the /WEB-INF/jsp directory.
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/page1.htm">page1Controller</prop>
<prop key="/page2.htm">page2Controller</prop>
</props>
</property>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
I think you could benefit from the open source URL Rewriting library made by tuckey.org. The guys at SpringSource endorse this library, since it is set up for you automatically if you use Spring Roo to create a project, so it is of good quality. I have used it successfully in a number of projects.
See here for its homepage. And Skaffman is right, you want it to 'forward' instead of redirect, which is the default behaviour.
Configure it in web.xml like this:
<filter>
<filter-name>UrlRewriteFilter</filter-name>
<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
</filter>
Then, in WEB-INF/urlrewrite.xml have an element like this:
<rule>
<from>offers.html</from>
<to>offers.jsp</to>
</rule>
I would use OCPsoft PrettyFaces or OCPsoft Rewrite for this:
With PrettyFaces:
create WEB-INF/pretty-config.xml
<url-mapping>
<pattern value="/offers.html" />
<view-id value="/offers.jsp" />
</url-mapping>
With Rewrite:
ConfigurationBuilder.begin()
.addRule(Join.path("/offers.html").to("/offers.jsp"));
I hope this helps.
~Lincoln
Firstly, I'm assuming that when you say "redirect", you really mean "forward". HTTP Redirects would not be appropriate here.
SO given that, here are some things to try:
Can't you just move the JSP files from WebContent into /WEB-INF/jsp/? You wouldn't have to change the ViewResolver definition, then.
You could try to have the controllers return a view name of something like ../../another.jsp, and hope that the servlet container resolves to /WEB-INF/jsp/../../another.jsp to /another.jsp.
The ViewResolver is only consulted if the controllers return the name of a view. Your controllers don't have to return the name of a view, they can return a View object directly, in this case a JstlView. This can point to whichever JSP you like. You can some controllers returning view names, and some returning View objects.
Remove the prefix property from your view resolver. This means you'd also have to change every existing controller, to prefix every view name they return with /WEB-INF/jsp/. Then you could refer to the JSPs under WebContent by name.

Spring Security: redirect to a URL with path variable after successful login

The following is what I have to redirect a visitor to a page after successful login:
<bean id="authenticationSuccessHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler" p:defaultTargetUrl="/account/quickview"/>
I would like to direct a visitor to a url with the following URL:
/account/quickview/id_of_account_object
How can I configure Spring security to append that account ID to the "/account/quickview" after successful login?
I am using Spring Security 3.1
Thanks and regards.
Here is how I solved this
I created a subclass of SavedRequestAwareAuthenticationSuccessHandler and I added a property called temporaryTargetUrl, which is set to "/account/quickview". When the class' onAuthenticationSuccess is called, I obtain the principal and the account id from the principal. At this moment, I append "/account_id" to temporaryTargetUrl and call the super:
super.setDefaultTargetUrl(this.temporaryTargetUrl + "/" + account.getId());
Note that getDetaulTargetUrl of SavedRequestAwareAuthenticationSuccessHandler is not available outside Spring's package, which is why I created temporaryTargetUrl in the first place.
Please feel free to comment.
Thanks!
You can save the account ID into the spring security session object and retrieve the object when is called the quickview url.
to redirect to the url add into the bean customAuthenticationSuccessHandler the following property
<property name="authenticationSuccessHandler" ref="successHandler" />
and create the successHandler bean:
<bean id="successHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<property name="defaultTargetUrl" value="/account/quickview" />
<property name="alwaysUseDefaultTargetUrl" value="true" />
</bean>
regards

How to get requestURI by using jstl in spring mvc project?

I google a lot and get a answer:
<c:out value="${pageContext.request.requestURI}" />
But I get /myapp/WEB-INF/views/index.jsp
I want to get /myapp/index
How can I do that?
My project is using spring mvc.
My config in spring-mvc.xml:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
In my /WEB-INF/views/, has a index.jsp
My Controler:
#RequestMapping("/index")
public String welcome() {
return "index";
}
When I view localhost:8088/myapp/index, It shows.
Try to use ${requestScope['javax.servlet.forward.servlet_path']}
javax.servlet.forward.* constants retrieve information based on URI passed to getRequestDispatcher() (DispatcherServlet sets this attribute while handling request in the case of Spring Web MVC). But it's independent of frameworks and web containers.
As documentation says FORWARD_SERVLET_PATH is:
The name of the request attribute under which the original servlet path is made available to the target of a forward
You should also remember that if the forward() works by calling getNamedDispatcher(), these attributes (there are 4 more similar attributes: request_uri, context_path, path_info and query_string) are not set because in this case the initial elements of the path does not change.

How can i prevent user from accessing the page using the link after logging out?

After logging out i want the user to never access the page even if they know the correct url and type it in. IF they type in the url of a page which they see when they login, it should be redirected to home page.
I used the code in header.jspfile
<core:if test="${userName == null}">
<script>
parent.location.href='logout.html'
</script>
</core:if>
But since the header is included in both about us page and registration page i had to create a different header for those two files without including the above code.
Is there a better solution?
explanation
Login and Navigate to a Page in the URL. Copy the URL of the Page
Logout
In the same browser window, paste the URL
Site is running fine without seeking any login details.
I'm not very sure about what you are asking, but here we go:
I assume you are protecting some private urls by means of spring security, for example:
<security:http use-expressions="true">
<!-- ...more configuration stuff -->
<security:intercept-url pattern="/private/*" access="isFullyAuthenticated()" />
<!-- ...more configuration stuff -->
<security:logout invalidate-session="true" logout-url="/logout" logout-success-url="/yourUrlAfterLogout.html"/>
</security:http>
Then, when user logs out, he can't access private urls anymore.
(UPDATE: End of Spring Security part)
If you want to prevent user accessing these protected pages when he press back button in the navigator or copy the private url, you can configure WebContentInterceptor as follows:
<mvc:interceptors>
<bean id="webContentInterceptor"
class="org.springframework.web.servlet.mvc.WebContentInterceptor">
<property name="cacheSeconds" value="-1" />
<property name="useExpiresHeader" value="true" />
<property name="useCacheControlHeader" value="true" />
<property name="useCacheControlNoStore" value="true" />
</bean>
</mvc:interceptors>

Spring Model or HttpServletRequest object is not overriding on controller

I am working with a spring hibernate project. all pages are working fine but from the last day i am battling with a problem.
In one of page, when page first time load data from controller in model. all data is coming fine.
but after a post request to update some details from page in database and redirect to same GET request. Database is giving updated data which i updated before and printing it to java code. every thing is fine on server side.
But when Model coming on client side on jsp. Old data is coming.
Even i put details in model as well in http request.
Both object not overriding.
One more thing, on my local machine, this page is working fine, but on Live server i am getting this problem.
please help. i am facing this problem from last day.
I think the problem is that the page requested by GET becomes cached by the Browser or some Server.
You should add some informations about now to cache the http response to the response.
Spring helps you:
<mvc:interceptors>
<bean id="webContentInterceptor"
class="org.springframework.web.servlet.mvc.WebContentInterceptor">
<property name="cacheSeconds" value="0" />
<property name="useExpiresHeader" value="true" />
<property name="useCacheControlHeader" value="true" />
<property name="useCacheControlNoStore" value="true" />
<property name="alwaysUseFullPath" value="true" />
<property name="cacheMappings">
<props>
<!-- 2678400 seconds = 31 days -->
<prop key="/resources/images/favicon*.ico">2678400</prop>
<prop key="/resources/images/*.png">2678400</prop>
</props>
</property>
</bean>
</mvc:interceptors>
For example this configruation will instruct Spring to prevent caching for every response exept the favicon and png files.

Resources