Spring MVC - Not Loading View - java

I've been experimenting with Java Servlets for web applications, in this application I was able to hit a Servlet and correctly load a .jsp page, having done this I have moved onto Spring MVC. I've run into a problem where my servlet controller class is called, however it will not load the view.
I've ruled out an the resources not being visible, because it worked correctly with a plain java servlet. I've also read just about every resource/tutorial out there in an effort to attempt to identify the problem without any luck, my problem remains the same. In addition in an effort to trouble-shoot I've added an error page tag () in order to see if when I attempt to hit my page, it would correctly redirect me, but its unable to find the page specified for 404 errors.
Can anyone identify what I've missed?
Web.xml
Variations: Changed url-pattern, init-params, context config location etc.
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/LoginServlet-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
LoginServlet-servlet.xml
Variations: I've tried moving the declarations into different positions as has been suggested on other posts, to no result. In addition typically I've had the prefix set to /WEB-INF/jsp/
<context:component-scan base-package="plan.route.server" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<context:annotation-config/>
<mvc:annotation-driven />
LoginServlet.java
Variations: Different requestMapping path, marking the methods not the class, returning string from methods, returning ModelAndView class
package plan.route.server;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller()
#RequestMapping("/")
public class LoginServlet extends org.springframework.web.servlet.mvc.AbstractController {
#RequestMapping(method = RequestMethod.GET)
public String forwardTo() {
return "index";
}
#Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
throws Exception {
return new ModelAndView("login", "login", "login");
}
}
Project setup
Variations: different locations for the servlet xml, .jsp files etc
Can anyone see what I've missed? all I'm trying to do, despite all the variations is load a .jsp page.
Edit: The following error is displayed after my java servlet method is called:
WARNING: No mapping found for HTTP request with URI [/Root/Login] in DispatcherServlet with name 'LoginServlet'

I see one thing that is wrong and is the jsp configuration in LoginServlet-servlet.xml, try change prefix value as follows:
<context:component-scan base-package="plan.route.server" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<context:annotation-config/>
<mvc:annotation-driven />
With your configuration Spring is not able to find jsp file, because you specified the wrong path. You have to be folder specific, in your case you have jsp files in /WEB-INF/jsp folder.
EDIT:
I configured your project in my workspace and it works. Try to remove this lines from web.xml:
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/LoginServlet-servlet.xml</param-value>
</init-param>
And your Controller class should be like this:
#Controller
#RequestMapping("/")
public class LoginServlet{
#RequestMapping(method = RequestMethod.GET)
public ModelAndView forwardTo(ModelMap model) {
return new ModelAndView("login", "login", "login");
}
}
And pay attention on how you invoke the controller:
http://localhost:8080/Root/
This is the correct way to call the controller because you named your project Root and the controller is listening to "/" path. I used port 8080 because you tagged the question with tomcat, and this is the default tomcat port, if you use another one change it with the one you use.

In LoginServlet-servlet.xml file try
<property name="prefix" value="/WEB-INF/jsp/"/>
instead of
<property name="prefix" value="/" />

With your current project setup
LoginServlet-servlet.xml
<context:component-scan base-package="plan.route.server" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<context:annotation-config/>
<mvc:annotation-driven />
LoginServlet.java
#Controller
#RequestMapping("/")
public class LoginServlet {
#RequestMapping(method = RequestMethod.GET)
public String forwardTo() {
return "index";
}
#RequestMapping(value="/login", method = RequestMethod.GET)
public String forwardToLogin() {
return "login";
}
}
This should work

Related

HTTP Status 404 – Not Found - JAVA MVC

Why I am getting double slash at WEB-INF/view//admin. I am new at Java MVC so please any suggestion, what am I doing wrong?
here is my code `
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>`
web.xml
<servlet-mapping>
<servlet-name>webapp-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping
Controller -
#Controller
public class ControllerClass {
#RequestMapping(value = "/deck", method = RequestMethod.GET)
public ModelAndView viewDeckPage(ModelMap model, HttpServletRequest request) {
System.out.println("in get method..");
return new ModelAndView("/admin/deck");
}
}
There are 2 slashes because first one is coming from the view resolver which is /WEB-INF/view/ and the second one you are returning as view name which is /admin/deck (slash before admin).
To resolve this you have to return only view name without a prefixed slash i.e admin/deck
Remove the trailing slash so your prefix is /WEB-INF/view

Is #responsebody required even when using the MappingJackson2HttpMessageConverter?

I was reading this https://spring.io/guides/gs/rest-service/ and I see that in Spring 4 , the #RestController is a combination of #ResponseBody and #Controller and hence its not necessary to mention the #ResponseBody at every method as it was previously. But, in one of the application am working on, we are using Spring 3.x and we have developed spring webservices and annotated the Controller class as #Controller. The sample controller looks like this:
#Controller
public class SomeController {
#RequestMapping(value = "uri/{values}", method = RequestMethod.GET)
public List<SampleClassPOJO> giveSomething(#PathVariable("values") String some){
//logic
return listOfSampleClassPOJO;
}
//Other services
}
and have the following config in the dispatcher servlet xml :
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="prettyPrint" value="false"/>
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper"/>
</property>
</bean>
</list>
</property>
</bean>
The dispatcher servlet is referred in the web.xml
<servlet>
<servlet-name>dispatch</servlet-name>
<servlet-class>someCustom.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatch</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
And we haven't annotated with #ResponseBody for any of the web services method nor at the class level, but still the response is a json. So, when is the #ResponseBody annotation required?
Now, this has gotten me into a confused state, I tried to search for any example with just the above entry in the dispatcher-servlet.xml and without using the #ResponseBody in the methods of the services, but there are no example as such. Only thing I found was, the above entry along with #RestController annotation in Spring 4.
Can anyone please tell me what is the piece of information that am missing here?
Thanks

