HTTP Status 404 – Not Found - JAVA MVC - java

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

Related

How to handle the html and jsp pages in spring mvc from the same URI pattern?

we usually use different URI for HTML and JSP
like
"/static/help" for mapping HTML pages
"/jsp/deposit" for mapping jsp pages
How can i map both HTML and JSP from same URI
like
"/help" should map to "help.html"
"/deposit" should map to "deposit.jsp"
Suppose i have below URI(without extension) which needs to be mapped to given location
and also i don't want to put extensions like .html or .jsp in return value of controller's view name since it is not the best practice.
How can i achieve it?
dispatcher servlet url mapping- "/"
Request Controller's Physical
URI logical File
view name location
------ ---------- ------------
"/" "home" WEB-INF/common/home.html
"/help" "help" WEB-INF/common/help.html
"/deposit" "deposit" WEB-INF/app/deposit.jsp
"/withdraw" "withdraw" WEB-INF/app/withdraw.jsp
Try this: Keep your suffix empty
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/yourDirectory/"/>
<property name="suffix" value=""/>
</bean>
And the in the controller
#RequestMapping("/home")
public String home() {
return "home.html";
}
#RequestMapping("/deposit")
public String deposit() {
return "deposit.jsp";
}
Step1
Create A Class that extends org.springframework.web.servlet.view.InternalResourceView
Step2
Override the method checkResource
The final Class will be like this:
package com.hanz.view;
import org.springframework.web.servlet.view.InternalResourceView;
import java.io.File;
import java.util.Locale;
public class HtmlResourceView extends InternalResourceView {
#Override
public boolean checkResource(Locale locale) {
File file = new File(this.getServletContext().getRealPath("/") + getUrl());
return file.exists();
}
}
Step3 Make the config right
Open the spring-mvc.xml,add this class's bean config,like this:
<bean id="viewResolverHtml" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="com.seeyon.wxapps.base.utils.view.HtmlResourceView"/>
<property name="contentType" value="text/html; charset=utf-8"/>
<property name="prefix" value="/WEB-INF/"/>
<property name="suffix" value=".html"/>
<property name="order" value="3"/>
</bean>

Spring MVC - Not Loading View

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

