SpringMVC之簡單的增刪改查(SSM整合)

雖然已經(jīng)在做關(guān)于SpringMVC的項(xiàng)目思犁。但是還沒有寫一些比較系統(tǒng)的博客谨娜。今天就先來說一說最簡單的增刪改查吧渠旁。這個(gè)例子是基于SpringMVC+Spring+Mybatis實(shí)現(xiàn)的竭翠。

環(huán)境配置

主要是幾項(xiàng)配置:springmvc的配置脑蠕,spring的配置酌泰,MyBatis的配置媒佣,jdbc的配置,和web.xml配置

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
    <!-- 文件掃描 -->
    <context:component-scan base-package="com.zhao"></context:component-scan>

    <!-- annotation-driven:默認(rèn)創(chuàng)建了多個(gè)對象:RequestMappingHandlerMapping陵刹,RequestMappingHandlerAdapter
        也就提供對json格式支持
     -->
    <mvc:annotation-driven/>
    <!-- 視圖解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

beans.xml(Spring的配置)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

        <context:component-scan base-package="com.zhao"></context:component-scan>

    <!-- 第一步:配置數(shù)據(jù)源 -->
    <context:property-placeholder location="classpath:jdbc.properties" />
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>

    </bean>

    <!-- 第二步:創(chuàng)建sqlSessionFactory默伍。生產(chǎn)sqlSession -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
    </bean>
    <!-- 配置mybatis接口代理開發(fā)
        * 接口類名和映射文件必須同名
        * 接口類和映射文件必須在同一個(gè)目錄 下
        * 映射文件namespace名字必須是接口的全類路徑名
        * 接口的方法名必須和映射Statement的id一致
     -->
     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
     <property name="basePackage" value="com.zhao.mapper"></property>
     <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
     </bean>

    <!-- 第三步:事務(wù) -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 配置通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
    <tx:method name="save*" propagation="REQUIRED" />
    <tx:method name="update*" propagation="REQUIRED" />
    <tx:method name="delete*" propagation="REQUIRED" />
    <tx:method name="insert*" propagation="REQUIRED" />
    <tx:method name="*" propagation="REQUIRED" />   
    </tx:attributes>

    </tx:advice>

    <!-- 配置攔截service -->
    <aop:config>
    <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.zhao.service.*.*(..))"/>
    </aop:config>

</beans>

jdbc.properties(數(shù)據(jù)庫jdbc的配置)

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://localhost\:8888/blog
jdbc.username=root
jdbc.password=123456

web.xml的配置

<?xml version="1.0" encoding="UTF-8"?>
<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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name></display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:beans.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

spring的配置中已經(jīng)添加了對數(shù)據(jù)源的支持。。在基礎(chǔ)的應(yīng)用中我們并不需要對MyBatis做什么配置也糊。因此基本的配置就是如上所示炼蹦。

增刪改查的操作

首先是查的操作

列表顯示所有信息

Controller層實(shí)現(xiàn)
    @RequestMapping("/list")
    public String UserList(Model model) {

        List<User> list =userService.findAll();
        //傳遞數(shù)據(jù)至前端
        model.addAttribute("list",list);
        //返回對應(yīng)視圖
        return  "itemsList";
    }

對應(yīng)的Service實(shí)現(xiàn)層
    @Override
    public List<User> findAll() {
        UserExample example = new UserExample();
        List<User> list=    userMapper.selectByExample(example);
        return list;
    }

前端頁面實(shí)現(xiàn)細(xì)節(jié)
<table width="100%" border=1>
<tr>
    <td>ID</td>
    <td>用戶名</td>
    <td>密碼</td>
    <td>昵稱</td>
    <td>電子郵箱</td>
    <td>操作</td>
</tr>
<c:forEach items="${list}" var="item">
<tr>
    <td>
    <input type="checkbox" name="iduser" value="${item.iduser}">
    </td>
    <td>${item.username }</td>
    <td>${item.password }</td>
    <td>${item.nickname }</td>
    <td>${item.email }</td>
    <td><a href="${pageContext.request.contextPath }/user/edit?iduser=${item.iduser}">修改</a>
    <a href="${pageContext.request.contextPath }/user/deleteByID?iduser=${item.iduser}">刪除</a>
    </td>

</tr>
</c:forEach>

根據(jù)id修改相應(yīng)的數(shù)據(jù)

Controller層實(shí)現(xiàn)
    @RequestMapping("/edit")
    public String Edit(Integer iduser,Model model)
    {
        User user=userService.findById(iduser);
        model.addAttribute("item",user);
        return "editItem";
    }

Service實(shí)現(xiàn)層實(shí)現(xiàn)
    @RequestMapping("/edit")
    public String Edit(Integer iduser,Model model)
    {
        User user=userService.findById(iduser);
        //將要修改的值傳遞到前端
        model.addAttribute("item",user);
        return "editItem";
    }
    @RequestMapping(value ="/saveOrUpdate",method = RequestMethod.POST)
    public String saveOrUpdate(User user)
    {
        //保存修改的值
        userService.update(user);
        //跳轉(zhuǎn)到對應(yīng)的list路由
        return "redirect:list";
    }

前端頁面實(shí)現(xiàn)
<form id="itemForm" action="${pageContext.request.contextPath }/user/saveOrUpdate" method="post">
<input type="hidden" name="iduser" value="${item.iduser }"/>
修改商品信息:
<table width="100%" border=1>
<tr>
    <td>用戶名稱</td>
    <td><input type="text" name="username" value="${item.username }"/></td>
</tr>
<tr>
    <td>密碼</td>
    <td><input type="text" name="password" value="${item.password}"/></td>
