重组一个基于java config的spring,mybatis和thymeleaf

由于当红偶尔像明星鹿晗、古力娜扎等主演的电视剧《择天记》结局都过去半单月了,但是近来有更进一步多的网友吐槽:《择天记》与《迪迦奥特曼》的百般结局一致!

工作至今日即将1年半了,一直无工夫友好开搭建筑个框架,这个星期实际上是无聊,真的不思由lol了,(黑色玫瑰开黑的吵嚷我!),正好把前覆盖下之坑填完.
您要以下工具:
IDE : Intellij idea15
jdk : 1.7.0_59
maven : 3.2.2
tomcat : 7.0.54

开吗《择天记》忠实粉丝,又是看奥特曼长大的小编,不能够经受被私自,要就此真情讲!默默的接触起来了异常结局,进行较。

  • new an empty project,相当于eclipse中的workspace

《择天记》中,教宗利用星阵找到长生的职位。

Paste\_Image.png

《迪迦奥特曼》中,大古是让那个兽禁锢,无法变换身。

  • new a maven
    module,相当于eclipse中的project,选择maven后一起next,设置好的称呼即可.

当百年的背后一直有相同博人当扶自己,不过奥特曼为是起友好的武装力量在共同战斗。

Paste\_Image.png

总的看无论是是打lol还是打怪兽,一居多好队友是就为重要的!

  • 在idea中配置maven,在preferences中将maven_home指向本地的安路径就是可.至于怎么安排maven_home环境,左改百度,右转google

于最后关键,不管是以神都的口还是于另地域的食指,都接触来得了祥和之命星,帮助长生共抗星阵。

Paste\_Image.png

一律当末关头,世界各地的子女还发了“信仰的才”帮助大古重得光明,成功变身奥特曼战斗。

  • 脚放上同样摆增加建筑好之工程结构图

竟,在颇具人数的共同努力下,主角战胜了最终BOSS,并且终于与喜爱之食指当共同了。

Paste\_Image.png

小编不得不承认《择天记》和《迪迦奥特曼》的后果有多底相似之处,但是及时并无见面潜移默化我们失去看《择天记》、去押《迪迦奥特曼》,他们同告诉我们邪恶终究会于打败,团结就是是能力,有情人终成眷属。在这也盼望世界起朋友,终成眷属。

  • 以下是装有应用的交之jar包依赖. (pom.xml)

<?xml version="1.0" encoding="UTF-8"?>
<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.sam</groupId>    
<artifactId>spring-mybatis</artifactId>    
<version>1.0-SNAPSHOT</version>    
<packaging>war</packaging>    
<properties>        
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>        
      <spring.version>4.1.6.RELEASE</spring.version>                  
      <cxf.version>2.7.15</cxf.version>        
      <aspectj.version>1.6.8</aspectj.version>        
      <slf4j-version>1.7.12</slf4j-version>
      <thymeleaf.version>2.1.3.RELEASE</thymeleaf.version>        
      <thymeleaf-layout.version>1.2.5</thymeleaf-layout.version>        
      <log4j-version>1.2.17</log4j-version>        
      <mybatis-version>3.3.0</mybatis-version>        
      <mybatis-spring-version>1.2.3</mybatis-spring-version> 
      <jackson.version>2.4.3</jackson.version>
      <json.version>1.9.13</json.version>            
      <diamond.version>0.0.18</diamond.version>    </properties>    
