OGLL小応用−動的数学式計算


OGLL解析器:

import ognl.Ognl;
import ognl.OgnlContext;
import ognl.OgnlException;
public class OgnlExpression {
/*     */
private Object expression;
/* expressionString OGNL    */
public OgnlExpression(String expressionString) throws OgnlException {
super();
/* Ognl     ,        */
expression = Ognl.parseExpression(expressionString);
}
/*       */
public Object getExpression() {
return expression;
}
/*   Ognl   */
//  1:   .
//  2:  
public Object getValue(OgnlContext context, Object rootObject)throws OgnlException {
/*      */
return Ognl.getValue(getExpression(), context, rootObject);
}
}

サーブレットのテスト:

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ognl.OgnlContext;
public class Test extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
//   OGNL   
OgnlContext context = new OgnlContext();
//      
OgnlExpression expr = new OgnlExpression(request.getParameter("test"));
/*                       */
System.out.println(expr.getValue(context, context));
System.out.println("    :" + expr.getExpression());
} catch (Exception e) {
throw new RuntimeException();
}
}
}

テストJSP:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
</head>
<body>
<form action="test" method="post">
<input type="text" name="test" />
<input type="submit" />
</form>
</body>
</html>

テスト例:
(1.12+13.4)/3.1*1.7
結果:
7.96258064516129