</tr>
<tr>
    <td>昵稱</td>
    <td><input type="text" name="nickname"  value="${item.nickname}"/></td>
</tr>
<tr>
    <td>email</td>
    <td><input type="text" name="email"  value="${item.email}"/></td>
</tr>

<tr>
<td colspan="2" align="center"><input type="submit" value="提交"/>
</td>
</tr>
</table>

</form>

上述流程并未對是否查詢成功做對應(yīng)處理。有興趣的同學(xué)可以嘗試將其補(bǔ)充完整

根據(jù)id刪除對應(yīng)的數(shù)據(jù)

Controller層實(shí)現(xiàn)
    @RequestMapping("/deleteByID")
    public String deleteByID(Integer iduser)
    {

        userService.deleteById(iduser);
        return "redirect:list";
    }

Service實(shí)現(xiàn)層實(shí)現(xiàn)
    @Override
    public void deleteById(Integer iduser) {
        // TODO Auto-generated method stub
        userMapper.deleteByPrimaryKey(iduser);
    }

前端頁面上需要做的修改狸剃。已經(jīng)在上述列表頁面展示過了掐隐。在此不再贅述。

新增數(shù)據(jù)

Controller層實(shí)現(xiàn)
    //超鏈接到對應(yīng)的頁面
    @RequestMapping("/add")
    public String Add()
    {
        return "AddUser";
    }
    //保存數(shù)據(jù)到數(shù)據(jù)庫后跳轉(zhuǎn)到列表頁面
    @RequestMapping("/addUser")
    public String Insert(User user)
    {
        userService.insert(user);
        return "redirect:list";
    }

Service實(shí)現(xiàn)層實(shí)現(xiàn)
    @Override
    public void insert(User user) {
        userMapper.insert(user);

    }

前端頁面實(shí)現(xiàn)
<form id="itemForm" action="${pageContext.request.contextPath }/user/addUser" method="post">
商品信息:
<table width="100%" border=1>
<tr>
    <td>用戶名稱</td>
    <td><input type="text" name="username"/></td>
</tr>
<tr>
    <td>密碼</td>
    <td><input type="text" name="password"/></td>
</tr>
<tr>
    <td>昵稱</td>
    <td><input type="text" name="nickname"  /></td>
</tr>
<tr>
    <td>email</td>
    <td><input type="text" name="email"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="提交"/>
</td>
</tr>
</table>

</form>

以上就是一個(gè)完整的增刪改查的全部過程钞馁。已上傳到github.有需要的同學(xué)可以下載查看虑省。有什么問題可以與我交流喜歡的同學(xué)也不妨點(diǎn)一下喜歡

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市僧凰,隨后出現(xiàn)的幾起案子探颈,更是在濱河造成了極大的恐慌,老刑警劉巖训措,帶你破解...
    沈念sama閱讀 221,430評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件伪节,死亡現(xiàn)場離奇詭異,居然都是意外死亡绩鸣,警方通過查閱死者的電腦和手機(jī)怀大,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,406評論 3 398
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來全闷,“玉大人叉寂,你說我怎么就攤上這事∽苤椋” “怎么了屏鳍?”我有些...
    開封第一講書人閱讀 167,834評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長局服。 經(jīng)常有香客問我钓瞭,道長,這世上最難降的妖魔是什么淫奔? 我笑而不...
    開封第一講書人閱讀 59,543評論 1 296
  • 正文 為了忘掉前任山涡,我火速辦了婚禮,結(jié)果婚禮上唆迁,老公的妹妹穿的比我還像新娘鸭丛。我一直安慰自己,他們只是感情好唐责,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,547評論 6 397
  • 文/花漫 我一把揭開白布鳞溉。 她就那樣靜靜地躺著,像睡著了一般鼠哥。 火紅的嫁衣襯著肌膚如雪熟菲。 梳的紋絲不亂的頭發(fā)上看政,一...
    開封第一講書人閱讀 52,196評論 1 308
  • 那天,我揣著相機(jī)與錄音抄罕,去河邊找鬼允蚣。 笑死,一個(gè)胖子當(dāng)著我的面吹牛呆贿,可吹牛的內(nèi)容都是我干的嚷兔。 我是一名探鬼主播,決...
    沈念sama閱讀 40,776評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼榨崩,長吁一口氣:“原來是場噩夢啊……” “哼谴垫!你這毒婦竟也來了章母?” 一聲冷哼從身側(cè)響起母蛛,我...
    開封第一講書人閱讀 39,671評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎乳怎,沒想到半個(gè)月后彩郊,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,221評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡蚪缀,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,303評論 3 340
  • 正文 我和宋清朗相戀三年秫逝,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片询枚。...
    茶點(diǎn)故事閱讀 40,444評論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡违帆,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出金蜀,到底是詐尸還是另有隱情刷后,我是刑警寧澤,帶...
    沈念sama閱讀 36,134評論 5 350
  • 正文 年R本政府宣布渊抄,位于F島的核電站尝胆,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏护桦。R本人自食惡果不足惜含衔,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,810評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望二庵。 院中可真熱鬧贪染,春花似錦、人聲如沸催享。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,285評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽睡陪。三九已至寺渗,卻和暖如春匿情,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背信殊。 一陣腳步聲響...
    開封第一講書人閱讀 33,399評論 1 272
  • 我被黑心中介騙來泰國打工炬称, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人涡拘。 一個(gè)月前我還...
    沈念sama閱讀 48,837評論 3 376
  • 正文 我出身青樓玲躯,卻偏偏與公主長得像,于是被迫代替她去往敵國和親鳄乏。 傳聞我的和親對象是個(gè)殘疾皇子跷车,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,455評論 2 359

推薦閱讀更多精彩內(nèi)容