频道栏目
首页 > 资讯 > Java > 正文

搭建SpringMVC4.3.2+MyBatis3.4.1框架

16-09-13        来源:[db:作者]  
收藏   我要投稿

1、本项目由maven管理

2、配置中包含了本地环境的一些配置,如果在你的机子上报错,请删除这部分配置代码即可

一、创建maven WEB项目,配置pom.xml文件

直接上代码


    4.0.0
    com
    zsx
    0.0.1-SNAPSHOT
    war
    ssm maven web
    null

    
        UTF-8
        1.7
        
        4.3.2.RELEASE
        
        3.4.1
        
        1.7.21
        1.2.17
    


    

        
        
            org.springframework
            spring-webmvc
            ${spring.version}
        

        
        
        
            org.springframework
            spring-core
            ${spring.version}
        

        
            org.springframework
            spring-web
            ${spring.version}
        

        
            org.springframework
            spring-oxm
            ${spring.version}
        

        
            org.springframework
            spring-tx
            ${spring.version}
        

        
            org.springframework
            spring-jdbc
            ${spring.version}
        

        
            org.springframework
            spring-context-support
            ${spring.version}
        

        
            org.springframework
            spring-orm
            ${spring.version}
        

        
            org.springframework
            spring-test
            ${spring.version}
        
        

        
        
            org.aspectj
            aspectjweaver
            1.8.9
        

        
         
            org.mybatis 
            mybatis 
            ${mybatis.version} 
        

        
         
            org.mybatis 
            mybatis-spring 
            1.3.0 
        


        
        
            mysql
            mysql-connector-java
            5.1.38
        

        
        
            junit
            junit
            4.12
            test
        

        
        
            com.alibaba
            druid
            1.0.25
        

        
        
            com.alibaba
            fastjson
            1.2.16
        

        
        
            com.fasterxml.jackson.core
            jackson-databind
            2.8.2
        

        
        
            commons-fileupload
            commons-fileupload
            1.3.2
        

        
        
        
            log4j
            log4j
            ${log4j.version}
        
        
            org.slf4j
            slf4j-api
            ${slf4j.version}
        
        
            org.slf4j
            slf4j-log4j12
            ${slf4j.version}
        
        


    


    
        ssm

        
        src/main/java
        src/test/java

        
            
                src/main/resources
            
        
        
            
                src/test/resources
            
        

        src/main/webapp/WEB-INF/classes
        src/main/webapp/WEB-INF/classes


        
        
            
            
                org.apache.maven.plugins
                maven-compiler-plugin
                3.1
                
                    ${jdk.version} 
                    ${jdk.version} 
                    
                    
                    
                    ${project.build.sourceEncoding}
                    true
                    512m
                    2048m
                
            

            
            
                org.apache.maven.plugins
                maven-resources-plugin
                2.4.3
                  
                      
                        compile  
                      
                  
                  
                    UTF-8
                
            


        


    

二、项目资源及其它配置文件

先说明一下项目的目录结构吧,如下

项目名称
    | pom.xml
    | src
        | main
            | java
                | com
                    | zsx
                        | core
                        | web  
                            | controller
                            | dao
                            | entity
                            | mapping
                            | service
                                |Impl

            | resources
                | conf
                    | jdbc.properties
                | applicationContext.xml
                | log4j.properties
                | springMVC-servlet.xml
                | spring-mybatis.xml

            | webapp
                | WEB-INF
                    | web.xml
                | index.jsp
        | test
            | UtilTest.java

现在说一下 \src\main\resources 目录下的配置文件,

conf 目录下 jdbc.properties 是数据库连接配置 applicationContext.xml 是spring的主要配置文件,(自动扫描) log4j.properties 记录日志 springMVC-servlet.xml 配置springMVC,(扫描注解、视图解析器、拦截器、上传文件配置) spring-mybatis.xml 配置数据源、注解、事务等

下面放代码:

jdbc.properties

# MySql 
jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/mytest?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true
jdbc_username=root
jdbc_password=root

applicationContext.xml




    
    
    
        
            
                classpath:conf/jdbc.properties
            
        
    

    
    

            

