如何发布请求并通过Wicket ajax从Spring REST控制器获得响应

时间:2016-03-18 14:40:29

标签: java ajax spring rest wicket

我想开发一个简单的Web应用程序,您可以在其中计算百分比,如本页所示: http://www.percentagecalculator.net/

我正在使用wicket编写我的前端,REST必须是Spring:

PercentageModel是:

public class PercentageModel {
    private int percentage;
    private int fullValue;
    private int percentagedValue;
    //getter/setter/constructors...
}

Spring RESTful控制器应该是这样的:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/percentController")
public class PercentController {

    @Autowired
    private PercentageCalculator percentageCalculator;

    @RequestMapping(method = RequestMethod.GET)
    public PercentageModel calculate(PercentageModel model) {
        return percentageCalculator.calculate(model);
    }

}

计算器spring bean是:

@Controller
public class PercentageCalculator {

    public PercentageModel calculate(PercentageModel request) {
        PercentageModel response = new PercentageModel();
        //it calculates everything, and set the values for the response
        return response;
    }

}

wicket提交链接是:

form.add(new AjaxSubmitLink("calculate") {
    @Override
    protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
        super.onSubmit(target, form);
        PercentageModel percentageModelRequest = (PercentageModel) form.getModelObject();
        //how to call the spring controller here with the PercentageModel request
    }
});

这就是我已经完成的所有事情。现在我有点麻烦了。首先,我是春天和REST的新手。这里的问题是:

如何从wicket ajax调用REST控制器?例子真的很棒!

另外,我应该对web.xml进行一些有趣的更改吗?现在就是这样:

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" 
        xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">   
    <filter>
        <filter-name>wicketfilter</filter-name>
        <filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
        <init-param>
            <param-name>applicationClassName</param-name>
            <param-value>myapp.WicketApplication</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>wicketfilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

我还需要其他XML-s,还是其他什么?无论如何,我已编写的代码是好的吗?或者我应该改变春豆里面的东西吗?

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:0)

您可以使用任何HTTP客户端库(如Apache CXF,Retrofit等)进行REST调用。

根本不需要创建PercentageModel实例。只需将原始数据作为路径/查询字符串参数传递给REST端点。

确保您执行同步HTTP调用!