404 page not found in spring mvc example on clicking the link - spring

I am a newbie to Spring framework especially Spring MVC. I am writing code to display a simple message. So index.jsp is the form class in which on hitting the Click Here link the request should get forwarded to hellopage.jsp and print the message. But on clicking the link it is giving 404 error. According to me all the names and configurations are fine but it just doesnt go and prints the message. Any help would be highly appreciated.
Folder structure in eclipse
index.jsp
web.xml
spring-servlet.xml
helloWorldController.java
hellopage.jsp

Replace line
click here
to
click here
in your index.jsp file
It looks like you have placed your index.jsp and hellopage.jsp files in /WEB-INF/JSP folder. Keep those files under WebContent folder and change the line
<property name="prefix" value="/WEB-INF/JSP/" />
to
<property name="prefix" value="/" />

Related

I cant load image in my spring mvc project

I am using spring tool suite. I have placed the image file in folder WebContent/WEB-INF/resources
<img src="WebContent/WEB-INF/resources/team_pic1.jpg" alt="Mountain View" style="width:304px;height:228px;">
This is my servlet.xml code
<mvc:resources mapping="/resources/" location="/resources/" />
I am getting error as
Failed to load resource: the server responded with a status of 404 (Not Found) at http://localhost:8080/SpringMVCTest/WebContent/WEB-INF/resources/team_pic1.jpg
Here is my directory structure
PLS let me know where I am going wrong
here is the error I get when I run through browser
Just try:
<c:url var="imgUrl" value="/resources/team_pic1.jpg" />
<img src="${imgUrl}" alt="Mountain View" style="width:304px;height:228px;">
this build the right URL to hit the resource handler.
You also have to correct the resource mapping:
if you want to deliver "subresources" then you need to add /**.
Depending on where your resource files are located, you also need to correct the location attribute: I expect that /WEB-INF/resources/ is the folder where your resources exist in the war!
So I think this it the resource configuration you need:
<resources mapping="/resources/**" location="/WEB-INF/resources/" />
Content is (usually) served from WEB-INF, so it is not part of the path.
Your configuration defines the mapping
<mvc:resources mapping="/resources/" location="/resources/" />
which says nothing more, that static resources are served from /resources, which means, they are delivered as is.
You could use ${pageContext.request.contextPath}- explanation here
<img src="${pageContext.request.contextPath}/resources/team_pic1.jpg" alt="Mountain View" style="width:304px;height:228px;">

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.

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 to keep the home page i18n on subsequent failed log in attempts

When a user first clicks a link to my homepage, if the link contains ?langId=fr_FR the page displays in French; so far so good. If the user makes a failed attempt to log in the page will display the error message in French, which is perfect. The problem is if a second failed attempt is made to log in. In this case the page language defaults to English.
I am not sure how to keep the page in French for the above case (i.e. any subsequent requests when the initial url contained langId=fr_FR). Should I be using a CookieLocaleResolver instead of a SessionLocaleResolver?
The site uses Spring Security and I have implemented a filter which runs before the Spring Security filters. This filter will set the LocaleContextHolder using the langId request parameter. This works great for the initial log in attempt. Any other requests made and I loose the langId parameter.
Is there something I can do in the loadByUserName() method that will allow me to persist the original langId?
Here is the config for the resolver and interceptor
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" >
<property name="defaultLocale" value="en" />
</bean>
<mvc:interceptors>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="langId" />
</bean>
</mvc:interceptors>
EDIT
Using a CookieLocaleResolver instead of a SessionLocaleResolver does fix this issue. But, if users disable cookies then I am back to square one. I'd like to find a way to keep the page in French upon multiple log in attempts for a user. Any help is really appreciated Thank you!
The problem is exactly the sessionlocaleresolver. Since the login attemps fail a new session is created every time ( i believe ) .
Thats why the cookielocaleresolver is working. The cookie is set and remains for your domain.
I do use the sessionlocaleresolver and havent thought about this issue yet.
One way i see should be to include the locale parameter in your form action. It is probably the easiest solution?

Spring MVC - Redirect page

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>

Resources