我是Java Spring MVC的新手。根据web上的一些教程,我不知道为什么,但是当我从controller向view传递一些文本时,这些文本似乎没有出现。
Controller
@Controller
public class HelloWorldController {
@RequestMapping(value = "/helloWorld.htm", method = RequestMethod.GET)
public ModelAndView helloWorld(){
String message = "Hello Spring MVC!";
return new ModelAndView("helloWorld", "message", message);
}
}View
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
Message is: ${message}
</body>
</html>我遵循的所有教程都有完全相同的代码,但它就是不起作用。我在这里错过了什么?
发布于 2015-02-14 02:43:10
如果只需要显示消息,请尝试向helloWorld接收的参数添加HttpServletRequest
public ModelAndView helloWorld(HttpServletRequest request){然后使用setAttribute显示消息:
request.setAttribute("message", "Hello Spring MVC!");编辑:事实证明这条法令是不需要的
我确实忘记了,在jsp中,您需要这样的东西:
<p><c:out value="${message}" /></p>这是在页面的顶部:
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>发布于 2015-02-14 07:19:00
这段代码运行良好。只是为了确认一下,您正在为helloWorld.htm创建一个JSP文件,对吗?
我只需将您的代码放入helloWorld.jsp中,它就能正常工作。
package com.dhargis.example;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloWorldController {
@RequestMapping(value = "/helloWorld.htm", method = RequestMethod.GET)
public ModelAndView helloWorld(){
String message = "Hello Spring MVC!";
return new ModelAndView("helloWorld", "message", message);
}
}
-------------------------------------JSP----------------------------------------------------
helloWorld.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
Message is: ${message}
</body>
</html>
</body>
</html>
然后我删除了<%@ taglib uri="http://java.sun.com/jsp/jstl/core“prefix="c”%>,它仍然工作得很好。
给我发一个后续问题,否则我可以把它放在Github上。
https://stackoverflow.com/questions/28506389
复制相似问题