SSM框架整合基于JavaConfig配置方式也就是通过注解方式不用XML配置

SSM(Srping、SrpingMVC、Mybatis)现JAVA最主流三大框架,本文是通过全注解方式配置的,无XML。经常会看到各种繁多的XML配置非常的烦人,在Spring3之后,Spring支持使用JavaConfig来代替XML配置。废话不多说了,直接上代码。

创建JAVA Web项目

我这里使用的是IDEA开发工具,编辑器没关系,个人喜欢。项目构建通过Maven不需要导入Jar包,直接添加依赖即可。

完整目录结构如下
SSM框架整合基于JavaConfig配置方式也就是通过注解方式不用XML配置_第1张图片

依赖包pom.xml

主要依赖Spring、mybatis、log4j等。



<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0modelVersion>

  <groupId>com.wipgroupId>
  <artifactId>myblogartifactId>
  <version>1.0-SNAPSHOTversion>
  <packaging>warpackaging>

  <name>myblog Maven Webappname>
  
  <url>http://maven.apache.orgurl>

  <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <maven.compiler.source>1.7maven.compiler.source>
    <maven.compiler.target>1.7maven.compiler.target>

    <spring.version>4.3.7.RELEASEspring.version>

  properties>

  <dependencies>
    
    
      
      
      
      
    

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>${spring.version}version>
    dependency>


    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
      <version>${spring.version}version>
    dependency>


    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-coreartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-beansartifactId>
      <version>${spring.version}version>
    dependency>


    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>jstlartifactId>
      <version>1.2version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-txartifactId>
      <version>${spring.version}version>
    dependency>


    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-context-supportartifactId>
      <version>${spring.version}version>
    dependency>


    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-aopartifactId>
      <version>${spring.version}version>
    dependency>


    <dependency>
      <groupId>log4jgroupId>
      <artifactId>log4jartifactId>
      <version>1.2.17version>
    dependency>


    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>5.1.40version>
    dependency>


    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>3.4.2version>
    dependency>


    <dependency>
      <groupId>commons-dbcpgroupId>
      <artifactId>commons-dbcpartifactId>
      <version>1.2.1version>
    dependency>

    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>1.3.1version>
    dependency>


    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>commons-collectionsgroupId>
      <artifactId>commons-collectionsartifactId>
      <version>3.2.2version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webartifactId>
      <version>${spring.version}version>
    dependency>


    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-oxmartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-txartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>javaxgroupId>
      <artifactId>javaee-apiartifactId>
      <version>7.0version>
      
      <scope>providedscope>
    dependency>

    <dependency>
      <groupId>org.tautua.markdownpapersgroupId>
      <artifactId>markdownpapers-coreartifactId>
      <version>1.4.1version>
    dependency>



  dependencies>

  <build>
    <finalName>myblogfinalName>
    <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-clean-pluginartifactId>
          <version>3.0.0version>
        plugin>
        
        <plugin>
          <artifactId>maven-resources-pluginartifactId>
          <version>3.0.2version>
        plugin>
        <plugin>
          <artifactId>maven-compiler-pluginartifactId>
          <version>3.7.0version>
        plugin>
        <plugin>
          <artifactId>maven-surefire-pluginartifactId>
          <version>2.20.1version>
        plugin>
        <plugin>
          <artifactId>maven-war-pluginartifactId>
          <version>3.2.0version>
        plugin>
        <plugin>
          <artifactId>maven-install-pluginartifactId>
          <version>2.5.2version>
        plugin>
        <plugin>
          <artifactId>maven-deploy-pluginartifactId>
          <version>2.8.2version>
        plugin>
      plugins>
    pluginManagement>
  build>
project>

配置文件


  • Webinitializer

Webinitializer实现WebApplicationInitializer这个类的Onstartup方法,可以看做是Web.xml的替代,它是一个接口,在其中可以添加Servlet,Listener等,在加载Web项目的时候会加载这个接口实现类,从而起到Web.xml相同的作用。

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

public class WebInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(MyMVCConfig.class);
        servletContext.addFilter("encodingFilter", new CharacterEncodingFilter("UTF-8",true));
        ctx.setServletContext(servletContext);
        ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher",new DispatcherServlet(ctx));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);
    }
}


  • MyMVCConfig

MyMVCConfig继承自WebMvcConfigurerAdapter它是一个抽象类,配置类的作用就是Spring内部的一种配置方式,替代Spring、SpringMVC.xml配置的。

import org.apache.commons.dbcp.BasicDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

import java.io.IOException;

@Configuration
@EnableWebMvc
@ComponentScan("com.wip")
public class MyMVCConfig extends WebMvcConfigurerAdapter {


    /**
     * 配置页面路径和.jsp文件
     * @return
     */
    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/");
        viewResolver.setSuffix(".jsp");
        viewResolver.setViewClass(JstlView.class);
        return viewResolver;
    }

    /**
     * 静态资源配置
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("/WEB-INF/static/");
    }

    /**
     * 数据资源配置
     * @return
     */
    @Bean
    public BasicDataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=UTF-8");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        return dataSource;
    }

    /**
     * mybatis配置
     * @return
     */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean() {
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        try {
            sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mapping/*.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sqlSessionFactoryBean;
    }

    /**
     * mybatis配置
     * @return
     */
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.wip.dao");
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
        return mapperScannerConfigurer;
    }


    /**
     * 添加拦截登录拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptors());
    }

    /**
     * 拦截器注入到Bean
     * @return
     */
    @Bean
    public LoginInterceptors loginInterceptors() {
        return new LoginInterceptors();
    }

}
viewResolver

