Spring mvc ошибка 404

I’m going crazy and can’t understand what the problem is:

I have the following structure:

SpringMVC
  +WebContent
      -web-inf
        -web.xml
        -springMVC-servlet.xml
      -index.jsp
      -security
           -login.jsp 

web.xml

<display-name>springMVC</display-name> 
<servlet> 
  <servlet-name>springMVC</servlet-name> 
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup> 
</servlet> 
<servlet-mapping>
  <servlet-name>springMVC</servlet-name>
  <url-pattern>*.html</url-pattern>
</servlet-mapping> 
  <servlet-mapping>
  <servlet-name>springMVC</servlet-name>
  <url-pattern>*.do</url-pattern> 
</servlet-mapping> 
<servlet-mapping> 
  <servlet-name>springMVC</servlet-name> 
  <url-pattern>/index.html</url-pattern>
</servlet-mapping>
<welcome-file-list> 
  <welcome-file>index.html</welcome-file> 
</welcome-file-list>

springMVC-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans 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 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd" 
        xmlns:mvc="http://www.springframework.org/schema/mvc"  
        xmlns:aop="http://www.springframework.org/schema/aop" 
        xmlns:context="http://www.springframework.org/schema/context" 
        xmlns:p="http://www.springframework.org/schema/p" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns="http://www.springframework.org/schema/beans"> 

    <context:annotation-config/> 
    <context:component-scan base-package="com.vanilla.springMVC"/> 

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" > 
       <property name="prefix"> 
          <value>/</value> 
       </property> 
       <property name="suffix"> 
       <value>.jsp</value> 
       </property> 
    </bean> 

</beans>

My Controller:

package com.vanilla.springMVC;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.portlet.ModelAndView;

@Controller
public class DefaultController {

    @RequestMapping(value="/index.html", method=RequestMethod.GET)
    public ModelAndView index(){
        ModelAndView mv = new ModelAndView("index");
        return mv;
    }

    @RequestMapping(value="/login.html", method=RequestMethod.GET)
    public ModelAndView loginPage(){
        ModelAndView mv = new ModelAndView("/security/login");
        return mv;
    }
}

I have no problem to navigate to /index.html

http://localhost:8080/SpringMVC/index.html
works perfect.

however when I’m navigating to
http://localhost:8080/SpringMVC/login.html
i have 404 error.

HTTP Status 404 - /SpringMVC/login.jsp    
type Status report
message /SpringMVC/login.jsp
description The requested resource (/SpringMVC/login.jsp) is not available.

I don’t want to move login.jsp on the same level as index.jsp, but why do I have this problem?

I get 404 error in my browser, after I start my tomcat :

I type in localhost:8080/mvc/hello or localhost:8080/mvc/hello.jsp

enter image description here

But if I type in localhost:8080, it is normal, can access:

enter image description here

In my springmvc-servlet.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans"     
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:context="http://www.springframework.org/schema/context"   
 xmlns:mvc="http://www.springframework.org/schema/mvc" 
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans.xsd 
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context-4.1.xsd  
 http://www.springframework.org/schema/mvc 
 http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> 
    <!-- scan the package and the sub package --> 
    <context:component-scan base-package="com.ypd.springmvcdemo"/>
    <!-- don't handle the static resource -->
    <mvc:default-servlet-handler />
    <!-- if you use annotation you must configure following setting -->
    <mvc:annotation-driven />
    <!-- configure the InternalResourceViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">

        <property name="prefix" value="/WEB-INF/jsp/" />

        <property name="suffix" value=".jsp" />
    </bean>
</beans>

And in my MVCController.java:

@Controller
@RequestMapping("/mvc")
public class MVCController {
    @RequestMapping("/hello")
    public String hello() {
        return "hello";
    }
}

In my web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <!--configure the setting of springmvcDispatcherServlet and configure the mapping-->
   <servlet>
       <servlet-name>springmvc</servlet-name>
       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
       <init-param>
           <param-name>contextConfigLocation</param-name>
           <param-value>classpath:springmvc-servlet.xml</param-value>
       </init-param>
   </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

This is my page of hello.jsp:

enter image description here

(I am sorry about the springmvc-servlet.xml‘s position, I have locate it to under the resource library)

UPDATE — 1:

I am so sorry about it, there is a mistake when I post this snapshot, in my issue project, the web folder has no blue dot on it.See my answer I find the issue with it.