<dependencies>       
       <!-- 日志配置-->        
       <dependency>            
            <groupId>ch.qos.logback</groupId>   
            <artifactId>logback-classic</artifactId>      
            <version>1.0.13</version>        
       </dependency>        
       <dependency>            
            <groupId>org.slf4j</groupId> 
            <artifactId>slf4j-api</artifactId>    
            <version>${slf4j-version}</version>               
       </dependency>        
       <dependency>            
            <groupId>javax.servlet</groupId>           
            <artifactId>javax.servlet-api</artifactId>     
            <version>3.1.0</version>        
       </dependency>        
       <dependency>                   
            <groupId>org.apache.commons</groupId>            
            <artifactId>commons-lang3</artifactId>                
            <version>3.3</version>        
       </dependency>        
       <dependency>         
            <groupId>com.alibaba</groupId>     
            <artifactId>fastjson</artifactId>      
            <version>1.2.1</version>      
        </dependency>        
        <!-- 数据源配置 -->        
        <dependency>            
             <groupId>commons-dbcp</groupId>     
             <artifactId>commons-dbcp</artifactId>      
             <version>1.4</version>        
        </dependency>        
        <!--mysql-->        
        <dependency>            
             <groupId>mysql</groupId>          
             <artifactId>mysql-connector-java</artifactId>    
             <version>5.1.37</version>     
        </dependency>        
        <dependency>            
             <groupId>org.mybatis</groupId>   
             <artifactId>mybatis-spring</artifactId>           
             <version>${mybatis-spring-version}</version>  
        </dependency>        
        <dependency>            
             <groupId>org.mybatis</groupId>    
             <artifactId>mybatis</artifactId>       
             <version>${mybatis-version}</version>     
         </dependency>        
         <dependency> 
             <groupId>org.mybatis.generator</groupId>         
             <artifactId>mybatis-generator-core</artifactId>      
             <version>1.3.2</version>          
         </dependency>        
         <!-- spring用到的包 -->        
         <dependency>          
             <groupId>org.springframework</groupId>     
             <artifactId>spring-web</artifactId>            
             <version>${spring.version}</version>     
         </dependency>        
         <dependency>     
             <groupId>org.springframework</groupId> 
             <artifactId>spring-core</artifactId>            
             <version>${spring.version}</version>        
         </dependency>        
         <dependency>        
             <groupId>org.springframework</groupId>     
             <artifactId>spring-context</artifactId>            
             <version>4.1.1.RELEASE</version>  
         </dependency>        
         <dependency>            
             <groupId>org.springframework</groupId>          
             <artifactId>spring-beans</artifactId>            
             <version>${spring.version}</version>        
         </dependency>        
         <dependency>         
             <groupId>org.springframework</groupId>    
             <artifactId>spring-aop</artifactId>            
             <version>${spring.version}</version>        
         </dependency>        
         <dependency>          
             <groupId>org.springframework</groupId>         
             <artifactId>spring-jdbc</artifactId>            
             <version>${spring.version}</version>        
         </dependency>       
         <dependency>         
             <groupId>org.springframework</groupId>    
             <artifactId>spring-webmvc</artifactId>    
             <version>${spring.version}</version>       
         </dependency>        
         <dependency>          
             <groupId>org.springframework</groupId>         
             <artifactId>spring-tx</artifactId>            
             <version>${spring.version}</version>        
         </dependency>        
          <!--测试-->        
         <dependency>         
             <groupId>junit</groupId>    
             <artifactId>junit</artifactId>       
             <version>4.11</version>   
             <scope>test</scope>        
         </dependency>        
         <dependency>         
             <groupId>org.springframework</groupId>   
             <artifactId>spring-test</artifactId>            
             <version>4.1.1.RELEASE</version>          
             <scope>test</scope>     
         </dependency>        
         <dependency>       
             <groupId>javax</groupId>            
             <artifactId>javaee-api</artifactId>   
             <version>7.0</version>       
             <scope>provided</scope>       
         </dependency>        
         <!-- thymeleaf -->   
         <dependency>            
             <groupId>org.thymeleaf</groupId>      
             <artifactId>thymeleaf-spring4</artifactId>    
             <version>${thymeleaf.version}</version>   
             <exclusions>     
                  <exclusion>              
                  <groupId>org.slf4j</groupId>     
                  <artifactId>slf4j-api</artifactId>     
                  </exclusion>            
             </exclusions>        
         </dependency>        
         <dependency>           
             <groupId>nz.net.ultraq.thymeleaf</groupId>          
             <artifactId>thymeleaf-layout-dialect</artifactId> 
             <version>${thymeleaf-layout.version}</version>   
         </dependency>       
        <!--diamond-->     
        <dependency>      
              <groupId>com.github.bingoohuang</groupId>     
              <artifactId>diamond-sdk</artifactId>            
              <version>0.0.5</version>
        </dependency>        
        <dependency>         
              <groupId>com.github.bingoohuang</groupId>     
              <artifactId>diamond-client</artifactId>           
              <version>${diamond.version}</version>    
        </dependency>     
        <dependency>         
              <groupId>org.aspectj</groupId>  
              <artifactId>aspectjrt</artifactId>  
              <version>${aspectj.version}</version>     
       </dependency>        
       <dependency>           
            <groupId>org.aspectj</groupId>      
            <artifactId>aspectjweaver</artifactId>   
            <version>${aspectj.version}</version>   
       </dependency>        
       <!--jackson-->       
       <dependency>     
            <groupId>org.codehaus.jackson</groupId>     
            <artifactId>jackson-mapper-asl</artifactId>    
            <version>${json.version}</version>        
       </dependency>        
       <dependency>

            <groupId>org.codehaus.jackson</groupId>

            <artifactId>jackson-core-asl</artifactId>

            <version>${json.version}</version>

       </dependency>
       <dependency>          
            <groupId>com.fasterxml.jackson.core</groupId>          
            <artifactId>jackson-databind</artifactId>        
            <version>${jackson.version}</version>
      </dependency>
      <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>
    </dependencies>
        <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
  • 概念一个WebMvcConfig类实现WebMvcConfigurerAdapter

