【问题标题】:JSP compiler shows error when using "+" operatorJSP 编译器在使用“+”运算符时显示错误
【发布时间】:2014-06-14 17:05:44
【问题描述】:

我构建了一个 servlet,它编译 java 代码并返回编译错误(如果有的话)。 我从输入代码的 html 表单中调用它。问题是,每当我使用“+”运算符进行算术加法或连接字符串时,它就是不喜欢它。

这是我的 servlet 类:

@WebServlet("/compiler")
public class Compiler extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        StringBuffer sb = new StringBuffer();
        String code = request.getParameter("codeToCompile").toString();
        String results = this.compile(code);
        sb.append(results);
        out.println(sb);
    }


    private String compile(String codeToCompile){
        String compilationResults = null;
        String toCompile = "class test {" + codeToCompile + "}";

        /*Creating dynamic java source code file object*/
        SimpleJavaFileObject fileObject = new JavaObjectFromString ("ejercicio", toCompile);
        JavaFileObject javaFileObjects[] = new JavaFileObject[]{fileObject} ;

        /*Instantiating the java compiler*/
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

        /*Create a diagnostic controller, which holds the compilation problems*/
        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

        /*get a standard file manager from compiler, this file manager helps us to customize how a compiler reads and writes to files*/
        StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(diagnostics, null, null);

        /* Prepare a list of compilation units (java source code file objects) to input to compilation task*/
        Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(javaFileObjects);

        /*Prepare any compilation options to be used during compilation
        //In this example, we are asking the compiler to place the output files under bin folder.*/
        String[] compileOptions = new String[]{"-d", "c:"} ;
        Iterable<String> compilationOptions = Arrays.asList(compileOptions);

        /*Create a compilation task from compiler by passing in the required input objects prepared above*/
        CompilationTask compilerTask = compiler.getTask(null, stdFileManager, diagnostics, compilationOptions, null, compilationUnits) ;
        /*Perform the compilation by calling the call method on compilerTask object.*/
        boolean status = compilerTask.call();
        /*On compilation failure, we can use the diagnostic collector to read the error messages and log them in specific format.*/
        if (!status){//If compilation error occurs
            /*Iterate through each compilation problem and print it*/
            for (@SuppressWarnings("rawtypes") Diagnostic diagnostic : diagnostics.getDiagnostics()){
                compilationResults = "ERROR IN LINE "+ diagnostic.getLineNumber() + ": " + diagnostic.getMessage(new Locale(null));
            }
        }
        else
        {
            compilationResults = "SUCCESS";
        }
        /*Finally close the fileManager instance to flush out anything that is there in the buffer.*/
        try {
            stdFileManager.close() ;//Close the file manager
        } catch (IOException e) {
            e.printStackTrace();
        }
        return compilationResults;
    }   
}

它实例化了一个名为“JavaObjectFromString”的类,如下所示:

public class JavaObjectFromString extends SimpleJavaFileObject{

    private String contents;
    private String name;

    public JavaObjectFromString(String className, String contents){
        super(URI.create(className.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
        this.contents = contents;
        this.name = className;
    }

    public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
        return this.contents;
    }
}

在我尝试将 + 运算符与字符串或数字一起使用之前,一切正常。

我一直在测试不同的场景。例如,一些这样的代码:

String someText = "test" + "test";

trows 第 1 行错误:';'预计。当我在方法中使用运算符时也会发生:

public String testMethod(){
      return "test" + "test";
}

如果我再尝试:

public String testMethod(String one, String two){
      return one + two;
}

它在第 2 行抛出 错误:不是语句

如果我这样做:

public int someNumber = 12 + 345;

我在第 1 行也遇到 错误:';'预计

在我的 servlet 代码中,我在哪里破坏了 + 运算符??

【问题讨论】:

  • 日食?掌握?什么是 IDE?
  • 我在 IDE 之外执行它。我有一个带有调用 servlet 的表单的 html(并使用 ajax 来获取和显示结果)。
  • 但是如果我使用 Eclipse+Tomcat 执行它,我会得到同样的错误。
  • 不用空格试试。 "test1"+"test2"
  • 不,仍然没有运气:( 不包括 + 运算符的代码被正确编译,编译器正确修剪空格。

标签: java operator-keyword string-concatenation addition


【解决方案1】:

已解决。问题不在于 servlet 如何处理代码,而在于如何使用 ajax 发送代码以发布表单内容。我只需要在发送之前对文本进行编码:

ajaxObject.send('codigo='+encodeURIComponent(codigo));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-03
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    • 2014-02-08
    • 1970-01-01
    相关资源
    最近更新 更多