Update image:


So, where is the mistake?


EDIT

My hello.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
Hello, world, jack loly!
</body>
</html>

EDIT

Logs looks like correct:

[2017-03-20 03:06:48,255] Artifact SpringMVCDemo:war exploded: Server is not connected. Deploy is not available.
Connected to the target VM, address: ‘127.0.0.1:51764’, transport: ‘socket’
20-Mar-2017 15:06:50.080 info [main] org.apache.catalina.startup.VersionLoggerListener.log Server version: Apache Tomcat/9.0.0.M17
20-Mar-2017 15:06:50.085 info [main] org.apache.catalina.startup.VersionLoggerListener.log Server built: Jan 10 2017 20:59:20 UTC
20-Mar-2017 15:06:50.085 info [main] org.apache.catalina.startup.VersionLoggerListener.log Server number: 9.0.0.0
20-Mar-2017 15:06:50.085 info [main] org.apache.catalina.startup.VersionLoggerListener.log OS Name: Mac OS X
20-Mar-2017 15:06:50.088 info [main] org.apache.catalina.startup.VersionLoggerListener.log OS Version: 10.12.2
20-Mar-2017 15:06:50.089 info [main] org.apache.catalina.startup.VersionLoggerListener.log Architecture: x86_64
20-Mar-2017 15:06:50.089 info [main] org.apache.catalina.startup.VersionLoggerListener.log Java Home: /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre
20-Mar-2017 15:06:50.089 info [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Version: 1.8.0_121-b13
20-Mar-2017 15:06:50.089 info [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Vendor: Oracle Corporation
20-Mar-2017 15:06:50.089 info [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_BASE: /Users/jack/Library/Caches/IntelliJIdea2016.3/tomcat/Tomcat_9_0_0_M17_SpringMVCDemo
20-Mar-2017 15:06:50.090 info [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_HOME: /Users/jack/Library/Tomcat9
20-Mar-2017 15:06:50.091 info [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.config.file=/Users/jack/Library/Caches/IntelliJIdea2016.3/tomcat/Tomcat_9_0_0_M17_SpringMVCDemo/conf/logging.properties
20-Mar-2017 15:06:50.091 info [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
20-Mar-2017 15:06:50.091 info [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:51764,suspend=y,server=n
20-Mar-2017 15:06:50.091 info [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote=
20-Mar-2017 15:06:50.092 info [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote.port=1099
20-Mar-2017 15:06:50.093 info [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote.ssl=false
20-Mar-2017 15:06:50.093 info [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote.authenticate=false
20-Mar-2017 15:06:50.093 info [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.rmi.server.hostname=127.0.0.1
20-Mar-2017 15:06:50.093 info [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djdk.tls.ephemeralDHKeySize=2048
20-Mar-2017 15:06:50.093 info [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.protocol.handler.pkgs=org.apache.catalina.webresources
20-Mar-2017 15:06:50.093 info [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.base=/Users/jack/Library/Caches/IntelliJIdea2016.3/tomcat/Tomcat_9_0_0_M17_SpringMVCDemo
20-Mar-2017 15:06:50.094 info [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.home=/Users/jack/Library/Tomcat9
20-Mar-2017 15:06:50.094 info [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.io.tmpdir=/Users/jack/Library/Tomcat9/temp
20-Mar-2017 15:06:50.094 info [main] org.apache.catalina.core.AprLifecycleListener.lifecycleEvent The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /Users/jack/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.
20-Mar-2017 15:06:50.527 info [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler [«http-nio-8080»]
20-Mar-2017 15:06:50.560 info [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
20-Mar-2017 15:06:50.563 info [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler [«ajp-nio-8009»]
20-Mar-2017 15:06:50.565 info [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
20-Mar-2017 15:06:50.581 info [main] org.apache.catalina.startup.Catalina.load Initialization processed in 1455 ms
20-Mar-2017 15:06:50.709 info [main] org.apache.catalina.core.StandardService.startInternal Starting service Catalina
20-Mar-2017 15:06:50.709 info [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/9.0.0.M17
20-Mar-2017 15:06:50.745 info [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler [http-nio-8080]
20-Mar-2017 15:06:50.766 info [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler [ajp-nio-8009]
20-Mar-2017 15:06:50.769 info [main] org.apache.catalina.startup.Catalina.start Server startup in 187 ms
Connected to server
[2017-03-20 03:06:51,046] Artifact SpringMVCDemo:war exploded: Artifact is being deployed, please wait…
[2017-03-20 03:06:51,751] Artifact SpringMVCDemo:war exploded: Artifact is deployed successfully
[2017-03-20 03:06:51,751] Artifact SpringMVCDemo:war exploded: Deploy took 705 milliseconds
20-Mar-2017 15:07:00.750 info [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /Users/jack/Library/Tomcat9/webapps/manager
20-Mar-2017 15:07:00.802 info [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /Users/jack/Library/Tomcat9/webapps/manager has finished in 52 ms


EDIT

My tomcat deployment config:
enter image description here


EDIT -2

enter image description here

This example provides the steps to write your own 404 Resource Not Found error page for your application. Here I am writing a custom exception for 404 error using the HttpStatus.NOT_FOUND. This will be annotated as the exception @ExceptionHandler in the controller. Whenever there is any error thrown on this type, it will be redirected to the configured error page. Lets look at the example.

1. Spring MVC Controller

SpringExceptionExample.java

package javabeat.net.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class SpringExceptionExample {
	@ExceptionHandler(ResourceNotFoundException.class)
    public String handleResourceNotFoundException() {
        return "notfound";
    }

    @RequestMapping(value = "/springexceptiontest/{name}", method = RequestMethod.GET)
    public String viewEdit(@PathVariable("name") final String name, Model model) {
        if (name.equals("null")) throw new ResourceNotFoundException();
        model.addAttribute("msg", name);
        return "hello";
    }
}

2. Custom Exception for 404

ResourceNotFoundException.java

package javabeat.net.spring.controller;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException{

}

3. Views

hello.jsp

<html>
<body>
	<h1>JavaBeat Spring MVC Example</h1>
	<h2>Parameter Value : ${msg}</h2>
</body>
</html>

notfound.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>404 Not Found</title>
</head>
<body>
<h2>Your requested page not found!!</h2>
</body>
</html>

4. Spring Configurations

spring-dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	<context:component-scan base-package="javabeat.net.spring.controller" />
	<bean id="jspViewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>

5. Deployment Descriptor

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Spring MVC Web Application</display-name>
	<servlet>
		<servlet-name>spring-dispatcher</servlet-name>
		<servlet-class>
			org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>spring-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

6. Spring MVC 404 Not Found Demo

 Spring MVC : How To Return Custom 404 Error Pages

 Spring MVC : How To Return Custom 404 Error Pages 1

[wpdm_file id=95]

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Reader Interactions

Exception Handling in Spring MVC Example and Return Custom 404 Error Pages

Exception Handling in Spring MVC is about handling exceptions in the application by using spring framework. Spring offers we can customized our error page to more friendly error page to user. This example provides the steps to write your own 404 Resource Not Found error page for your application.

Here I am writing a custom exception for 404 error using the HttpStatus.NOT_FOUND. This will be annotated as the exception @ExceptionHandler in the controller. Whenever there is any error thrown on this type, it will be redirected to the configured error page.

Popular Tutorials

  • Spring Tutorial
  • Spring MVC Web Tutorial
  • Spring Boot Tutorial
  • Spring Security Tutorial
  • Spring AOP Tutorial
  • Spring JDBC Tutorial
  • Spring HATEOAS
  • Microservices with Spring Boot
  • REST Webservice
  • Core Java
  • Hibernate Tutorial
  • Spring Batch

Lets see the example.

1. Controller in Application

package com.doj.spring.web.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.doj.spring.web.bean.Student;
import com.doj.spring.web.exception.StudentNotFoundException;

@Controller
public class WebController {
 
 static Map<String, Student> map = new HashMap<String, Student>();
 @RequestMapping("/")
 public String home(){
  Student student = new Student();
  student.setFname("Dinesh");
  student.setLname("Rajput");
  student.setAge("29");
  student.setAddress("Noida");
  student.setCourse("MS");
  map.put("1000", student);
  return "home";
 }
 
 @RequestMapping("/doj-student-{rollNumber}")
 public String dojStudentByRollNumber(ModelMap model, @PathVariable(value="rollNumber") String rollNumber){
  Student student = map.get(rollNumber);
  if (student == null) {
   throw new StudentNotFoundException("Student Not Found", "ERROR:404");
  }
  String name = student.getFname()+" "+student.getLname()+" "+student.getAddress()+" "+student.getCourse();
  model.put("name", name);
  return "home";
 }
 
 @ExceptionHandler(StudentNotFoundException.class)
 public ModelAndView handleStudentNotFoundException(StudentNotFoundException ex) {
  Map<String, StudentNotFoundException> model = new HashMap<String, StudentNotFoundException>();
  model.put("exception", ex);
  return new ModelAndView("student.error.400", model);

 }
 
 @ExceptionHandler(Exception.class)
 public ModelAndView handleException(Exception ex) {
  Map<String, Exception> model = new HashMap<String, Exception>();
  model.put("exception", ex);
  return new ModelAndView("student.error.500", model);

 }
}


2. Add Custom Exception

package com.doj.spring.web.exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="Student Not Found")
public class StudentNotFoundException extends RuntimeException{

 /**
  * 
  */
 private static final long serialVersionUID = -2581975292273282583L;
 
 String errorMessage;
 
 String errorCode;

 public StudentNotFoundException(String errorMessage, String errorCode) {
  super();
  this.errorMessage = errorMessage;
  this.errorCode = errorCode;
 }

 public String getErrorMessage() {
  return errorMessage;
 }

 public void setErrorMessage(String errorMessage) {
  this.errorMessage = errorMessage;
 }

 public String getErrorCode() {
  return errorCode;
 }

 public void setErrorCode(String errorCode) {
  this.errorCode = errorCode;
 }
 
}

3. Student Bean Class

package com.doj.spring.web.bean;


public class Student {
 
 String fname;
 
 String lname;
 
 String address;
 
 String course;
 
 String age;
 
 public String getFname() {
  return fname;
 }
 public void setFname(String fname) {
  this.fname = fname;
 }
 public String getLname() {
  return lname;
 }
 public void setLname(String lname) {
  this.lname = lname;
 }
 public String getAddress() {
  return address;
 }
 public void setAddress(String address) {
  this.address = address;
 }
 public String getCourse() {
  return course;
 }
 public void setCourse(String course) {
  this.course = course;
 }
 public String getAge() {
  return age;
 }
 public void setAge(String age) {
  this.age = age;
 }
 
}

4. Views JSP

home.jsp

View for Success Page

<h1>${name} Welcome to DOJ Classes for Spring MVC!!!</h1>

Error Page View
400.jsp

<h1>${exception.errorCode}  -  ${exception.errorMessage} !!!</h1>

mainTemplate.jsp

<!DOCTYPE h1 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
<html>
 <head>
  <title><tiles:insertAttribute name="title"/></title>
  <style>
      .error {
          color: red; font-weight: bold;
      }
  </style>
 </head>
 <body style="text-align: center;">
  <div id="header" style="height: 10%;background-color: gray;"><tiles:insertAttribute name="header"/></div>
  <div id="body" style="height: 70%; background-color: aqua;padding-top: 40px;"><tiles:insertAttribute name="body"/></div>
  <div id="footer" style="height: 10%;background-color: gray;"><tiles:insertAttribute name="footer"/></div>
 </body>
</html>

5. Spring Configurations based on Java Configuration

package com.doj.spring.web.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.tiles3.TilesConfigurer;
import org.springframework.web.servlet.view.tiles3.TilesViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages={"com.doj.spring.web.controller"})
public class SpringWebConfiguration extends WebMvcConfigurerAdapter{

 @Bean
 public ViewResolver viewResolver() {
  return new TilesViewResolver();
 }
 
 @Bean
 public TilesConfigurer tilesConfigurer() {
  TilesConfigurer tiles = new TilesConfigurer();
  tiles.setDefinitions(new String[] {
    "/WEB-INF/view/tiles/tiles-def.xml"
  });
  tiles.setCheckRefresh(true);
  return tiles;
 }
 
 //Configure for default static content handling
 @Override
 public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
  configurer.enable();
 }
}

6. Deployment Descriptor based on java configuration

package com.doj.spring.web;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import com.doj.spring.web.config.SpringWebConfiguration;

//this file is equivalent to web.xml
public class WebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{

 //Configuration for non web components like services, daos, repos, etc.
 @Override
 protected Class<?>[] getRootConfigClasses() {
  return null;
 }
 
 //Specifying Spring MVC configuration class "SpringWebConfiguration.class" it equivalent to *-servlet.xml file
 @Override
 protected Class<?>[] getServletConfigClasses() {
  return new Class<?>[]{SpringWebConfiguration.class};
 }

 //Mapping dispatcher server to "/" i.e. Servlet Mapping in the web.xml 
 @Override
 protected String[] getServletMappings() {
  return new String[]{"/"};
 }
}

All files related this example is not mention here for whole application you can download the zip of working application.

SpringMVCExceptionHandlingExample

7. Lets see demo this application

1. Welcome Page

http://localhost:8080/SpringMVCExceptionHandlingExample/

Exception Handling in Spring MVC

2. Error Page

http://localhost:8080/SpringMVCExceptionHandlingExample/doj-student-10001

Exception Handling in Spring MVC Example and Return Custom 404 Error Pages

Spring MVC Related Posts

  • Spring MVC Web Tutorial
  • Spring MVC Interview Questions
  • MVC Design Pattern
  • Spring MVC DispatcherServlet
  • Spring MVC WebApplicationContext and Root Application Context
  • Spring MVC @Controller Annotation
  • Spring MVC @RequestMapping Annotation
  • Spring MVC @RequestParam Annotation
  • Spring MVC ContextLoaderListener
  • Spring MVC @RequestParam and @PathVariable annotations
  • Spring MVC Hello World Example
  • Spring MVC Exception Handling Example
  • Spring MVC with Hibernate CRUD Example
  • Spring MVC Tiles Plugin with Example
  • Spring MVC Interceptor with example
  • Spring MVC with MongoDB CRUD Example
  • Spring MVC Internationalization & Localization with Example

About The Author

Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture.

He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Разрабатываю приложение с использованием Spring MVC apache tomcat 9
Но на урле localhost:8080/hello-world получаю ошибку 404.
В чем ошибка кода?

Исходный код
pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
-->
<!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <packaging>war</packaging>

  <name>web2</name>
  <properties>
    <maven.compiler.source>1.11</maven.compiler.source>
    <maven.compiler.target>1.11</maven.compiler.target>
  </properties>
  <groupId>org.example</groupId>
  <artifactId>web2</artifactId>
  <version>1.0-SNAPSHOT</version>

  <build>
    <plugins>
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>maven-jetty-plugin</artifactId>
        <version>6.1.7</version>
        <configuration>
          <connectors>
            <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
              <port>8888</port>
              <maxIdleTime>30000</maxIdleTime>
            </connector>
          </connectors>
          <webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}</webAppSourceDirectory>
          <contextPath>/</contextPath>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.32</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-simple</artifactId>
      <version>1.7.32</version>
      <scope>test</scope>
    </dependency>

    <!--dependency>
      <groupId>org.example</groupId>
      <artifactId>[the artifact id of the block to be mounted]</artifactId>
      <version>1.0-SNAPSHOT</version>
    </dependency-->
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>5.2.17.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.17.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.2.17.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.17.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf-spring5 -->
    <dependency>
      <groupId>org.thymeleaf</groupId>
      <artifactId>thymeleaf-spring5</artifactId>
      <version>3.0.12.RELEASE</version>
    </dependency>

  </dependencies>

</project>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         id="WebApp_ID" version="3.1">

  <display-name>spring-mvc-app1</display-name>

  <absolute-ordering/>

  <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/applicationContextMVC.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>

</web-app>

applicationContextMVC.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="web"/>

    <mvc:annotation-driven/>

    <bean id="templateResolver" class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".html"/>
    </bean>

    <bean id="templateEngine" class="org.thymeleaf.spring5.SpringTemplateEngine">
        <property name="templateResolver" ref="templateResolver"/>
        <property name="enableSpringELCompiler" value="true"/>
    </bean>

    <bean class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="templateEngine" ref="templateEngine"/>
        <property name="order" value="1"/>
        <property name="viewNames" value="*"/>
    </bean>
</beans>

HelloController.java

package web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {

    @GetMapping("hello-world")
    public String sayHello(){
        return "hello_world";
    }


}

hello_world.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">

<head>
    <meta charset="ISO-8859-1">
    <title>My app</title>
</head>

<body>

<p>Hello world!</p>

</body>

</html>

В чем ошибка кода?

Понравилась статья? Поделить с друзьями:
  • Spowha 412 ошибка e4
  • Spovl ошибка yaskawa a1000
  • Spotify прокси ошибка
  • Spotify ошибка при оплате
  • Spotify ошибка 408