首页 > 解决方案 > 弹簧靴。ModelAndView addObject 不是替换标签

问题描述

我的控制器不替换标签。

我的控制器有两个端点 URL“/”和“/login”

@Controller
@RequestMapping(value={"/"})
public class Index {
    @GetMapping("/")
    public ModelAndView getLoginPageId() {
        return new ModelAndView("login");
    }

    @GetMapping("/index")
    public ModelAndView getLoginPageId(
            @RequestParam("login") String login,
            @RequestParam("password") String password
    ) {
        ModelAndView modelAndView = new ModelAndView("index");
        modelAndView.addObject("message", "123");

        return modelAndView;
    }
}

登录.jsp

<html>
<head>

    <title>login</title>
</head>
<body>
<form name="newUser" action="/index" method="get">
    Login:<br>
    <input type="text" name="login"><br>
    Password:<br>
    <input type="text" name="password"><br>
    <br>
    <input type="submit" value="Login">
</form>
</body>
</html>

索引.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8"/>
</head>
<body>
<h1>My message ${message}</h1>
</body>
</html>

Chrome浏览器给出响应

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8"/>
    <title>My Message ${message}</title>
</head>
<body>
<h1>HOA v ${message}</h1>
</body>
</html>

${message} 不会被替换。我期待 ${message} 应该被替换为 123。我需要改变什么?

项目结构

标签: javaspring-mvc

解决方案


尝试添加<%@ page isELIgnored="false" %>它将启用 EL:

看一下:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>

   <%@ page isELIgnored="false" %>

    <meta charset="UTF-8"/>
    <title>My Message ${message}</title>
</head>
<body>
<h1>HOA v ${message}</h1>
</body>
</html>

或者,您可以添加<el-ignored>false</el-ignored>到 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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<jsp-property-group>
    <url-pattern>*.jsp</url-pattern>
    <el-ignored>true</el-ignored>
  </jsp-property-group>
</web-app>

推荐阅读