spring+springMvc+mybatis框架简单实例

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>

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>

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>        

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);

    }

}

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);

}

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;
    }

}

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);

}

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>

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;
    }

}

视图层(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>

<%@ 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>

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

时间: 2024-11-06 11:27:25

spring+springMvc+mybatis框架简单实例的相关文章

spring+springMvc+hibernate框架简单实例

配置文件: 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

SSM(Spring + Springmvc + Mybatis)框架面试题

JAVA SSM框架基础面试题https://blog.csdn.net/qq_39031310/article/details/83050192 SSM(Spring + Springmvc + Mybatis)框架面试题 一.Spring面试题 1.Spring 在ssm中起什么作用? Spring:轻量级框架 作用:Bean工厂,用来管理Bean的生命周期和框架集成. 两大核心:1.IOC/DI(控制反转/依赖注入) :把dao依赖注入到service层,service层反转给action

用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建三:配置spring并测试

这一部分的主要目的是 配置spring-service.xml  也就是配置spring  并测试service层 是否配置成功 用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建二:配置MyBatis 并测试(2 配置spring-dao和测试)在这个基础上面 继续进行spring的配置. 回顾上面  我们已经成功测试通过了Mybatis的配置. 这时候的目录结构是: 一:下面我们继续补充目录结构,在com.peakfortake的文件目录项目 

SSM:spring+springmvc+mybatis框架中的XML配置文件功能详细解释

SSM:spring+springmvc+mybatis框架中的XML配置文件功能详细解释 2016-04-14 23:40 13030人阅读 评论(2) 收藏 举报 分类: SSM(7) 这几天一直在整合SSM框架,虽然网上有很多已经整合好的,但是对于里面的配置文件并没有进行过多的说明,很多人知其然不知其所以然,经过几天的搜索和整理,今天总算对其中的XML配置文件有了一定的了解,所以拿出来一起分享一下,希望有不足的地方大家批评指正~~~ 首先   这篇文章暂时只对框架中所要用到的配置文件进行解

Spring+SpringMvc+Mybatis框架集成搭建教程

一.背景 最近有很多同学由于没有过SSM(Spring+SpringMvc+Mybatis , 以下简称SSM)框架的搭建的经历,所以在自己搭建SSM框架集成的时候,出现了这样或者那样的问题,很是苦恼,网络上又没有很详细的讲解以及搭建的教程.闲来无事,我就利用空闲时间来写这样一个教程和搭建步骤,来帮助那些有问题的小伙伴,让你从此SSM搭建不再有问题. 二.教程目录 1.Spring+SpringMvc+Mybatis框架集成搭建教程一(项目创建) 2.Spring+SpringMvc+Mybat

Spring+SpringMVC+Mybatis+Mysql整合实例【转】

本文要实现Spring+SpringMVC+Mybatis+Mysql的一个整合,实现了SpringMVC控制访问的页面,将得到的页面参数传递给Spring中的Mybatis的bean类,然后查找Mysql数据的功能,并通过JSP显示出来.建议可以先看笔者另一文章Mybatis与Spring整合创建Web项目 .笔者觉得整合过程中问题比较多的还是Spring+Mybatis的整合,SpringMVC的整合还是比较简单. Spring        Spring 是一个开源框架, Spring 是

Spring+SpringMVC+MyBatis框架的搭建

1,SSM的简介 SSM(Spring+SpringMVC+MyBatis)框架集由Spring.SpringMVC.MyBatis三个开源框架整合而成,常作为数据源较简单的web项目的框架. 其中spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架. SpringMVC分离了控制器.模型对象.分派器以及处理程序对象的角色,这种分离让它们更容易进行定制. MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架. 2,SSM的搭建 项目的结构如下: 首先配

Spring+SpringMVC+Mybatis+Mysql整合实例

林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 本文要实现Spring+SpringMVC+Mybatis+Mysql的一个整合,实现了SpringMVC控制访问的页面,将得到的页面参数传递给Spring中的Mybatis的bean类,然后查找Mysql数据的功能,并通过JSP显示出来.建议可以先看笔者另一文章Mybatis与Spring整合创建Web项目.笔者觉得整合过程中问题比较多的还是Spring+Mybatis的整合,Spring

搭建Spring + SpringMVC + Mybatis框架之二(整合Spring和Mybatis)

整合Spring和Mybatis 首先给出完整的项目目录: (1)引入项目需要的jar包 使用http://maven.apache.org作为中央仓库即可. Spring核心包,mybatis核心包,json数据需要的包[经常需要用到],log4j日志管理包. 1 <projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance&q