How to use existing java class from grails

后端 未结 5 626
执念已碎
执念已碎 2021-02-10 18:19

how can I call a method residing in an existing Java class from Grails app ? Is it necessary/recommended to wrap that up in a service?

5条回答
  •  时光取名叫无心
    2021-02-10 18:46

    I thought I should send an update on the how to on grails 2.2, since I did a lot of looking around and found a lot of irrelevant stuff that did not appear to work, ended up making it work this way:

    Project name: gp22 
    Grails Domain Example name:  DemoGrailsDomain 
    JavaClass:src/java/vv/Baggie.java 
    Controller: DemoGrailsDomainController
    

    1: src/java/vv/Baggie.java

    package vv;
    import gp22.DemoGrailsDomain;
    
    
    public class Baggie {
        public int  myresult(int value1) {
            int resultset=10+value1;
            return resultset;
    
        }
    
        public int getResult(int value1) {
            int aa=myresult(value1);
        return aa;
            //You can call your domain classes directly
        // Once called do a control shift o to pull in the above import example
            //DemoGrailsDomain getdomain = new DemoGrailsDomain();
        }
    
    
    }
    

    DemoGrailsDomainController:

    def list(Integer max) {
            //def myJavaFunction
            Baggie a=new Baggie()
            int passit=5
            def bb=a.getResult(passit);
            println "--"+bb
    

    Do a control shift o on your contoller now, and it will import the vv.Baggie

    Now when I hit the list on the browser the println shows:

    | Server running. Browse to localhost:8080/gp22 --15 on my console

    There you have a value being passed from Grails controller to a Java class processed and returned, the Java class can also call the Groovy Domains and retrieve information

提交回复
热议问题