ssm框架實現簡單互動
阿新 • • 發佈:2018-11-13
ssm框架實現簡單互動
今天簡單的測試了下在前端提交請求之後把對應的資料放在資料庫中,
ssm(spring-springmvc-mybatis)實現過程可以是如下流程
來看下各個層的實現程式碼:
實體層:
package com.qcbylearn.entitys; public class person { private int a,b,c; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } }
dao層:
package com.qcbylearn.dao; import com.qcbylearn.entitys.person; public interface person_insert { int insert(person p); }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.qcbylearn.dao.person_insert" > <insert id="insert" parameterType="com.qcbylearn.entitys.person" > insert into person values (#{a,jdbcType=BIGINT}, #{b,jdbcType=BIGINT}, #{c,jdbcType=BIGINT}) </insert> </mapper>
其中的mapper對映dao層的interface介面,id對應接口裡的方法。parameterType對應傳入的引數,這裡是一個類物件。
server層:
package com.qcbylearn.services; import com.qcbylearn.entitys.person; public interface person11 { int insert(person p); }
package com.qcbylearn.serviceimpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.qcbylearn.dao.person_insert; import com.qcbylearn.entitys.person; import com.qcbylearn.services.person11; @Service("tt") public class persontt implements person11{ @Autowired private person_insert person_insert; @Override public int insert(person p) { person_insert.insert(p); return 0; } }
server層先實現server的介面,在實現的serverimpl中
在頭部新增@webservice(tt),表示他是service層。
@Autowired
private person_insert person_insert;實現dao層xml配置的insert方法。
controllers層:
package com.qcbylearn.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.qcbylearn.entitys.person; import com.qcbylearn.services.person11; @Controller @RequestMapping("/test") public class test { @Autowired private person11 tt; @ResponseBody @RequestMapping("/t1") public String test111(person p) { System.out.println("aaaaas"); tt.insert(p); return "SUCCESS"; } }
先宣告@controller。
注意這個與上面的聯絡,private後面的型別是server的介面名稱,tt是service的名稱。
然後呼叫server的insert方法。從頁面顯示success,然後在資料庫插入一條資料。
至此完成了簡單的互動。
分析一下遇到的坑的地方:
- tomcat有時候無法啟動,改了下spring-mvc.xml的xsd版本,可能是版本過低匯入無法啟動。
- 右擊專案屬性,要修改mvn下面的project facts dynamic web module的版本為3.0,java版本為1.8,dyplyment assembly裡面引入mvn依賴。
- 有時候可能是tomcat或者專案有快取,可以更新專案或者清除tomcat快取試一試。