/**
 * 继承web mvc adapter
 * 包含通用的配置
 * Created by sam on 16/5/26.
 */
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    //static resources
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/css/**").addResourceLocations("/css/");
        registry.addResourceHandler("/img/**").addResourceLocations("/img/");
        registry.addResourceHandler("/js/**").addResourceLocations("/js/");
    }

    // 配置thymeleaf视图解析器,
    // 保留原有配置
    // 加入自定义参数 如${e.res()}
    @Bean
    public ThymeleafViewResolver thymeleafViewResolver() {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(templateEngine());
        viewResolver.setCharacterEncoding("UTF-8");

        Map<String, Object> oldStaticVariables = viewResolver.getStaticVariables();
        Map<String, Object> staticVariables = Maps.newHashMap(oldStaticVariables);
        staticVariables.put("e", new SpringUtils());
        viewResolver.setStaticVariables(staticVariables);
        return viewResolver;
    }

    //配置模板引擎
    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(templateResolver());
        engine.addDialect(new LayoutDialect());
        return engine;
    }

    //配置模板解析器
    @Bean
    public TemplateResolver templateResolver() {
        ClassLoaderTemplateResolver templateResolver;
        templateResolver = new ClassLoaderTemplateResolver();
        templateResolver.setTemplateMode("XHTML");
        templateResolver.setPrefix("views/");
        templateResolver.setCharacterEncoding("UTF-8");
        templateResolver.setSuffix(".html");
        templateResolver.setCacheable(false); // true by default
        return templateResolver;
    }

    //定义spring文件上传编码
    @Bean
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver.setDefaultEncoding("UTF-8");
        return multipartResolver;
    }

    //解析json返回数据
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        List<MediaType> mediaTypes = new ArrayList(converter.getSupportedMediaTypes());
        converter.setSupportedMediaTypes(mediaTypes);
        mediaTypes.addAll(asList(MediaType.TEXT_PLAIN, MediaType.TEXT_HTML, MediaType.TEXT_XML));
        converters.add(converter);
    }

    //配置diamond,如果本地没有配置diamond可以注释该段代码
    @Bean
    public DiamondSDK diamondSDK() {
        Minerable minerable = new Miner().getMiner("poet.diamond", "diamondConfig");
        DiamondSDK diamondSDK = new DiamondSDK(
                new DiamondSDKConf(
                        Lists.newArrayList(new DiamondConf(
                                minerable.getString("diamondIp"),
                                minerable.getInt("diamondPort"),
                                minerable.getString("diamondUsername"),
                                minerable.getString("diamondPassword")))));
        return diamondSDK;
    }

    //快捷定义ViewController
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }
}
  • 概念实际行使及之spring mvc config

/**
 * 实际使用到的配置文件
 * 可以将该文件放入不同的工程来辨别使用不同的spring配置,如不同的interceptor
 * Created by sam on 16/5/26.
 */
@EnableWebMvc
@Configuration
@EnableAspectJAutoProxy
public class SpringMvcConfig extends WebMvcConfig {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SpringInterceptor());
    }
}
  • 以下是方配置中以及的interceptor

/**
 * Created by sam on 16/5/26.
 */
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Component
public class SpringInterceptor extends HandlerInterceptorAdapter {

    private Logger logger = LoggerFactory.getLogger(SpringInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.debug("interceptor works --------- return true");
        return true;
    }
}
  • 注册DispatcherServlet

/**
 * 注册Spring DispatcherServlet
 * Created by sam on 16/5/26.
 */
public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{

    //配置扫描根路径
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{RootConfig.class};
    }

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

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

    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);
        return new Filter[]{characterEncodingFilter};
    }

    @Override
    protected void customizeRegistration(ServletRegistration.Dynamic registration) {
       registration.setInitParameter("throwExceptionIfNoHandlerFound", "true");
    }
}
  • 安排方面配置中的RootConfig,包括部署包的围观路径,配置mybatis需要的数据源等

