我如何将这个servlet.java分解成更多的类?



我使用GAE,它运行Jetty和Java。我在一个单片java文件中有一个工作的servlet。我想开始把它分成不同的类。

在这一点上,我真的只是想把大部分代码放到另一个类中,并调用它的想法是根据输入在不同的类中生成不同的网页。

现在,在/Servlet.java中,我有:

package webapp
        public class servlet extends HttpServlet {
           public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
           ...
           try {
               temp.process(root, resp.getWriter());
           } catch (TemplateException e) {
               throw new IOException("Error while processing Freemarker template", e);
           } 
        }

当我尝试创建一个新的类:

public classA {
public void generatePageA() {
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        ...
        resp.setContentType("text/html; charset=UTF-8");
        try {
        temp.process(root, resp.getWriter());
    } catch (TemplateException e) {
        throw new IOException("Error while processing Freemarker template", e);
    } 
    }

}

然后回到servlet.java中,我尝试用

在ClassA中调用函数
ClassA.doGet();

但是我得到语法错误请求标识符后的令牌。

调用ClassA.doGet();你需要把它设为Static

public classA {
    public static void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html; charset=UTF-8");
        try {
            temp.process(root, resp.getWriter());
        } catch (TemplateException e) {
           throw new IOException("Error while processing Freemarker template", e);
        } 
    }
}

还必须传递如下参数:

package webapp
public class servlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        ClassA.doGet(req,resp);
    }
}

如果您想了解更多信息,请发布完整的堆栈跟踪,以便我们提供更好的支持

看起来doGet()方法在generatePageA()方法结束之前就开始了。doget()是对方法的静态引用。该方法要么需要是静态的,要么需要像这样实例化类对象

new ClassA().doGet();

在eclipse这样的IDE中工作将实时显示这些错误,并且通常会提供如何修复的建议。希望对大家有所帮助

最新更新