码迷,mamicode.com
首页 > 编程语言 > 详细

spring+springMvc+mybatis框架简单实例

时间:2018-03-02 10:20:22      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:only   err   can   service   autowire   user   ado   reac   cdata   

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" 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">
  <display-name>ssm</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  

    
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:config/applicationContext.xml</param-value>
  </context-param>
  <servlet>
    <servlet-name>spring-mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:config/spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    <async-supported>true</async-supported>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring-mvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  
      <!--编码过滤器  -->
  <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>  
        <init-param>  
            <param-name>forceEncoding</param-name>  
            <param-value>true</param-value>  
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>characterEncodingFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>
    
    
</web-app>
View Code

spring-mvc.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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd                        
                        http://www.springframework.org/schema/context 
                        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
    <!-- 注解配置 自动扫描controller  -->
    <context:component-scan base-package="com.controller" />

</beans>
View Code

applicationContext.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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/tx 
                        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
                        http://www.springframework.org/schema/aop 
                        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                        http://www.springframework.org/schema/context 
                        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
        
        <!-- 注解配置 自动扫描装载service -->
        <context:component-scan base-package="com.service" />
        <!-- 1.数据源配置 -->    
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
            destroy-method="close">
            <property name="driverClassName" value="com.mysql.jdbc.Driver" />
            <property name="url" value="jdbc:mysql://localhost:3306/com?useUnicode=true&characterEncoding=utf-8" />
            <property name="username" value="root" />
            <property name="password" value="root" />
        </bean>
        <!-- 2.sqlSessionFactory配置 -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
        </bean>
        <!-- 3.事务管理器配置 -->
        <bean id="txManager"
            class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource" />
        </bean>
        <!-- 4.事务通知配置 -->
        <tx:advice id="txAdvice" transaction-manager="txManager">
            <tx:attributes>
                <tx:method name="*" />
            </tx:attributes>
        </tx:advice>
        <!-- 5.事务切面配置 -->
        <aop:config>
        <!-- 只对业务逻辑层(service层)实施事务 -->
            <aop:pointcut id="serviceCut"
                expression="execution(* com.service.*Service.*(..))" />
            <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceCut" />
        </aop:config>
        <!-- 自动扫描mapper映射文件 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.mapper" />
        </bean>
        
        
        
        
        
        
        
        
        
        
        
        
</beans>        
View Code

controller(控制层)

技术分享图片
package com.controller;

import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.entity.User;
import com.service.UserService;

@Controller
@RequestMapping("/userController")
public class UserController {

    
    private UserService userService;
    
    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }


    @RequestMapping(params="toUserList")
    public String selectList(HttpServletRequest req) {
        
        List<User> userList=userService.selectList();
        
        req.setAttribute("userList", userList);
        return "user/userList.jsp";
    }
    

    /*@RequestMapping(params = "doDel")
    @ResponseBody
    public void doDel(User user,HttpServletResponse response) throws IOException{
        
        Boolean ok=userService.deleteById(user);
        
        if(ok){
            String result= "{\"result\":\"成功\"}";
            response.getWriter().write(result);
        }else{
            String result= "{\"result\":\"失败\"}";
            response.getWriter().write(result);
        }
        
    }*/
    
    @RequestMapping(params = "toAdd")
    public String toAdd(User user,HttpServletRequest req){
        
        if(user.getId()!=null && !"".equals(user.getId())){
            
            user=userService.selectById(user);
            req.setAttribute("u", user);
        }
        
        return "user/addOrUpdUser.jsp";
    }
    
    @RequestMapping(params = "doAdd")
    public String doAdd(User user,HttpServletResponse response,HttpServletRequest req){
            
            if(user.getId()!=null && !"".equals(user.getId())){
                userService.doUpdate(user);
            }else{
                user.setId(UUID.randomUUID().toString().replace("-", ""));
                userService.doAdd(user);
            }
            
        
        return "redirect:userController.do?toUserList";
    }
    @RequestMapping(params = "doDel")
    @ResponseBody
    public void doDel(User user,HttpServletResponse response){
        
        Boolean ok= userService.doDel(user);
        
    }
    
}
View Code

service(服务层)

技术分享图片
package com.service;

import java.util.List;

import com.entity.User;

public interface UserService {

