Redirection of pages in spring mvc - spring

I have a product page which displays all products
home.jsp:
<a class="campaign" href="page/dynamic/product1">
Controller
#RequestMapping(value="/page/dynamic/{pagename}")
public ModelAndView loadProductPage(ModelMap model, #PathVariable("pagename") String pagename) {
model.addAttribute("productname",pagename);
return new ModelAndView("products/"+pagename+"/"+pagename);
}
It is getting redirected to the product1 page. Product1 page has a link called features
product1.jsp
<li>Features</li>
Controller
#RequestMapping(value="/page/loadpage/{choosedProduct}/{linkChoosed}")
public ModelAndView loadProductMenuPages(ModelMap model, #PathVariable("linkChoosed") String linkChoosed, #PathVariable("choosedProduct") String choosedProduct) {
System.out.println("Loading links here");
System.out.println("cones gere");
System.out.println("Product Choosed" + choosedProduct);
System.out.println("Link Choosed" + linkChoosed);
return new ModelAndView("products/"+choosedProduct+"/"+linkChoosed);
}
It is not getting redirected to the "features page", but throws an error:
HTTP Status 404 - /controller/WEB-INF/views/products/loadpage/loadpage.jsp
What should I need to do to get redirected to features page?
EDIT:
Adding servlet-context.xml informed in comment:
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>

In your configuration file please configure below tag
<bean id="PageRedirect"
class="org.springframework.web.servlet.view.RedirectView">
<property name="url" value="RedirectPage.jsp" />
</bean>
And in your controller
#Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
return new ModelAndView("PageRedirect");
}

Related

How can I redirect a user after successful login to different pages, based on their previous page?