springMVC-servlet.xml




    
    
        
        
        
        
    

    
    
    
    
    
    
    
    
    
    
    
    


    
    

    
    
    
    
    

    
    



    
    

    
    


    
    
        
        
        
    

    
    
        
            
                
                    
                        
                            text/plain;charset=UTF-8
                        
                    
                
                
                    
                        
                            application/json;charset=UTF-8
                        
                    
                
            
        
    

    
    
        
            UTF-8
        
        
            104857600 
        
        
            4096
        
    

    
    
        
        
            
            
                
                
                    
                        wechat
                        checkname
                        register
                        login
                        logout
                        validatecode
                        user/getUserList
                    
                
            
        
    

  

spring-mybatis.xml




    
    

        
        
        

        
        
        
        
        
        
        
        
        
        

        
        
        
        

        
        
        
        
        
        

        
        
    


    
    
        
        
         
    

      
      
        
          
    

      
      
          
    

    
    

    
    
        
            
            
            
            
            
            
            
            
            

            
            
            
            
            

            
        
    


    
    
    
    
    
    
    
        
            
        
    

三、后台核心代码 java\src

1. 创建实体类对象 src\main\java\com\zsx\web\entity\User.java

package com.zsx.web.entity;

import java.io.Serializable;

public class User implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private String id;//

    private String name;//

    private String pwd;//

    public String getId() {
         return id;
    }

    public void setId(String id) {
         this.id = id;
    }

    public String getName() {
         return name;
    }

    public void setName(String name) {
         this.name = name;
    }

    public String getPwd() {
         return pwd;
    }

    public void setPwd(String pwd) {
         this.pwd = pwd;
    }


}

2. Mybatis的映射xml文件 src\main\java\com\zsx\web\mapping\UserMapper.xml





  

  
    insert into user (`id` ,`name` ,`pwd` ) values (#{id},#{name},#{pwd})
  

  
    delete from user where  `id` = #{id}
  

3. 与mapper.xml对应的dao层文件

package com.zsx.web.dao;

import org.apache.ibatis.annotations.Param;

import com.zsx.web.entity.User;

public interface UserMapper {

    int deleteByPrimaryKey(@Param(value="id")String id);

    int insert(User user);

    User selectByPrimaryKey(@Param(value="id")String id);
}

4. 逻辑层service 定义接口 及 其实现类

src\main\java\com\zsx\web\service\UserService.java
package com.zsx.web.service;
import com.zsx.web.entity.User;

public interface UserService {

    User searchById(String id);

    int insert(User user);

    int delete(String id);
}
src\main\java\com\zsx\web\service\Impl\UserServiceImpl.java
package com.zsx.web.service.Impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zsx.web.dao.UserMapper;
import com.zsx.web.entity.User;
import com.zsx.web.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    public User searchById(String id){
        return userMapper.selectByPrimaryKey(id);
    }

    @Transactional
    public int insert(User user) {
        return userMapper.insert(user);
    }

    @Transactional
    public int delete(String id){
        return userMapper.deleteByPrimaryKey(id);
    }

}

5. controller 控制层(action层) src\main\java\com\zsx\web\controller\UserController.java

package com.zsx.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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 com.alibaba.fastjson.JSON;
import com.zsx.web.entity.User;
import com.zsx.web.service.UserService;

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取用户
     */
    @RequestMapping("/getUserList")
    public void getJson(HttpServletRequest request, HttpServletResponse response)
            throws IOException {        
        User user = userService.searchById("1");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(JSON.toJSONString(user));
        out.flush();
        out.close();
    }
}

6. 拦截器代码(可忽略)

我在springMVC-servlet.xml中配置了拦截器,所以要添加下面的一个方法,如果不想添加,直接去springMVC-servlet.xml 中把拦截器的标签注释掉即可。

src\main\java\com\zsx\core\interceptors\AuthInterceptor.java
package com.zsx.core.interceptors;