    List<User> selectList();

    

    void doAdd(User user);

    User selectById(User user);

    void doUpdate(User user);
    
    Boolean doDel(User user);

}
View Code
技术分享图片
package com.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.entity.User;
import com.mapper.UserMapper;
import com.service.UserService;
@Service
public class UserServiceImpl implements UserService {

    private UserMapper userMapper;
    
    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }


    @Override
    public List<User> selectList() {
        
        return userMapper.selectList();
    }




    @Override
    public void doAdd(User user) {
        
        userMapper.doAdd(user);
    }


    @Override
    public User selectById(User user) {
        
        return userMapper.selectById(user);
    }


    @Override
    public void doUpdate(User user) {
        
        userMapper.doUpdate(user);
    }

    @Override
    public Boolean doDel(User user) {
        
        return userMapper.doDel(user)>0;
    }


    
}
View Code

mapper(持久层)

技术分享图片
package com.mapper;

import java.util.List;

import com.entity.User;

public interface UserMapper {

    List<User> selectList();

    
    User selectById(User user);

    void doUpdate(User user);

    void doAdd(User user);


    int doDel(User user);

}
View Code

mapper.xml(mapper映射文件)

技术分享图片
<?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.mapper.UserMapper">
    <!-- parameterType="com.entity.User" -->
    <select id="selectList"  resultType="com.entity.User">
        select * from user;
    </select>
    <select id="selectById" parameterType="com.entity.User" resultType="com.entity.User">
        select * from user where 1=1 and id=#{id}
    </select>
    <update id="doUpdate" parameterType="com.entity.User">
        update user  set
        <if test="userName!=null and userName!=‘‘">
        userName=#{userName}
        </if>
         where 1=1 and id=#{id}
    </update>
    <insert id="doAdd" parameterType="com.entity.User">
            insert into user
        (
        id
        <if test="userName!=null and userName!=‘‘">
        ,userName
        </if>
    
        )
        values
        (
        #{id}
        <if test="userName !=null and userName !=‘‘">
        ,#{userName}
        </if>
         )
    </insert>
    <delete id="doDel" parameterType="com.entity.User">
        delete from user where id=#{id}
    </delete>
</mapper>
View Code

entity(实体)

技术分享图片
package com.entity;

public class User {

    private String id;
    private String userName;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    
    
}
View Code

视图层(jsp)

技术分享图片
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>userList</title>
</head>
<script type="text/javascript" src="/ssm/js/jquery-1.10.2.js"></script>  
<style type="text/css">
    .tab{
     width:50%; 
     height:30%;
     text-align:center;
     border-collapse:collapse;
     }
</style>
<body>
        <button onclick="toAdd()">添加</button>
        <table  class="tab" border="1">
        <tr>
        <td>编号</td>
        <td>姓名</td>
        <td>操作</td>
        </tr>
    <c:forEach var="user" items="${userList}">
        <tr>
        <td>${user.id}</td>
        <td>${user.userName}</td>
        <td> 
            <a href="/ssm/userController.do?toAdd&id=${user.id}">编辑</a>  
          <%--   <a href="javascript:doDel(‘${user.id}‘)">删除</a> </td> --%>
        </tr>
    </c:forEach>    
        </table>
    
</body>
<script type="text/javascript">
             function doDel(id){
                 debugger;
                  $.ajax({
                         type: "POST",
                         url: "/ssm/userController.do?doDel",
                         data: {
                             id : id
                                },
                         dataType: "json",
                         success: function(data){
                             location.reload();
                                   alert(data.result);  
                                  }
                         });
            } 
            
            function toAdd(){
                location.href="/ssm/userController.do?toAdd";
            }
</script>

</html>
View Code
技术分享图片
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>addOrUpdUser</title>
</head>
<body>

     <form action="/ssm/userController.do?doAdd"  method="post">  
        编号:<input type="text"  name="id" value="${u.id}" readonly="readonly">  
        姓名:<input type="text"  name="userName"  value="${u.userName}">  
        <button type="submit">确定</button> 
    </form> 


</body>
</html>
View Code

 

spring+springMvc+mybatis框架简单实例

标签:only   err   can   service   autowire   user   ado   reac   cdata   

原文地址:https://www.cnblogs.com/libf/p/8491266.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!