I'm redirecting a user to the homepage with the "Default target-url" being set to "/". However, I need to redirect a user if they login on either a product page (/p/) or a search page (/search). How could I go about doing this? I'm not all that knowledgeable about Spring Security and redirects yet.
I've tried intercepting the request within the onAuthenticationSuccess() method in my AuthenticationSuccessHandler and checking for the URL if it contains the product page or search page url.
Within the AuthenticationSuccessHandler:
if (!response.isCommitted()) {
super.onAuthenticationSuccess(request,response,authentication);
}
Within the spring-security-config.xml:
<bean id="authenticationSuccessHandler" class ="com.storefront.AuthenticationSuccessHandler" scope="tenant">
<property name="rememberMeCookieStrategy" ref="rememberMeCookieStrategy" />
<property name="customerFacade" ref="customerFacade" />
<property name="sCustomerFacade" ref="sCustomerFacade" />
<property name="sProductFacade" ref="sProductFacade" />
<property name="defaultTargetUrl" value="/" />
<property name="useReferer" value="true" />
<property name="requestCache" value="httpSessionRequestCache" />
The expected results will be:
When a user logs in on a product page, they will be returned to the product page they were on.
When a user logs in on a search page, they will be returned to the search page they were on.
If the user logs in while not on a product or search page, they are redirected to the homepage.
Hybris OOTB (I'm referring to V6.7) has a functionality where you can list the URLs for which you want to redirect to Default Target Url. The idea here is to have another list(or replace the existing one) with the reverse logic which only allows the given URLs and redirects all other URLs to the default target URLs.
In OOTB you can see listRedirectUrlsForceDefaultTarget in the spring-security-config.xml, where can define the list of URLs which you want to redirect to the default target. Like below.
<alias name="defaultLoginAuthenticationSuccessHandler" alias="loginAuthenticationSuccessHandler"/>
<bean id="defaultLoginAuthenticationSuccessHandler" class="de.hybris.platform.acceleratorstorefrontcommons.security.StorefrontAuthenticationSuccessHandler" >
<property name="customerFacade" ref="customerFacade" />
<property name="defaultTargetUrl" value="#{'responsive' == '${commerceservices.default.desktop.ui.experience}' ? '/' : '/my-account'}"/>
<property name="useReferer" value="true"/>
<property name="requestCache" ref="httpSessionRequestCache" />
<property name="uiExperienceService" ref="uiExperienceService"/>
<property name="cartFacade" ref="cartFacade"/>
<property name="customerConsentDataStrategy" ref="customerConsentDataStrategy"/>
<property name="cartRestorationStrategy" ref="cartRestorationStrategy"/>
<property name="forceDefaultTargetForUiExperienceLevel">
<map key-type="de.hybris.platform.commerceservices.enums.UiExperienceLevel" value-type="java.lang.Boolean">
<entry key="DESKTOP" value="false"/>
<entry key="MOBILE" value="false"/>
</map>
</property>
<property name="bruteForceAttackCounter" ref="bruteForceAttackCounter" />
<property name="restrictedPages">
<list>
<value>/login</value>
</list>
</property>
<property name="listRedirectUrlsForceDefaultTarget">
<list>/example/redirect/todefault</list>
</property>
</bean>
StorefrontAuthenticationSuccessHandler
#Override
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response,
final Authentication authentication) throws IOException, ServletException
{
//...
//if redirected from some specific url, need to remove the cachedRequest to force use defaultTargetUrl
final RequestCache requestCache = new HttpSessionRequestCache();
final SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest != null)
{
for (final String redirectUrlForceDefaultTarget : getListRedirectUrlsForceDefaultTarget())
{
if (savedRequest.getRedirectUrl().contains(redirectUrlForceDefaultTarget))
{
requestCache.removeRequest(request, response);
break;
}
}
}
//...
}
Now reverse that logic by declaring new list (let's say listAllowedRedirectUrls ) or replacing listRedirectUrlsForceDefaultTarget with listAllowedRedirectUrls in the spring-security-config.xml and do the respective changes in the SuccessHandler. Like
<property name="listAllowedRedirectUrls">
<list>/p/</list>
<list>/search</list>
</property>
StorefrontAuthenticationSuccessHandler
if (savedRequest != null)
{
for (final String listAllowedRedirectUrl : getListAllowedRedirectUrls())
{
if ( ! savedRequest.getRedirectUrl().contains(listAllowedRedirectUrl))
{
requestCache.removeRequest(request, response);
break;
}
}
}
You have to do the same changes for /login/checkout handler declaration (defaultLoginCheckoutAuthenticationSuccessHandler) as well.
You can extend AbstractLoginPageController for running your own scenario. Save referrer URL in doLogin method to httpSessionRequestCache. Then check and filter and return referrer URL in getSuccessRedirect method.

View not getting resolved in Spring mvc gradle application

web application is made with gradle sts project
i've added view Resolver like this
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".html" />
</bean>
it is hitting the url but wont return any view
#Controller
public class HomeController {
#RequestMapping(value = DatahubClientConstant.CLIENT_URL , method = RequestMethod.GET )
public ModelAndView getTestPage(HttpServletRequest request, HttpServletResponse response) throws Exception {
//System.out.println("Hello World");
return new ModelAndView("home");
}
}
Tried to sysout it works
It doesnt return any view?
After Some Research i have found out that InternalViewResolver does not resolve html pages directly that's why i was not able to get the view.
Spring MVC ViewResolver not mapping to HTML files
This was a helpful question in resolving the issue. All it is doing is loading the html as static content.

removing GET parameters from URL Spring 4

I have multilanguage installed on my spring app, and I don't want the 'lang' parameter to appear in the URL (I'm storing the locale with sessionLocaleResolver or cookieLocaleResolver/neither works).
I've searched for hours to find a solution to this issue, although apparently it should already be working with what I've done. Here's my code :
The view (welcome.jsp) :
Language : English|Francais|Romanian
<h2>welcome.springmvc : <spring:message code="welcome.text" text="default text" /></h2>
My servlet.xml
<!-- Multi-Language / Localization Setup -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
</mvc:interceptor>
</mvc:interceptors>
<mvc:annotation-driven ignore-default-model-on-redirect="true" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:lang.files/welcome</value>
<!-- <value>classpath:messages2</value> -->
</list>
</property>
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en" />
<property name="cookieName" value="lang" />
<property name="cookieMaxAge" value="60000" />
<property name="cookiePath" value="/" />
</bean>
My Controller code - note that I'm staying in the same page when I click on the link to change the language. Because ideally it would be a dropdown, and I'd stay in the same page
#RequestMapping("/welcome")
public ModelAndView helloWorld() {
String message = "<br/ ><div style='text-align:center;'>"
+ "<h3>********** Hello World, Spring MVC Tutorial</h3></div><br />";
ModelAndView mv = new ModelAndView();
// ModelAndView mv = new ModelAndView(new
// RedirectView("welcome.do", true, true, true));
RedirectView view = new RedirectView("/welcome", true);
view.setExposeModelAttributes(false);
mv.setView(view);
mv.addObject("message", message);
mv.addObject("activities", activityService.getAll());
mv.addObject("act", activityService.getR());
return new ModelAndView(view);
}
The result is a '404' saying that 'localhost/myapp/welcome' is not found.
Finally this the controller, working, but adding the 'lang' parameter in the URL :
#RequestMapping("/welcome")
public ModelAndView helloWorld() {
String message = "<br/ ><div style='text-align:center;'>"
+ "<h3>********** Hello World, Spring MVC Tutorial</h3></div><br />";
ModelAndView mv = new ModelAndView();
mv.addObject("message", message);
mv.addObject("activities", activityService.getAll());
mv.addObject("act", activityService.getR());
return mv;
}
Please help.
Thanks :)
#RequestMapping("/welcome")
public ModelAndView helloWorld() {
String message = "<br/ ><div style='text-align:center;'>"
+ "<h3>********** Hello World, Spring MVC Tutorial</h3></div><br />";
ModelAndView mv = new ModelAndView();
// ModelAndView mv = new ModelAndView(new
// RedirectView("welcome.do", true, true, true));
RedirectView view = new RedirectView("/welcome", true);
view.setExposeModelAttributes(false);
mv.setView(view);
mv.addObject("message", message);
mv.addObject("activities", activityService.getAll());
mv.addObject("act", activityService.getR());
return new ModelAndView(view);
}
This code causes an infinite loop as you are redirecting to /welcome over and over again.
Moreover when you've got a link like English the parameter will always appear in the url when you click on it.
The easiest way(not best) to achieve the goal you want is to create another controller method like
#RequestMapping("/changeLocale")
public ModelAndView changeLocale() {
RedirectView redirectView = new RedirectView("/welcome");
redirectView.setExposePathVariables(false);
return new ModelAndView(redirectView);
}
And links will look like
English|Francais|Romanian

