前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java Web技术经验总结(九)

Java Web技术经验总结(九)

作者头像
阿杜
发布2018-08-06 11:36:38
3150
发布2018-08-06 11:36:38
举报
文章被收录于专栏:阿杜的世界
  1. 有时我们需要定义ParameterizableViewController一个类,由这个类负责快速将请求导入到另一个视图。<mvc:view-controller path="controller" />,这个标签是对应的简称。如下是一个Java配置,会将"/"的请求引导到名叫"home"的视图:
代码语言:javascript
复制
@Configuration 
@EnableWebMvc 
public class WebConfig extends WebMvcConfigurerAdapter {
      @Override
     public void addViewControllers(ViewControllerRegistry registry) {
         registry.addViewController("/").setViewName("home");
     }
  }

跟这个代码对应的XML配置代码如下:

代码语言:javascript
复制
<mvc:view-controller path="/" view-name="home"/>
  1. <mvc:default-servlet-handler>,通常我们使用DispatchServlet处理"/"开头的URL(覆盖了Tomcat容器的默认Servlet),通过定义这默认的servlet-handler,可以在使用DispatchServlet的同时,允许容器的默认Servlet处理静态资源请求。这个标签配置了一个DefaultServletHttpRequestHandler,用于处理"/"之类的URL,不过相对于其他的URL匹配模式来说具有较低的优先级。 这个handler将会把所有请求引导到默认的Servlet,因此,我们配置时,要让默认handler在所有的URL处理器映射中位于最低优先级;尤其是当你在使用<mvc:annotation-driven>或者你设置了自定义的处理器映射时,最低优先级的值是Integer.MAX_VALUE。通过Java Config代码启用default-servlet-handler:
代码语言:javascript
复制
@Configuration 
@EnableWebMvc 
public class WebConfig extends WebMvcConfigurerAdapter {
      @Override
      public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
         configurer.enable();
     }
  }

同样的功能可使用如下XML代码实现:

代码语言:javascript
复制
<mvc:default-servlet-handler/>
  1. <mvc:interceptors>,在请求由DispatchServlet传递到具体的业务逻辑控制器之前,Spring MVC还提供了拦截器、过滤器等机制用于对请求进行预处理和post处理。可以针对所有的请求或者指定URL匹配模式的请求进行拦截,如下是一个Java Config代码:
代码语言:javascript
复制
@Configuration 
@EnableWebMvc 
public class WebConfig extends WebMvcConfigurerAdapter { 
     @Override 
    public void addInterceptors(InterceptorRegistry registry) {
         registry.addInterceptor(new LocaleInterceptor());
         registry.addInterceptor(new ThemeInterceptor()).addPathPatterns("/**").excludePathPatterns("/admin/**");
         registry.addInterceptor(new SecurityInterceptor()).addPathPatterns("/secure/*");
     }
  }

对应的XML配置代码如下:

代码语言:javascript
复制
<mvc:interceptors>
     <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>
     <mvc:interceptor>
         <mvc:mapping path="/**"/>
         <mvc:exclude-mapping path="/admin/**"/>
         <bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor"/>
     </mvc:interceptor>
     <mvc:interceptor>
         <mvc:mapping path="/secure/*"/>
         <bean class="org.example.SecurityInterceptor"/>
     </mvc:interceptor>
 </mvc:interceptors>

这个配置的含义有二:(1)对于所有符合"/"模式的请求(除"/admin/"之外)要应用ThemeChangeInterceptor拦截器;(2)对于所有符合"/secure/*"模式的请求,都要应用SecurityInterceptor拦截器。

  1. 根据用户填写的生日,自动计算出星座。
代码语言:javascript
复制
public class ConstellationBuilder {
    public static String getAstro(int month, int day) {
        String[] starArr = {"魔羯座", "水瓶座", "双鱼座", "牡羊座", "金牛座", "双子座", "巨蟹座", "狮子座",
                "处女座", "天秤座", "天蝎座", "射手座"};
        int[] DayArr = {22, 20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22};  //两个星座分割日
        int index = month;        // 所查询日期在分割日之前,索引-1,否则不变
        if (day < DayArr[month - 1]) {
            index = index - 1;
        }
        return starArr[index];
    }
}

对应的测试代码如下,注意Joda Time包的使用,不过如果你使用Java 8的话,可以直接使用Java 8提供的日期接口。

