利用jslint对javascript进行语法校验

初步试用jslint对javascript进行语法校验,事例代码如下:

package com.yonge.validateScript;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

import com.googlecode.jslint4java.Issue;
import com.googlecode.jslint4java.JSLint;
import com.googlecode.jslint4java.JSLintBuilder;
import com.googlecode.jslint4java.JSLintResult;
import com.googlecode.jslint4java.Option;

/**
 * 利用JSLint验证js的正确性
 * @author wb-gaoy
 * @version $Id: JSLintTest.java,v 0.1 2012-12-17 下午4:46:23 wb-gaoy Exp $
 */
public class JSLintTest {

    public static void main(String[] args) throws IOException {
        JSLintBuilder builder = new JSLintBuilder();

        //使用默认的jslint.js进行初始化
        JSLint jsLint = builder.fromDefault();
        //自定义jslint.js进行初始化
        /*JSLint jsLint = builder.fromFile(new File(JSLintTest.class.getResource("/").getPath()
                                                  + "/resource/webjslint.js"));*/
        //过滤的警告选项
       jsLint.addOption(Option.SLOPPY);
        jsLint.addOption(Option.WHITE);
        jsLint.addOption(Option.EQEQ);
        jsLint.addOption(Option.NOMEN);
        jsLint.addOption(Option.UNDEF);
        jsLint.addOption(Option.CONTINUE);
        jsLint.addOption(Option.ON);
        jsLint.addOption(Option.REGEXP);
        jsLint.addOption(Option.VARS);
        jsLint.addOption(Option.PLUSPLUS);

        //jsLint.lint(String systemId, Reader reader)第一个参数是指需要检查的文件名称,第二个参数是文件的内容
        JSLintResult result = jsLint.lint("test.js", new FileReader(new File(ValidateScript.class
            .getResource("/").getPath() + "/resource/test.js")));
        List<Issue> issues = result.getIssues();
        System.out.println(String.format("总共有%1$d个问题", issues.size()));
        if (issues != null && issues.size() > 0) {
            for (Issue issue : issues) {
                System.out.println(String.format("第%1$s行的%2$s出现问题,原因:%3$s", issue.getLine(),
                    issue.getEvidence(), issue.getReason()));
            }
        }
    }
}

 不知道校验的效果好不好,有待考究,但如果有更好的校验方法,请留言,!!

你可能感兴趣的:(JavaScript,validation,jslint,jslint4java)