Spring mvc用html符号替换引号

时间:2011-05-12 18:04:07

标签: java jsp spring-mvc jstl

然而,我尝试将双引号引入我的视图spring以某种方式替换它们,这是我尝试过的:

@RequestMapping(value="test", method = RequestMethod.GET)
    public ModelAndView test(){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("test");
        Wrapper wp = new Wrapper();
        wp.setTestField("$(function() { alert(\"test\"); });");
        mav.addObject("testObject", wp);
        return mav;
    }

Wrapper是自定义对象,带有一个字段testField。

@RequestMapping(value="test", method = RequestMethod.GET)
    public ModelAndView test(){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("test");
        mav.addObject("testObject", "$(function() { alert(\"test\"); });");
        return mav;
    }

和jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>Insert title here</title>
</head>
<body>
<script type="text/javascript">
<c:out value="${requestScope.testObject.testField}"></c:out>
</script>
</body>
</html>

结果是:

<script type="text/javascript">
    alert(&#039;test&#039;);    
</script>

我想得到:

 <script type="text/javascript">
        alert("test");    
    </script>

1 个答案:

答案 0 :(得分:4)

那是因为<c:out>会自动转义您的内容。

要阻止它,请使用

<c:out escapeXml="false" value="${requestScope.testObject.testField}"/>