请不要打我脸!我知道面对好的设计这是行得通的,但是我只是写一个测试页来演示一些东西。我们的webapp模块(正确)不能直接访问我们的域类。我不想在JSP之外创建整个类,因为该页面仅用于演示目的,出于相同的原因,我也不想编写很多无关的代码。我试图用JSP中的常用方法定义一个类,但是那没用(抛出了很多编译时错误)。这是一项快速,一次性的交易(完成后,我将立即将其删除)。我只想知道这是否可行。如果没有,那我会走很长的路。
<% public class Person { private int id; private int age; private String name; /* ... ctor and getters and setters */ } %>
和我得到的错误:
convert-jsp-to-java: [INFO] ------------------------------------------------------------------------ [ERROR] BUILD ERROR [INFO] ------------------------------------------------------------------------ An error occurred at line: 57 in the generated java file Syntax error on token "class", invalid VariableDeclarator An error occurred at line: 73 in the generated java file The return type is incompatible with Object.getClass() An error occurred at line: 74 in the generated java file Syntax error on token "class", Identifier expected An error occurred at line: 77 in the generated java file Syntax error on token "class", invalid VariableDeclaratorId An error occurred at line: 78 in the generated java file Syntax error on token "this", PrimitiveType expected An error occurred at line: 78 in the generated java file Syntax error on token "class", invalid Expression An error occurred at line: 79 in the generated java file Syntax error on token "class", invalid Expression
我不明白为什么这不可能。JSP只是编写Servlet的另一种方式,因此,您应该能够像使用其他所有类一样,使用<%!%>约定。
我能够进行快速,实用的概念验证:
<%@page contentType="text/html" pageEncoding="MacRoman"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%! private static class NdBadIdea { private final int foo = 42; public int getFoo() { return foo; } } %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=MacRoman"> <title>JSP Page</title> </head> <body> <h1>Hello World!</h1> <%=new NdBadIdea().getFoo()%> </body> </html>