告别XML 使用JAVA配置SpringMVC

2017-08-04  本文已影响0人  Gxiner
eclipse4.7.0 + jdk8 + tomcat9 + spring4.2.0 + mybatis
Maven项目结构
jitu.png
POM.XML
<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.0</modelVersion>

  <groupId>com.yg</groupId>
  <artifactId>YouGan</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>YouGan</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java-version>1.8</java-version>
    <!-- Web -->
    <jsp.version>2.2</jsp.version>
    <jstl.version>1.2</jstl.version>
    <servlet.version>3.1.0</servlet.version>
    <!-- Spring -->
    <spring-framework.version>4.2.0.RELEASE</spring-framework.version>
    <!-- logging -->
    <org.slf4j-version>1.6.6</org.slf4j-version>
    <!-- mybatis版本号 -->  
    <mybatis.version>3.2.6</mybatis.version>
  </properties>
  
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
    <!-- java EE component -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>${jstl.version}</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>${servlet.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>${jsp.version}</version>
      <scope>provided</scope>
    </dependency>
    
    <!-- Spring -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${spring-framework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring-framework.version}</version>
      <exclusions>
        <!-- Exclude Commons Logging in favor of SLF4j -->
        <exclusion>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>${spring-framework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring-framework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring-framework.version}</version>
    </dependency>   
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring-framework.version}</version>
    </dependency>  
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring-framework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring-framework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${spring-framework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring-framework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring-framework.version}</version>
    </dependency>

    <!-- Logging -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${org.slf4j-version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jcl-over-slf4j</artifactId>
      <version>${org.slf4j-version}</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${org.slf4j-version}</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.15</version>
      <exclusions>
        <exclusion>
          <groupId>javax.mail</groupId>
          <artifactId>mail</artifactId>
        </exclusion>
        <exclusion>
          <groupId>javax.jms</groupId>
          <artifactId>jms</artifactId>
        </exclusion>
        <exclusion>
          <groupId>com.sun.jdmk</groupId>
          <artifactId>jmxtools</artifactId>
        </exclusion>
        <exclusion>
          <groupId>com.sun.jmx</groupId>
          <artifactId>jmxri</artifactId>
        </exclusion>
      </exclusions>
      <scope>runtime</scope>
    </dependency>

    <!-- @Inject -->
    <dependency>
      <groupId>javax.inject</groupId>
      <artifactId>javax.inject</artifactId> 
      <version>1</version>
    </dependency>
       
    <!-- 数据库连接 -->
    <!-- DruidDataSource用到 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.0.16</version>  
    </dependency>
    <!-- mysql -->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
        <version>2.1.1</version>
    </dependency>
    
    <!-- mybatis核心包 -->  
    <dependency>  
        <groupId>org.mybatis</groupId>  
        <artifactId>mybatis</artifactId>  
        <version>${mybatis.version}</version>  
    </dependency>  
    <!-- mybatis/spring包 -->  
    <dependency>  
        <groupId>org.mybatis</groupId>  
        <artifactId>mybatis-spring</artifactId>  
        <version>1.2.2</version>  
    </dependency>  
  </dependencies>
  <build>
    <finalName>YouGan</finalName>
  </build>
</project>
WeblabWebAppInitializer.JAVA

这是servlet配置

package com.yg.YouGan.config;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WeblabWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] {};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { WebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);

        FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("characterEncodingFilter",
                new CharacterEncodingFilter());
        encodingFilter.setInitParameter("encoding", "UTF-8");
        encodingFilter.setInitParameter("forceEncoding", "true");
        encodingFilter.addMappingForUrlPatterns(null, true, "/*");

    }
}
WebConfig.JAVA

这是springmvc配置

package com.yg.YouGan.config;

import java.beans.PropertyVetoException;
import java.io.IOException;

import javax.sql.DataSource;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.alibaba.druid.pool.DruidDataSource;

/**
 * web组件相关配置
 * 
 * @author WebConfig
 *
 */
@Configuration
@EnableWebMvc
@PropertySource("classpath:/jdbc.properties")
@MapperScan(basePackages = "com.yg.YouGan.mybatis")
@ComponentScan(basePackages = { "com.yg.YouGan.controller,com.yg.YouGan.service.Imp,com.yg.YouGan.mybatis" })
public class WebConfig extends WebMvcConfigurerAdapter {

    @Autowired
    Environment env;