Spring: servlet-mapping -> url-pattern : /* working but can't display

web.xml
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/webmvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/</welcome-file>
</welcome-file-list>
/WEB-INF/spring/webmvc-config.xml
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="atom" value="application/atom+xml" />
<entry key="html" value="text/html" />
<entry key="json" value="application/json" />
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
</list>
</property>
</bean>
Controller
#Controller
#RequestMapping ( "/" )
public class IndexController extends BaseController
{
#RequestMapping ( "/" )
public String index ( Model model ){
System.out.println("AA");
return index2(model);
}
#RequestMapping ( "/index" )
public String index2 ( Model model ){
System.out.println("BB");
return "index";
}
}
And exist index.jsp File
I guess that is very good working
BBBBBBBBBBBUUUUUUUUUTTTTTTTTT, BUT!
WHY????
WHY????
WHY????
WHY????
And More strange
??????????????????????????????????????????????????????????????????
Controller work it!! but don't display browser
What's going on?
Please help me.
And Log
DispatcherServlet with name 'dispatcher' processing GET request for [/WEB-INF/views/index.jsp]
No mapping found for HTTP request with URI [/WEB-INF/views/index.jsp] in DispatcherServlet with name 'dispatcher'
Servlet containers have rules for how they map and handle URI requests. These can be found in the Servlet Specification. It's also important to note that most Servlet containers have a Servlet to handle JSPs, mapped to *.jsp, which is an extension mapping. Tomcat has a JspServlet to do this.
You've mapped your DispatcherServlet to
<url-pattern>/*</url-pattern>
which is a path mapping. Path mappings take precedence over extension mappings. So when you submit your view name
return "index";
Spring will use the ViewResolver
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
to resolve a path to use with a RequestDispatcher's forward method. That path will be /WEB-INF/views/index.jsp. Now the Servlet container will receive that path and attempt to find a Servlet to handle it. Since you have a Servlet mapped to /* it will use it, but your DispatcherServlet doesn't have a mapping for that path and therefore responds with a 404.
The simple solution is to change your mapping to /, which is the default handler if no other matches are found. In this case, when you submit your view and the container must find a mapped Servlet, it will find the JspServlet and use it.

controller redirect is not working in spring mvc 3.2 with tiles 2

I am not getting the page displayed ,after tiles resolving the page which was redirected by a controller
I have my controller
public ModelAndView addUser(){
if(success){
return new ModelAndView("redirect:myredirectPage.html");
}else {
--show error page---
}
}
and in the same controller
#RequestMapping(value="/myredirectPage", method=RequestMethod.GET)
public ModelAndView showMyRedirectPage(){
ModelAndView modelView = new ModelAndView("redirectPage");
return modelView;
}
all I see in the my log is , tiles is resolving the redirected view, but the page is not getting displayed in the browser.
Added model object 'org.springframework.validatio
n.BindingResult.command' of type
[org.springframework.validation.BeanPropertyBin dingResult] to request
in view with name 'redirectPage' 02 Dec 2013 21:03:23
[http-apr-8080-exec-3] DEBUG [org.springframework.web.servl
et.DispatcherServlet] - - Successfully completed request
and I have spring config file view resolver, where tiles view resolver is given priority.
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="order" value="1"></property>
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="TilesviewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="order" value="0"></property>
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
cant able to debug, since I am not getting any error on logs. appreciate yours responses
Are you absolutely sure that the redirected request is hitting your showMyRedirectPage() method? That method is mapped to /myredirectPage but the redirect request is going to myredirectPage.html
Have you tried adding the .html extension to your #RequestMapping
#RequestMapping(value="/myredirectPage.html", method=RequestMethod.GET)
public ModelAndView showMyRedirectPage(){
ModelAndView modelView = new ModelAndView("redirectPage");
return modelView;
}

PUT method Spring MVC

I'm trying to use the following format for making a put request through the RESTtemplate.
#Autowired
RestTemplate template;
#RequestMapping(value = "/change", method = RequestMethod.PUT)
public ModelAndView change(Data data){
List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.APPLICATION_XML);
HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);
HttpEntity<Data> entity = new HttpEntity<Data>(data, headers);
String url="http://www...com";
try {
template.put(url, entity);
} catch (Exception e) {
System.out.println(e);
}
return new ModelAndView("redirect:/home");
}
I checked on the database and I realized that there is no change. Even the request is not written on the log file. When I'm debugging, I am not getting any error. Probably I'm not using correctly the put method. Can anyone suggest me how should I use the put method or what else should I try to perform a put request with the RestTemplate?
Also i try to use the exchange method instead of the put:
try {
ResponseEntity<Data> result = template.exchange(Url, HttpMethod.PUT, entity, Data.class);
} catch (Exception e) {
System.out.println(e);
}
But in this case i'm taking the following exception:
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [website.Data] and content type [text/html;charset=utf-8].
As you can see from the headers i set the content type as application/xml and not text/html. I look at the headers and i can see that contained:
Accept: application/xml
I really can't understand. What else should i change? Any comments on the exception?
Configuration:
<bean id="viewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver"
p:basename="config/views" p:order="1" />
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<bean class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="location">
<value>/WEB-INF/classes/config/xml-views.xml</value>
</property>
<property name="order" value="0" />
</bean>
<!--It is used for redirect-->
<bean id="urlBasedViewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value=""/>
<property name="suffix" value=""/>
<property name="order" value="2" />
</bean>
<context:annotation-config />
<!--<context:annotation-config />-->
<context:component-scan base-package="data.controller" />
<context:component-scan base-package="data.service" />
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>
</list>
</property>
</bean>
I guess the client of your application is a web-page (then HTML). This article explain what to do for your webapp to be ready for the future browsers compatibility (if they decide later to support e.g PUT, DELETE operations).
In summary for our project we just declared these line in the web.xml:
<filter>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hiddenHttpMethodFilter</filter-name>
<url-pattern>/app/*</url-pattern>
</filter-mapping>
The article talk about javascript to add (probably for version prior to Spring 3.0 M1), but we found this solution better as it is just a configuration.

Categories