/**
 * 定义扫描的根路径,数据源
 * Created by sam on 16/5/26.
 */
@Configuration
@ComponentScan(basePackages = "com.sam")
@MapperScan(basePackages = "com.sam")
public class RootConfig {

    private static String diver = "com.mysql.jdbc.Driver";

    private static String url = "jdbc:mysql://localhost:3306/YOUR_INSTANCE_NAME";

    private static String user = "YOUR_NAME";

    private static String pwd = "YOUR_PASSWORD";

    @Bean
    public BasicDataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(diver);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(pwd);
        return dataSource;
    }

    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager() throws NamingException {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(ApplicationContext ap) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setTypeAliasesPackage("com.sam");
        return sessionFactory;
    }
}
  • 概念SpringUtils类实现thymeleaf中应用及之自定义参数,这个布局写以WebMvcConfig中

/**
 * 配置thymeleaf自定义参数的相关方法
 * Created by sam on 16/5/26.
 */
public class SpringUtils {

    // 可以在html中使用${e.res('/')}
    // 将会自动代理到相关静态资源下面
    public static String res(String relativeResPath) {
        Minerable resConfig = new Miner().getMiner("poet.base", "res");

        String resVersion = resConfig.getString("version", "1");
        String baseResPath = resConfig.getString("prefix");
        if (baseResPath == null) throw new RuntimeException("prefix config is NULL.");

        return new StringBuilder(removeEnd(baseResPath, "/")).append("/").append(removeStart(relativeResPath, "/")).append("?v=").append(resVersion).toString();
    }
}
  • 定义helloWorldController来测试下

/** 
  * Created by sam on 16/5/26. 
  */
@Controller
@RequestMapping("/hello")
public class HelloWorldController {

    @Autowired
    UserDao userDao;

    private Logger logger = LoggerFactory.getLogger(HelloWorldController.class);

    @RequestMapping("/world")
    public String hello(Model model) {
        String email = "sam@balabala.com";
        String name = userDao.queryUserNameByEmail(email);
        User user = userDao.queryUserInfoByEmail(email);

        logger.debug("you have been here !");
        model.addAttribute("hello", "您好! " + name);
        model.addAttribute("world", "everything is " + user.getUserId());
        return "sam";
    }

    @RequestMapping("/test")
    public String test(Model model){
        logger.debug(">>>>>>>>我就测试下日志 debug  <<<<<<<<<");
        logger.info(">>>>>>>> 我就测试下日志 info   <<<<<<<<<");
        model.addAttribute("hello", "您好! test");
        model.addAttribute("world", "everything is id");
        return "sam";
    }
}
  • 在resources下建views夹子,sam.html如下

<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>my first html</title>
</head>
<body>
<h1 data-th-text="${hello}"></h1>
<h1 data-th-text="${world}"></h1>
</body>
</html>
  • UserDao

/**
 * Created by sam on 16/5/29.
 */
@Service
public interface UserDao {

    @Select("select customer_name from customer where email= #{email}")
    String queryUserNameByEmail(@Param("email") String email);

    User queryUserInfoByEmail(@Param("email") String email);
}
  • User

/**
 * Created by sam on 16/5/29.
 */
public class User {

    private String userId;

    private String userName;

    private String email;

    //get set toString and so on;
}
  • 当你的MySQL中建造一个Customer表(customer_id,customer_name,email)即可
  • 当resources下建和dao相同包名的xml文件,在公的MySQL中修一个Customer表,包含customer_id,customer_name,email即可,

<?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.sam.dao.UserDao">
    <resultMap id="User" type="com.sam.domain.User">
        <id column="customer_id" property="userId" jdbcType="VARCHAR"/>
        <result column="customer_name" property="userName" jdbcType="VARCHAR"/>
        <result column="email" property="email" jdbcType="VARCHAR"/>
    </resultMap>

    <select id="queryUserInfoByEmail" resultMap="User" parameterType="java.lang.String">
        select customer_id,customer_name,email
        from customer
        where email= #{email,jdbcType=VARCHAR}
    </select>
</mapper>
  • Finally ,访问
    http://localhost:8080/YOUR\_MODULE\_NAME/hello/world
    来试一下咔嚓
  • 章的结尾 :
    感谢下涛bra,嘟嘟MD鲜各类童鞋~~~

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*
*
Website