how to make rest service in spring mvc?

I am trying to make simple rest service which is used by everybody example it will consume by mobile developer.so I need to send static data to every one .I am trying to send static this data .
{
name:"abcd"
}
in other word if some one hit my system like this
http://192.168.12.61:8080/springfirst/hello .then user get above json.
I follow this like to make
http://www.programming-free.com/2014/03/spring-mvc-40-restful-web-service-json.html
I follow this step
download these jar files(-- jackson-annotations-x.x.x.jar
-- jackson-core-x.x.x.jar
-- jackson-databind-x.x.x.jar) and include in lib folder.
here is my code
web.xml
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
hello-servelts.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.tutorialspoint" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
controller.js
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/hello")
public class HelloController{
#RequestMapping( method = RequestMethod.GET,headers="Accept=application/json")
public String printHello(ModelMap model) {
return "abcd";
}
}
you have configuration problems:
If you register DispatcherServlet in web.xml with out context configuration file path, then you should name the context file as per your servletName-servlet.xml.
So rename hello-servelts.xml as HelloWeb-servlet.xml.
and add #ResponseBody in your controller handler method to return JSON like:
#RequestMapping( method = RequestMethod.GET,headers="Accept=application/json")
public #ResponseBody Map printHello(ModelMap model) {
Map<String,String> json = new HashMap<String,String>();
json.put("name", "abcd");
return json;
}
Here is the working application using ContentNegotiatingViewResolver.
how to make rest service in spring mvc?
Ans, there is different ways are available. I am listing below some of:
To read/write JSON data from HTTP request or response you should use #RequestBody to read from HTTP request and #ResponseBody to write a object as JSON into HTTP response.
Spring provides ContentNegotiatingViewResolver where you can use it to resolve Views by request URL extension OR request ACCEPT header value. for example if URL is /view.html then it will return a view which has text/html content-type. same you can configure it to return JSON as well.
ContentNegotiatingViewResolver configuration for JSON View will look like:
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
</map>
</property>
<property name="defaultViews">
<list>
<!-- JSON View -->
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
</bean>
</list>
</property>
<property name="ignoreAcceptHeader" value="true" />
</bean>
Note: Jackson mapper or any other mapper should be available on buildpath in order to work JSON serialize and deserialize.
If you use Maven, then confirm this dependency available in pom.xml:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.3</version>
</dependency>
SEE ALSO:
How to return object from controller to ajax in spring-mvc
New features in spring mvc 3.1
You can follow this guide which is an official documentation and it is using spring-boot which will do easy your way to start writing services.
You rest service would be something like
#RestController
#RequestMapping("/hello")
public class HelloController{
#RequestMapping( method = RequestMethod.GET,headers="Accept=application/json")
#ResponseBody
public String printHello() {
return "abcd";
}
}

Servlet-mapping glitch with spring mvc

​If I try:
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
I get this error:
No mapping found for HTTP request with URI [/sample/WEB-INF/jsp/person.jsp]
If I try just / as <url-pattern> then everything works fine.
My url : http://localhost:8080/sample/person
Why is this happening? What is the preferred way of doing this configuration in web.xml?
My app-servlet.xml has :
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
You mapped /* (every request to your app) to your servlet called 'app'. The InternalResourceViewResolver than looks (internally) for '/person' inside '/WEB-INF/jsp/person.jsp'. This way you can access your views, while the scripts are secured inside WEB-INF, which is not accessible from the url (public).
/* means every public request to your web-app. It means for your jsp it should be public accessed, since it is in WEB-INF and not public it will give error.
If you use only / it means server took the request and the web-app processes it internal without any public access.

How to create view resolver for html in Spring?

I have faced the problem when decided to create a web-app without JSPs, but using only HTML-pages which are under directory WEB-INF/pages.
I've made the view resolver:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="WEB-INF/pages/"/>
<property name="suffix" value=""/>
</bean>
Also I've imported all the resources in WEB-INF/pages:
<mvc:resources mapping="/**" location="WEB-INF/pages/"/>
My controller have the following view:
#PreAuthorize("isAuthenticated()")
#RequestMapping("/")
public String indexPage() {
return "redirect:/index.html";
}
It works fine for mapping "/" (redirects to login page if not authenticated), but it is not secured for url "/index.html" due to importing of this page as static resource (but it will not work at all if not import it).
Finally, I found the solution. Maybe, it will be interesting to anybody. The main servlet mapping that I had, had url-pattern: /**
And that was my problem. As I understood the main servlet in someway intercepted viewResolver even if it had such configuration: <bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".html"/>
</bean>
When I make the configuration of servlet make as the next one:
<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
everything became ok.
i dont know why you want to do that ..... as putting pages under web-inf is a wrong practice.......
also the container cant access the static contents that are under web-inf folder. I have faced exactly same problem see resource problem post.
what i have found from googling is you can access dynamic resources under web-inf folder but not the static. I have tried even regestring all the static contents (ie. css, js,html, etc) in xml at the first place but nothing worked. finally i moved my pages out and it worked with no configuration ....
so try moving the resources out of web-inf and under webcontent
tell me if you got some extras on this.
thanks.

Categories