【发布时间】:2019-02-26 07:34:06
【问题描述】:
我真的需要这方面的帮助。我正在练习使用 JSP 开发基于 Spring MVC 的应用程序。我从基本开始并尝试打印“page.jsp”内容,但它总是打印“index.html”内容。如果我删除“index.html”,则会收到 404 错误。似乎 Controller 类没有被扫描。我被困在这里,我没有找到任何解决方案。以下是我的代码:
web.xml
<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">
<display-name>Archetype Created Web Application</display-name>
<!-- CONFIGURING FRONT CONTROLLER -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
PageController.java
package net.ritz.onlineshopping.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class PageController {
@RequestMapping(value= {"/","/home","/index"})
public ModelAndView index() {
ModelAndView mv = new ModelAndView("page");
mv.addObject("greeting", "Welcome to Spring Web MVC");
return mv;
}
}
page.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>Online Shopping</title>
</head>
<body>
${greeting}
</body>
</html>
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.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-3.0.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="net.ritz.onlineshopping.controller"/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
This is Index
</body>
</html>
当我在浏览器中输入这个网址时:http://localhost:8080/onlineshopping/
【问题讨论】:
-
您应该有一个切片 XML 配置文件,该文件将文件 page.jsp 与模型名称页面映射。检查这是否正确。
-
对不起,我没听懂。
标签: java spring spring-mvc jsp servlets