Spring MVC IE7 redirect

First, I execute save.do in edit.jsp
#RequestMapping(value = "/saveUser.do")
public String saveUser(User user) {
userService.save(user);
return "redirect:/listUser.do";
}
I then system redirect to list.do
#RequestMapping(value = "/listUser.do")
public String listUser(User user, HttpServletRequest request) throws Exception {
List<User> list = userService.getAll(user, getRowBounds(request));
request.setAttribute("list", list);
return "/framework/system/user/listUser";
}
When I use chrome, the page will view new data.
But if I use IE7, the page does not view new data, only views the old data.
But with IE11 seems to be working fine.
Tanks for every one.
I find the answer.
Add
<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"/>
</bean>
</mvc:interceptors>
how to set header no cache in spring mvc 3 by annotation

ajax login with spring webMVC and spring security

I've been using Spring Security 3.0 for our website login mechanism using a dedicated login webpage. Now I need that login webpage to instead be a lightbox/popup window on every webpage in our site where upon logging in I get an AJAX result whether it was successful or not. What's the best way to go about this with Spring Security and Spring webmvc 3.0?
At the client-side you may simulate a normal form submission to your login url via ajax. For example, in jQuery:
$.ajax({
url: "${pageContext.request.contextPath}/j_spring_security_check",
type: "POST",
data: $("#loginFormName").serialize(),
beforeSend: function (xhr) {
xhr.setRequestHeader("X-Ajax-call", "true");
},
success: function(result) {
if (result == "ok") {
...
} else if (result == "error") {
...
}
}
});
At the server side, you may customize AuthenticationSuccessHandler and AuthenticationFailureHandler to return a value instead of redirect. Because you probably need a normal login page as well (for attempt to access a secured page via direct url), you should tell ajax calls from normal calls, for example, using header:
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private AuthenticationSuccessHandler defaultHandler;
public AjaxAuthenticationSuccessHandler() {
}
public AjaxAuthenticationSuccessHandler(AuthenticationSuccessHandler defaultHandler) {
this.defaultHandler = defaultHandler;
}
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication auth)
throws IOException, ServletException {
if ("true".equals(request.getHeader("X-Ajax-call"))) {
response.getWriter().print("ok");
response.getWriter().flush();
} else {
defaultHandler.onAuthenticationSuccess(request, response, auth);
}
}
}
I did something similar (thanks axtavt):
public class AjaxAuthenticationSuccessHandler extends
SimpleUrlAuthenticationSuccessHandler {
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication auth)
throws IOException, ServletException {
if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
response.getWriter().print(
"{success:true, targetUrl : \'"
+ this.getTargetUrlParameter() + "\'}");
response.getWriter().flush();
} else {
super.onAuthenticationSuccess(request, response, auth);
}
}}
I chose to extend the simple success handler for the default behavior on non-Ajax requests. Here's the XML to make it work:
<http auto-config="false" use-expressions="true" entry-point-ref="authenticationProcessingFilterEntryPoint">
<custom-filter position="FORM_LOGIN_FILTER" ref="authenticationFilter" />
...
...
</http>
<beans:bean id="authenticationProcessingFilterEntryPoint"
class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<beans:property name="loginFormUrl" value="/index.do" />
<beans:property name="forceHttps" value="false" />
</beans:bean>
<beans:bean id="authenticationFilter" class=
"org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
<beans:property name="authenticationManager" ref="authenticationManager"/>
<beans:property name="filterProcessesUrl" value="/j_spring_security_check"/>
<beans:property name="sessionAuthenticationStrategy" ref="sas" />
<beans:property name="authenticationFailureHandler" ref="failureHandler"/>
<beans:property name="authenticationSuccessHandler" ref="successHandler"/>
</beans:bean>
<beans:bean id="successHandler" class="foo.AjaxAuthenticationSuccessHandler">
<beans:property name="defaultTargetUrl" value="/login.html"/>
</beans:bean>
<beans:bean id="failureHandler" class="foo.AjaxAuthenticationFailureHandler" />

Resources