代码语言:javascript
复制
public class ConstellationBuilderTest {
    @Test
    public void getAstro() throws Exception {
        Calendar calendar = Calendar.getInstance();
        calendar.set(1988, Calendar.OCTOBER, 16);
        LocalDateTime localDateTime = LocalDateTime.fromDateFields(calendar.getTime());
        String res = ConstellationBuilder.getAstro(localDateTime.getMonthOfYear(), localDateTime.getDayOfMonth());
        Assert.assertEquals("天秤座", res);
    }
}
  1. 在Mybatis中,使用语句INSERT ... ON DUPLICATE KEY UPDATE的语法。
代码语言:javascript
复制
<insert id="insertOrUpdate" parameterType="userBean">
    <![CDATA[
    INSERT INTO
      user
      (id, name, sex, birthday, constellation, work, province, city, district, mobile, integral, ctime, mtime)
    VALUES     (#{id}, #{name}, #{sex}, #{birthday}, #{constellation}, #{work}, #{province}, #{city}, #{district},
      #{mobile}, #{integral}, now(), now())
    ON DUPLICATE KEY
     UPDATE
          name=VALUES(name),
          sex=VALUES(sex),
          birthday=VALUES(birthday),
          constellation=VALUES(constellation),
          work=VALUES(work),
          province=VALUES(province),
          city=VALUES(city),
          district=VALUES(district),
          mobile=VALUES(mobile),
          integral=VALUES(integral),
          mtime=now()
    ]]>
</insert>

MySQL的官方文档,要找个时间认真阅读,有问题的时候,也可以直接翻阅官方文档,而不是漫无目的得Google。根据官方文档-insert-on-duplicate中提到:

You can use the VALUES(col_name) function in the UPDATE clause to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE statement. In other words, VALUES(col_name) in the ON DUPLICATE KEY UPDATE clause refers to the value of col_name that would be inserted, had no duplicate-key conflict occurred. This function is especially useful in multiple-row inserts. The VALUES() function is meaningful only in INSERT ... UPDATE statements and returns NULL otherwise. 重点:VALUES函数用于提取对应的列值,如果没有则返回NULL;

  1. Spring Boot + Thymeleaf + BootStrap结合使用的一个例子:Spring MVC with Bootstrap and Thymeleaf
  2. 对于JVM中垃圾回收算法的分类,我目前为止看到的最清晰的一篇文章:JVM调优总结(三):(1)按照基本策略——引用计数、标记清除、复制、标记整理;(2)按照分区对待的方式区分——增量升级、分代搜集;(3)按照系统线程划分——串行搜集、并行搜集、并发搜集。
  3. 阅读文章JVM调优(四),JVM中垃圾回收,面临的问题可以总结为如下三类:
  • 如何识别垃圾对象?(1)引用计数;(2)Root Objects对象树
  • 如何处理内存碎片问题?(1)复制;(2)标记-整理
  • 如何处理“对象创建”和“对象回收”这两个相反的动作?(1)串行;(2)并行;(3)并发
  1. JDK中单利模式的经典应用是?答:Runtime类,如下是我在JDK 1.8中查到的Runtime类的主要代码,可以看出,它是通过构造函数私有化实现的单例模式。参考JDK设计模式应用——单例模式(Singleton)
代码语言:javascript
复制
public class Runtime {
    private static Runtime currentRuntime = new Runtime();
    /**
     * Returns the runtime object associated with the current Java application.
     * Most of the methods of class <code>Runtime</code> are instance
     * methods and must be invoked with respect to the current runtime object.
     *
     * @return  the <code>Runtime</code> object associated with the current
     *          Java application.
     */
    public static Runtime getRuntime() {
        return currentRuntime;
    }
    /** Don't let anyone else instantiate this class */
    private Runtime() {}
}

原有的旧方法,在反序列号方面会有问题,需要我们重写方法,在Java 1.7之后,实现单利模式的最佳实践是利用枚举(枚举类型天然支持序列化)。参考StackOverflow:Implementing Singleton with an Enum (in Java)

代码语言:javascript
复制
// Enum singleton - the preferred approach
 public enum Elvis {
       INSTANCE;
       public void leaveTheBuilding() { ... }
 }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016.07.22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档