告别XML 使用JAVA配置SpringMVC

eclipse4.7.0 + jdk8 + tomcat9 + spring4.2.0 + mybatis
Maven项目结构
告别XML 使用JAVA配置SpringMVC_第1张图片
jitu.png
POM.XML

  4.0.0

  com.yg
  YouGan
  0.0.1-SNAPSHOT
  jar

  YouGan
  http://maven.apache.org

  
    UTF-8
    1.8
    
    2.2
    1.2
    3.1.0
    
    4.2.0.RELEASE
    
    1.6.6
      
    3.2.6
  
  
  
    
      junit
      junit
      3.8.1
      test
    
    
    
    
      javax.servlet
      jstl
      ${jstl.version}
    
    
      javax.servlet
      javax.servlet-api
      ${servlet.version}
      provided
    
    
      javax.servlet.jsp
      jsp-api
      ${jsp.version}
      provided
    
    
    
    
      org.springframework
      spring-beans
      ${spring-framework.version}
    
    
      org.springframework
      spring-context
      ${spring-framework.version}
      
        
        
        commons-logging
        commons-logging
        
      
    
    
      org.springframework
      spring-expression
      ${spring-framework.version}
    
    
      org.springframework
      spring-webmvc
      ${spring-framework.version}
    
    
      org.springframework
      spring-test
      ${spring-framework.version}
       
    
      org.springframework
      spring-tx
      ${spring-framework.version}
      
    
      org.springframework
      spring-core
      ${spring-framework.version}
    
    
      org.springframework
      spring-web
      ${spring-framework.version}
    
    
      org.springframework
      spring-orm
      ${spring-framework.version}
    
    
      org.springframework
      spring-jdbc
      ${spring-framework.version}
    
    
      org.springframework
      spring-aop
      ${spring-framework.version}
    

    
    
      org.slf4j
      slf4j-api
      ${org.slf4j-version}
    
    
      org.slf4j
      jcl-over-slf4j
      ${org.slf4j-version}
      runtime
    
    
      org.slf4j
      slf4j-log4j12
      ${org.slf4j-version}
      runtime
    
    
      log4j
      log4j
      1.2.15
      
        
          javax.mail
          mail
        
        
          javax.jms
          jms
        
        
          com.sun.jdmk
          jmxtools
        
        
          com.sun.jmx
          jmxri
        
      
      runtime
    

    
    
      javax.inject
      javax.inject 
      1
    
       
    
    
    
      com.alibaba
      druid
      1.0.16  
    
    
    
        org.apache.commons
        commons-dbcp2
        2.1.1
    
    
      
      
        org.mybatis  
        mybatis  
        ${mybatis.version}  
      
      
      
        org.mybatis  
        mybatis-spring  
        1.2.2  
      
  
  
    YouGan
  

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
  




    
        
        
        
        
    

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

你可能感兴趣的:(告别XML 使用JAVA配置SpringMVC)