Intellij14搭建SpringMVC+Mytatis框架整合和调用测试

来源:互联网 发布:江西 网络小额贷款牌照 编辑:程序博客网 时间:2024/05/16 03:01

这篇博客拖了2个星期才开始写,实在是忙的。
前两篇博客Mybatis,SpringMVC已经分别介绍了在Intellij14上搭建框架的方法,这篇文章会介绍以下内容:

  1. 如何将两个框架整合起来(其实很简单,但是可能实例代码与前两篇稍有不同)
  2. 实现一个上一篇文章中没有实现的POST接口
  3. Java中调用接口的方法

两个框架的整合:

这一部分没有新的内容,按照前两篇博客的步骤全都做完之后,我们会有两个`xml`配置文件,`spring-mybatis.xml`和`mvc-dispatcher-servlet.xml`,前者暂时只有在Test方法中通过spring注释`@ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})`使用,后者已经在`web.xml`中被web容器管理起来了。所以为了完成整合为一个web服务程序的目标,要把前者也管理起来,我们把`spring-mybatis.xml`也放入`WEB-INF`下的`spring`文件夹下,然后管理`web.xml`如下(我把`mvc-dispatcher-servlet.xml`重命名为`spring-servlet.xml`了):    
    <?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">    <servlet>        <servlet-name>MESService</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <init-param>            <param-name>contextConfigLocation</param-name>            <param-value>/WEB-INF/spring/spring-servlet.xml</param-value>        </init-param>        <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>MESService</servlet-name>        <url-pattern>/</url-pattern>    </servlet-mapping>    <context-param>        <param-name>contextConfigLocation</param-name>        <param-value>/WEB-INF/spring/spring-mybatis.xml</param-value>    </context-param>    <listener>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener></web-app>

然后为了保证Test的正常使用,我们把spring文件夹也设置为Resources,至此Mybatis+SpringMVC就算整合完毕了,如果按照前两篇博客的步骤成功配置并测试成功的,这一步应该是水到渠成了。


实现一个POST接口:

我们还是在上一篇博客中的Controller中创建这个方法吧。
 package com.gcoreinc.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controller@RequestMapping("/home")public class HelloController {    //@RequestMapping("/hello")    //@ResponseBody    //public String sayHello(){    //    return "Hello World!";    //}    //以上是上一篇文章的方法,这里我完善一下    @RequestMapping(path = "/hello", method = RequestMethod.GET)    @ResponseBody    public String sayHello(){        return "Hello World!";    }    //这是一个POST方法    @RequestMapping(path = "/newworld", method = RequestMethod.POST)    public void addWorld(@RequestBody World world) {//World类自己创建一个,发挥一下想象力        System.out.println(boxDetail);        //调用Service中的add方法    }}

至此接口创建成功,启动你的Tomcat服务器吧!


Java中调用接口:

如果是有Android开发经验的可以关掉界面了。
原来是想介绍一下OkHttp的,奈何这玩意儿支持JDK7以上,而我公司的还是6,所以,只能自己动手丰衣足食了。
其实就是使用HttpURLConnection来获取HTTP链接。获取一个GET请求的接口可以是这样的(以上面的helloworld为例):

public void helloWorld(){    URL url = new URL(http://127.0.0.70:8080/TestSpringMVC/home/hello);    HttpURLConnection conn = url.openConnection();    conn.setRequestMethod("GET");    conn.connect();    if (conn.getResponseCode() == CON_SUC) {        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));        String line = null;        while (null != (line = reader.readLine())) {            result.append(line);        }        reader.close();        conn.disconnect();     }     System.out.println(result.toString());}

请求一个POST接口的代码如下:

public void newWorld(){    //准备JSON数据,这里我们用google的开源框架`Gson`,用maven下一个就好    //World类自己创建,建议与服务器的World相同,而且如果你是新手,请不要使用诸如Date,TimeStamp作为属性类型    World world = new World();    world.setName("XiWorld");    world.setGod("XiWenRen");    world.setProgramable(false);    Gson gson = new Gson();    String json = gson.toJson(world);    URL url = new URL(http://127.0.0.70:8080/TestSpringMVC/home/newworld);    HttpURLConnection conn = url.openConnection();    conn.setRequestMethod("POST");    conn.setDoInput(true);    conn.setDoOutput(true);    conn.setRequestProperty("Content-Type", "application/json");    conn.connect();    DataOutputStream dataOutputStream = new DataOutputStream(conn.getOutputStream());    dataOutputStream.writeBytes(jsonData);    dataOutputStream.flush();    dataOutputStream.close();}查看一下服务器控制台的输出,应该就能正确输出world的值此处注意:`@RequestBody`注释会自动把Controller接受到的json字符串转换为World对象,所以必须保证World类在服务器端存在

后记:

由于距离项目整合完已经过了两个星期才写这篇博客,项目状态已经不同了,所以没有更详细的步骤的截图,但是这个部分相对没有什么坑,应该很容易就过去了。然后由于没有用IDEA边测边写,以上代码都是无测试纯手打,未免有疏漏之处,欢迎大家指正。
因为现在在使用Gson的过程中遇到一些坑,还没解决,所以下一篇博客会和大家分享一下Gson的详细用法。

0 0
原创粉丝点击