这个对我们来说很熟悉,只要我们配置html、Jsp页面视图时就会用到InternalResourceViewResolver配置类,然后设置preffix、suffix参数进行配置视图文件路径前缀与后缀。

sqlSessionFactoryBean、dataSource

这里主要配置数据源,Spring的事务管理和Dao接口的扫描,以及MyBatis的一些配置文件的扫描。

addInterceptors

在之前Xml配置形式天下的时候,我们都是在spring-mvc.xml配置文件内添加标签配置拦截器。我这里添加了一个登录拦截器。LoginInterceptors登录拦截器

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

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

/**
 * 登录拦截器
 */
public class LoginInterceptors implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setCharacterEncoding("UTF-8");
        StringBuffer requestURL = request.getRequestURL();
        if (requestURL.toString().contains("admin") &&
                !requestURL.toString().contains("admin/login") &&
                !requestURL.toString().contains("admin/dologin")) {
            Object user = request.getSession().getAttribute("user");
            if (null == user) {
                response.sendRedirect("/admin/login");
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
log4j.properties主要是日志文件
log4j.rootLogger=DEBUG,stdout
log4j.logger.org.mybatis=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n
jdbc.properties主要是数据源配置
db.driverClass=com.mysql.jdbc.Driver
db.url=jdbc:mysql//localhost:3306/blog
db.username=root
db.password=root
db.initialSize=0
db.maxActive=500
db.maxIdle=20
db.minIdle=1
db.maxWait=60000
到这里我们的框架基本就成形了

下面进行测试

文章结尾提供源码下载地址 在数据库里新建表(数据库是用的mysql)
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `password` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;
  • 实体类User
public class User {
    private long id;
    private String username;
    private String password;

    public long getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
  • Mapper文件Usermapper.xml


<mapper namespace="com.wip.dao.UserDao">
    
    <select id="getUser" resultType="com.wip.model.User" parameterType="string">
        SELECT * FROM user WHERE username=#{username} AND password=#{password}
    select>
mapper>
  • UserDao接口
import com.wip.model.User;
import org.apache.ibatis.annotations.Param;

public interface UserDao {
    /**
     * 通过用户名和密码查找用户
     * @param username
     * @param password
     * @return
     */
    User getUser(@Param("username") String username,@Param("password") String password);
}
  • UserService服务层
import com.wip.dao.UserDao;
import com.wip.model.User;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class UserService {
    @Resource
    private UserDao userDao;

    public boolean login(String username, String password) {
        User user = userDao.getUser(username,password);
        if (user == null) {
            return false;
        }else {
            return true;
        }
    }
}
  • Controller
   @RequestMapping(value = "/admin/dologin", method = RequestMethod.POST)
   public String doLogin(HttpServletRequest request, User user, Model model) {
       System.out.println("user.getUsername():" + user.getUsername() + ";user.getPassword()" + user.getPassword());
       if (userService.login(user.getUsername(),user.getPassword())) {
           request.getSession().setAttribute("user",user);
           model.addAttribute("user",user);
           return "redirect:/admin";
       } else {
           model.addAttribute("error","用户名或密码错误");
           return "admin/login";
       }
   }
  • WEB-INF/admin下的login.jsp
<%--
  Created by IntelliJ IDEA.
  User: Kyrie
  Date: 2018/7/20
  Time: 9:09
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
    String contextPath = request.getContextPath();
%>
<html>
<head>
    <title>登录title>
    <script src="<%=contextPath%>/static/jquery-3.1.1.js">script>
    <script src="<%=contextPath%>/static/bootstrap/js/bootstrap.js">script>
    <link href="<%=contextPath%>/static/bootstrap/css/bootstrap.css" rel="stylesheet"/>
    <link href="<%=contextPath%>/static/bootstrap/css/bootstrap-theme.css" rel="stylesheet"/>
    <link href="<%=contextPath%>/static/signin.css" rel="stylesheet"/>
head>
<body>
<div class="container">

    <form class="form-signin" action="/admin/dologin" method="post">
        <h2 class="form-signin-heading">请登录h2>
        <div style="height: 25px; color: red;">
            <%if (request.getAttribute("error") != null) {%>
                <%=request.getAttribute("error")%>
            <%}%>
        div>
        <label for="inputEmail" class="sr-only">请输入用户名label>
        <input type="text" id="inputEmail" name="username" value="Kyrie" class="form-control" placeholder="用户名" required autofocus>
        <label for="inputPassword" class="sr-only">密码label>
        <input type="password" id="inputPassword" name="password" value="123456" class="form-control" placeholder="密码" required>
        <div class="checkbox">
            <label>
                <input type="checkbox" value="remember-me"> 记住我
            label>
        div>
        <button class="btn btn-lg btn-primary btn-block" type="submit">登录button>
    form>

div>
body>
html>
  • 运行项目,访问localhost:8080/admin
    SSM框架整合基于JavaConfig配置方式也就是通过注解方式不用XML配置_第2张图片
    登录成功
    SSM框架整合基于JavaConfig配置方式也就是通过注解方式不用XML配置_第3张图片

项目源码:GitHub

不足的地方,请留言会及时改正。觉得可以的话帮忙Start

你可能感兴趣的:(Spring)