    /**
     * 配置JSP视图解析器
     * 
     * @return
     */
    @Bean
    public ViewResolver viewResolver() {
        System.out.println("配置试图解析");
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) throws IOException {
        System.out.println("工厂配置mybatis");
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(resourcePatternResolver.getResources("classpath*:/*Mapper.xml"));
        return sqlSessionFactoryBean;
    }

    /**
     * 配置静态资源的处理
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.out.println("配置静态资源处理");
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
        registry.addResourceHandler("js/**").addResourceLocations("/js/");
        registry.addResourceHandler("css/**").addResourceLocations("/css/");
        registry.addResourceHandler("img/**").addResourceLocations("/img/");
        registry.addResourceHandler("images/**").addResourceLocations("/images/");
        registry.addResourceHandler("fonts/**").addResourceLocations("/fonts/");
        registry.addResourceHandler("plugins/**").addResourceLocations("/plugins/");
    }

    @Bean
    public DataSource dataSource() throws PropertyVetoException {
        System.out.println("数据库连接");
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(env.getProperty("jdbc.driver"));
        dataSource.setUrl(env.getProperty("jdbc.url"));
        dataSource.setUsername(env.getProperty("jdbc.username"));
        dataSource.setPassword(env.getProperty("jdbc.password"));
        dataSource.setInitialSize(Integer.valueOf(env.getProperty("dbcp.initialSize")));
        dataSource.setMaxActive(Integer.valueOf(env.getProperty("dbcp.maxActive")));
        // dataSource.setMaxIdle(Integer.valueOf(env.getProperty("dbcp.minIdle")));
        // dataSource.setMaxIdle(Integer.valueOf(env.getProperty("dbcp.maxIdle")));
        dataSource.setMaxWait(Long.valueOf(env.getProperty("dbcp.maxWait")));
        return dataSource;

    }
}
jdbc.properties

数据库配置文件,这里我用的是oracle

#----------------------------------------------------------
#  oracle
#----------------------------------------------------------
jdbc.driver=oracle.jdbc.OracleDriver
jdbc.url=jdbc:oracle:thin:@ip:端口:orcl
jdbc.username=admin
jdbc.password=123

#dbcp settings
dbcp.initialSize=0
dbcp.minIdle=1
dbcp.maxIdle=20
dbcp.maxActive=20
dbcp.maxWait=60000

UserMpper.XML
<?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.yg.YouGan.mybatis.UserMyBatisDao">

    <resultMap type="com.yg.YouGan.entity.User" id="User">
        <result property="id" column="id" />
        <result property="user_name" column="user_name" />
        <result property="name" column="name" />
        <result property="age" column="age" />
    </resultMap>

    <select id="getUser" parameterType="String" resultMap="User">
        SELECT
        u.id,u.name,u.age FROM user u WHERE name=#{name}
    </select>
</mapper>  
UserMyBatisDao.JAVA
package com.yg.YouGan.mybatis;

import org.springframework.stereotype.Repository;

import com.yg.YouGan.entity.User;

@Repository
public interface UserMyBatisDao {
    
    public User getUser(String name);
}

UserService.JAVA
package com.yg.YouGan.service;

import com.yg.YouGan.entity.User;

public interface UserService {
    
    public User getUser(String name);  
}

UserServiceImp.JAVA
package com.yg.YouGan.service.Imp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yg.YouGan.entity.User;
import com.yg.YouGan.mybatis.UserMyBatisDao;
import com.yg.YouGan.service.UserService;

@Service
public class UserServiceImp implements UserService {

    @Autowired
    UserMyBatisDao userMapper;

    public User getUser(String name) {
        return userMapper.getUser(name);
    }
}
UserController.JAVA
package com.yg.YouGan.controller;

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.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.yg.YouGan.entity.User;
import com.yg.YouGan.service.UserService;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index() {
        System.out.println("访问成功");
        return "index";
    }

    @RequestMapping(value = "/getUser", method = RequestMethod.GET)
    public Object toIndex() {
        System.out.println("访问用户成功");
        ModelAndView mv = null;
        try {
            User user = userService.getUser("张广新");
            mv = new ModelAndView("/index");
            mv.addObject("user", user);
        } catch (Exception e) {
            mv = new ModelAndView("/index");
        }
        return mv;
    }
}

User.JAVA

实体类

package com.yg.YouGan.entity;

public class User {

    private int id;
    private String user_name;
    private String name;
    private int age;

    public int getId() {
        return id;
    }

    public String getUserName() {
        return user_name;
    }

    public void setUserName(String user_name) {
        this.user_name = user_name;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
上一篇下一篇

猜你喜欢

热点阅读