У меня проблема с моим веб-приложением Spring: оно показывает Apache Tomcat/4.0.6 — HTTP-статус 404 — /spring-mvc-example/ (запрошенный ресурс (/spring-mvc-example/) недоступен.) I' Я схожу с ума от этой ошибки, и я не знаю, что делать. Я использую СТС. Спасибо за помощь! Вот как организованы папки. https://i.stack.imgur.com/ded48.png
веб.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_4_0.xsd" id = "WebApp_ID"
version = "4.0">
<display-name>spring-mvc-example</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<display-name>spring-mvc-example</display-name>
<!-- Add Spring MVC DispatcherServlet as front controller -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
spring-servlet.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<beans:beans xmlns = "http://www.springframework.org/schema/mvc"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xsi:schemaLocation = "http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
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">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<context:component-scan base-package = "com.spring" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources
in the /WEB-INF/views directory -->
<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>
пом.xml
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>spring-mvc-example</groupId>
<artifactId>spring-mvc-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Spring MVC Example</name>
<description>Picco esempio</description>
<!-- Add Spring Web and MVC dependencies -->
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.1</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
</configuration>
</plugin>
</plugins>
HomeController.java
package com.spring.controller;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.spring.model.User;
@Controller
public class HomeController {
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
System.out.println("Home Page Requested, locale = " + locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate);
return "home";
}
@RequestMapping(value = "/user", method = RequestMethod.POST)
public String user(@Validated User user, Model model) {
System.out.println("User Page Requested");
model.addAttribute("userName", user.getUserName());
return "user";
}
}
home.jsp
<%@ page language = "java" contentType = "text/html; charset=UTF-8"
pageEncoding = "UTF-8"%>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c"%>
<%@ page session = "false"%>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Hello world!</h1>
<P>The time on the server is ${serverTime}.</p>
<form action = "user" method = "post">
<input type = "text" name = "userName"><br>
<input type = "submit" value = "Login">
</form>
</body>
</html>
user.jsp
%@ page language = "java" contentType = "text/html; charset=UTF-8"
pageEncoding = "UTF-8"%>
<!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=UTF-8">
<title>User Home Page</title>
</head>
<body>
<h3>Hi ${userName}</h3>
</body>
</html>




Две проблемы:
<context:component-scan base-package = "com.spring" /> на
<context:component-scan base-package = "com.spring.*" /><beans:property name = "prefix" value = "/WEB-INF/views/" /> на
<beans:property name = "prefix" value = "/WEB-INF/view/" />(С
ваша папка называется view)Попробуйте перейти к пути http://localhost:{your_port_num}/spring-mvc-example/user
Я действительно не могу понять, в чем проблема. Я также пытался загрузить проект с разных веб-сайтов и пытался запустить их, но у меня та же ошибка, и это действительно странно.
URL-адрес локальный: 8080/весна-MVC-пример/пользователь, я пробовал также локальный: 8080/весна-MVC-пример/домашний
Обратите внимание, что URL-адрес, который вы пытаетесь использовать, является операцией POST. Попробуйте получить к нему доступ через любой rest-client (Postman, Advanced REST Client и т. д.)
Конечно. Я пробовал с Postman, и у меня всегда одна и та же ошибка.
Ну, из того, что я вижу, ваш код выглядит нормально. Вы правильно строите код? Также вы можете изменить сопоставление для вашего GET на /home, а затем попробовать
измените сопоставление сервлета web.xml на
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
затем в вашем файле contextConfigLocation, который является /WEB-INF/spring-servlet.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">
// to scan for annotation controllers, beans or configurations
<context:component-scan base-package = "com.spring" />
<bean
class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix">
<value>/WEB-INF/view/</value>
</property>
<property name = "suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
Вы неправильно упаковываете и развертываете свое приложение.
Я бы рекомендовал вам упаковать ваше приложение в правильный файл WAR, поместить его в папку /webapps или /WebContent и запустить Tomcat.
Если пакет называется spring-mvc-example.war или [любое-имя].war, ваш URL-адрес будет следующим:
http://локальный:8080/весна-MVC-пример/
Здесь выдает ошибку: springframework.org/schema/context/spring-context-3.0.xsd">
Это тоже то, что я заметил.