import java.util.List;

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

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class AuthInterceptor implements HandlerInterceptor {

    private List excludeUrls;// 不需要拦截的资源
    public List getExcludeUrls() {
        return excludeUrls;
    }
    public void setExcludeUrls(List excludeUrls) {
        this.excludeUrls = excludeUrls;
    }

    /**
     * 这个方法的主要作用是用于清理资源的,当然这个方法也只能在当前这个Interceptor的preHandle方法的返回值为true时才会执行。
     */
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO Auto-generated method stub

    }

    /**
     * 在Controller的方法调用之后执行
     */
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
        // TODO Auto-generated method stub

    }

    /** 
     * preHandle方法是进行处理器拦截用的,顾名思义,该方法将在Controller处理之前进行调用,
     * SpringMVC中的Interceptor拦截器是链式的,可以同时存在多个Interceptor,
     * 然后SpringMVC会根据声明的前后顺序一个接一个的执行,而且所有的Interceptor中的preHandle方法都会在Controller方法调用之前调用。
     * SpringMVC的这种Interceptor链式结构也是可以进行中断的,这种中断方式是令preHandle的返 
     * 回值为false,当preHandle的返回值为false的时候整个请求就结束了。 
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        HttpSession session = request.getSession();
        String requestURI = request.getRequestURI();
        String contextPath = request.getContextPath();
        String url = requestURI.substring(contextPath.length() + 1);

        // 测试用
        if (true) {
            return true;
        }

        // 如果要访问的资源是不需要验证的
        if (url.indexOf("wechatController") > -1 || excludeUrls.contains(url)) {
            return true;
        }

        // 获取用户 信息 验证 然后判断  TODO

        return false;
    }

}

四、单元测试

src\test\java\ssm\UtilTest.java

package ssm;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import com.alibaba.fastjson.JSON;
import com.zsx.web.dao.UserMapper;
import com.zsx.web.entity.User;
import com.zsx.web.service.UserService;

/**
 * 单元测试
 * @author developer
 */
// 告诉spring怎样执行
@RunWith(SpringJUnit4ClassRunner.class)
//  标明是web应用测试
@WebAppConfiguration(value = "src/main/webapp") //可以不填,默认此目录
// 配置文件地址
@ContextConfiguration(locations = { "file:src/main/resources/applicationContext.xml", "file:src/main/resources/spring-mybatis.xml", "file:src/main/resources/springMVC-servlet.xml" })

public class UtilTest {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    @Before
    public void before(){
        System.out.println("准备测试!!!");
    }

    @After
    public void After(){
        System.out.println("测试结束!!!");
    }

    @Test
    public void get() {
        User user = userMapper.selectByPrimaryKey("1");
        System.out.println(JSON.toJSONString(user));
    }

    @Test
    public void add(){
        User user = new User();
        user.setId("7");
        user.setName("wodemingzi");
        user.setPwd("!@#$%^&");
        userService.insert(user);
    }

}

当把上面的单元测试代码写完后,就可以运行单元测试了,选中方法名add 右键 Debug As —— JUnit Test 即可。


最后,忘了配置web.xml了,代码如下: src\main\webapp\WEB-INF\web.xml




    Archetype Created Web Application

    
    
        contextConfigLocation
        
            classpath:applicationContext.xml,classpath:spring-mybatis.xml

        
    

    
        spring监听器
        org.springframework.web.context.ContextLoaderListener
    

    
    
        Introspector缓存清除监听器
        org.springframework.web.util.IntrospectorCleanupListener
    

    
    
    
        springMVC
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath:springMVC-servlet.xml
        
        
        1
    
    
        springMVC
        /
    


    
    
        characterEncodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            UTF-8
        
        
            forceEncoding
            true
        
    
    
        characterEncodingFilter
        /*
    

    
    
        30
    

    
        index.jsp
    

    
    
        
        404
        /WEB-INF/errorpage/404.jsp
    
    
        
        405
        /WEB-INF/errorpage/405.jsp
    
    
        
        500
        /WEB-INF/errorpage/500.jsp
    

至此,整个项目算是搭建完毕了,将项目发布到tomcat或jetty中,在浏览器中输入:

http://localhost:[端口号]/[你的项目名]/user/getUserList

就可以看到效果了

五、注意事项

如果你的文件目录名称跟我的不一样,请注意修改applicationContext.xml 、spring-mybatis.xml 、springMVC-servlet.xml 配置文件里的各种路径属性 注意 jdbc.properties 里数据库连接地址配置, ip、端口号、库名等 mybatis的Mapper映射文件只写了最基本的增删查功能,其它的请自行添加 本篇代码仅在spring4.3.2和Mybatis3.4.1版本下运行测试,其它版本请自行查看版本变动
相关TAG标签
上一篇:httppost 200、300、400、500 错误分析,HttpPost、HttpGet关于URL重定向区别
下一篇:IE浏览器漏洞利用技术的演变(一)
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站