본문 바로가기
Programming/jsp

jsp 내에서 class 정의하기

by 막이 2014. 7. 9.

----> 에러

<%

 public class Person {
    private int id;
    private int age;
    private String name;

    /*
      ... ctor and getters and setters
    */

 }
%>


Answer

I don't see why it wouldn't be possible. A JSP is just another way of writing a Servlet, so you should be able to create classes as static (or for that matter, non-static) inner classes within the Servlet, as you would any other class, using the <%! %> convention.

I was able to do a quick, functional, proof of concept:

<%@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>


'Programming > jsp' 카테고리의 다른 글

JSP 선언부 <%! %>  (0) 2014.07.09
[JSP]getOutputStream() has already been called for this response  (0) 2014.07.09