顯示具有 Spring 標籤的文章。 顯示所有文章
顯示具有 Spring 標籤的文章。 顯示所有文章

2014年1月20日 星期一

[Spring] Directory pattern

/* 
match only one directory
ex: /a

/** 
match multiple directories 表示該目錄下且包含子目錄
ex: /a/b/c


2014年1月7日 星期二

[Spring] @Component, @Scope

  • 標注了 @Component,@Service,@Controller,@Repository 的 class,定義為 bean 也就由 Spring 管理 class lifecycle (creation/destruction)。
  • 作用和在 XML 文件中使用 <bean> 一樣。


@Service
  • 表示是邏輯層物件。
@Controller
  • 表示是控制層物件, 如 struts 中的 action。
@Repository
  • DAO 物件。
@Component
  • 泛指沒有明確歸類的元件。


@Component is a generic stereotype for any Spring-managed component.
@Repository, @Service, and @Controller are specializations of @Component for more specific use cases, for example, in the persistence, service, and presentation layers, respectively.


@Scope
  • Spring container 要回傳哪個 bean instance。
  • singleton(default), prototype, request, session, globalSession。
    • singleton: container 中只存在一個 instance。
    • prototype: 每個取得都是新的 instance



* Reference
- 4.4 Bean scopes
- Spring Bean Scopes Example
- What's the difference between @Component, @Repository & @Service annotations in Spring?

2014年1月3日 星期五

[Spring] 使用 Properties

有以下兩種做法:

1. web.xml 宣告



    




在程式中可以這樣使用

. Autowired Properties

@Autowired private Properties applicationProperties;
String fileRootPath = applicationProperties.getProperty(PROPERTY_FTP_UPLOAD_PATH);


2. context:property-placeholder + @Value

. 以前的寫法

    
        
            WEB-INF/classes/config/properties/database.properties
            classpath:config/properties/database.properties
        
    
    



    
    
    
    



. 用 PropertyPlaceholderConfigurer 可以簡化成一行:






...
    



程式中引用

@Value("${url}")
private String url


* Reference
- Spring Util:Properties Injection via Annotations into a bean

2014年1月2日 星期四

[Spring] @Async


// 此 method 會再另一個 thread 中被執行.
@Async
public void execute() { // TODO }


在 applicationContext.xml 中要宣告:


    





* Reference
- Asynchronous method invocation in Spring 3.0

2013年8月25日 星期日

[Spring] Neither BindingResult nor plain target object for bean name ''

Error Message

RequestContextAwareTag.java org.sprin
rk.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:86) ERROR - Neither BindingResult nor plain target object fo
ame 'loginForm' available as request attribute
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'loginForm' available as request attribute
at org.springframework.web.servlet.support.BindStatus.(BindStatus.java:141)
............
............
............



Solution

因為沒有指定 jsp form modelAttribute 所對應的物件

ex:

// Controller
public String login(Map model) {
model.put("login", new new LoginForm());
}


// JSP
<form:form method="POST" modelattribute="login">


* Reference
- Neither BindingResult nor plain target object for bean name available as request attribute
- Spring MVC – Neither BindingResult Nor Plain Target Object For Bean Name ‘Xxx’ Available As Request Attribute.

2012年8月27日 星期一

[Spring] enum type attribute

// 如果物件中有 enum type 的屬性。
public class User {
    private MyEnumType name;

    ...... 
}

<%-- 
    JSP 中 form 欄位的 value 必須放入 MyEnumType 才能對回物件。
    使用 List options
--%>
.....

2012年8月26日 星期日

[Spring] Type not matched when String is "" and is tried to convert to date

ERROR MESSAGE
Type not matched when String is "" and is tried to convert to date


Solution

因為 form 中的 date 為 "" (空字串) 因為要轉成 Date 時會出錯。

@InitBinder
protected void initializeBinder (WebDataBinder binder)  {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd" );
    dateFormat.setLenient(false);
    CustomDateEditor dateEditor = new CustomDateEditor(dateFormat, true);

    binder.registerCustomEditor(Date. class, dateEditor);
    binder.registerCustomEditor(ModelEntity.class, customPropertyEditor);
}

2012年7月1日 星期日

[Spring] Mapping among jsp, controller and DB

// === @ModelAttribute ===
@ReuestMapping(value=...)
public String m(
    @ModelAttribute(ATTRIBUTE_MODEL) MyObject myObject) {
    
    // 若 MyObject 前有宣告 @ModelAttribute(ATTRIBUTE_MODEL)
    // 會受 prepare() 中對 MyObject o 操作的影響
    // 若沒有宣告 則仍單純是 form bean

}

@ModelAttribute(ATTRIBUTE_MODEL)
public Object prepare() {
    // 進入 m() 前會先經過這裡
    MyObject o = new MyObject();
    return o;
}


// === URL Mapping ===
@RequestMapping(value = URL_MAPPING, method = RequestMethod.POST)
public String m(
    @RequestParam(value = ATTRIBUTE_ID, required = true) BigDecimal id) {
    // 除了 RequestMapping 中的 value 要 mapping 到以外
    // 若 RequestParam 中 required = true,request 中也必須帶有此 attribute
}


// === Mapping enum object to DB ===
// DB 內儲存的是 NAME1
// @Enumerated 便會儲存 MyObject 所對應的 name
@Enumerated (EnumType.STRING)
public MyObject getMyObject() {}

enum MyObject {
    NAME1("value1");
}


// DB 內儲存的是 DB_VALUE
// 從 DB 取出後 可藉 valueOfCode 取得相對應 MyObject
enum MyObject {
    NAME1("DB_VALUE");

    private static volatile Map<String, MyObject> registry = new HashMap<String, MyObject>();

    // Use DB_VALUE be the key of Map
    // put value to Map and use key to get MyObject
    public static MyObject valueOfCode (String code) {
        if(0 == registry.size())  {
             synchronized ( registry) {
                 if(0 == registry.size())  {
                     for(MyObject o: MyObject.values())  {
                         registry.put(o. code, o);
                     }
                 }
              }
        }
            return registry.get(code);
        }
    }

2012年6月30日 星期六

[Spring] Spring Expression Language (SpEL)

Assume get this value from DB #{#root["valueB"]}/path
// Using Expression parser, valueB should be found from DB, too.
Expression expression = parser.parseExpression(property.getValue(), 
    new TemplateParserContext());
property.setValue(expression.getValue(context, String.class));


* Reference
- Spring Expression Language (SpEL)

2012年6月22日 星期五

[Web] Brief notes


  • slf4j
    • 在 jar 檔時就 binding,比較好切換。
  • framework
    • 提供 pattern 的模組
  • Spring framework
    • 本身是個大 factory,將工作交給底下的 factory...
  • Struts2
    • #attribute 作用約是 ${attribute}
  • iBatis
    • $var$
      • paraClass 中的 attribute
    • #fieldName:fieldType#
      • Table field
  • HTML
    • 由上而下 compiler,結果會是 DOM tree 結構。
    • DTD
      • 描述 HTML syntax
    • <meta>
      • 提供和 browser or search engine 相關的訊息。
      • ex: 描述文檔的內容。

2012年5月6日 星期日

[Spring] configurations


<!-- Activates various annotations to be detected in bean classes -->
<!-- 設定註釋注册到Spring容器 -->
<context:annotation-config />

<!-- Scans the classpath for annotated components that will be auto-registered as Spring beans.
 For example @Controller and @Service. Make sure to set the correct base-package-->
<!-- 在 base-package下尋找有 @Component 和 @Configuration 的 target Class予註冊為 bean -->
<context:component-scan base-package="org.krams.tutorial" />

<!-- Configures the annotation-driven Spring MVC Controller programming model.
Note that, with Spring 3.0, this tag works in Servlet MVC only!  -->
<mvc:annotation-driven />


* Reference
- krams::: Spring 3 MVC: Using @ModelAttribute in Your JSPs

2012年2月15日 星期三

[Spring] URL Mapping with Controller

@Controller
@RequestMapping("mappingUrlPrefix") - A
public class TestController {

    // 若有設 A 則表示此 method 的 mapping URL is /mappingUrlPrefix/home
    @RequestMapping(value = "/home", method = RequestMethod.POST) 
    public String showHome(...) { }

    // x 是此 url 中的變數,但若 x 的值可能會等於 aaa.bbb.ccc
    // 又是 url 最後面,則必須寫成 {x:.+},若僅寫 {x},則只能判斷到 aaa.bbb
    // 但若是寫在 url 中,則能寫成 "/home/{x}/functions",而能使用
    // 或是參考 reference {x:[a-zA-Z0-9\\.]+}
    @RequestMapping(value = "/home/functions/{x:.+}", method = RequestMethod.POST) 
    public String showInfo(@PathVariable("pathVariable") String x...) {  }
}


* Reference
- Spring MVC @PathVariable 最後一個點(dot)以後的字串(或說副檔名)被切掉了! **

2012年2月14日 星期二

[HTML] Checkbox with Spring or Apache Struts

checkbox 回傳至 server 值如: [1,2,3],ex: List setObjectAttribute(...) {}

可能會收到 [, 2] 這類含有空值的設定值;當 checkboxlist 完全未選擇時,設定值會為 []。


SpringFramework:

<input type="hidden" name="_peopleGroupTags" value="on" />

Apache Struts 2:

Fix for https://issues.apache.org/jira/browse/WW-992

<s:hidden id="
attributeName_0" name="attributeName" value="" />

[Spring] form 和 Object 的對應

* 對應 form 和 Object
<%
// Get the service bean.
TestService testService = WebApplicationContextUtils.getWebApplicationContext(session.getServletContext())
            .getBean("testService", TestService.class);
%>

<body>
..

     
     

</body>


* 使用 form:form tag
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>


    


* 物件過程
  1. Browser request。
  2. Server 向 DB 取出相對應的物件。
  3. Send to Browser showing Object values on page and disconnected with DB。
  4. Submit Object to server。
  5. Server 向 DB 取出相對應的物件 again, 對應傳入的值, 然後將此物件存入 DB。
// 若有此宣告,則在進入 controller 前會先經過此 method
// 然後這裡 return 的 Object 再被送往 controller
@ModelAttribute(ATTRIBUTE_MODEL)
protected Object prepareModelAttribute(....) { }

2012年1月29日 星期日

[Spring] @Service

@Service("ServiceName")

Service name is used by Spring to identify the service so ServiceName must be unique.

所以必須注意在不同的 project 中的 ServiceName 是否有衝突。

如果寫成 @Service 表示 Class name is ServiceName.



2011年10月1日 星期六

[Spring] mvc annotation

* mvc:annotation-driven
  • registers a DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter.
  • @NumberFormat and @DateTimeFormat annotations.
  • JSR-303 Bean Validation API support will be detected on classpath and enabled automatically.

* mvc:default-servlet-handler
  • allows for mapping the DispatcherServlet to "/" (thus overriding the mapping of the container's default Servlet),
  • while still allowing static resource requests to be handled by the container's default Servlet.


[J2EE] action, controller and servlet

action = controller = servlet

2011年7月5日 星期二

[Spring] Base concept

如果要使用 ApplicationContext

就會太依賴 Spring

所以才有IoC(?)

乾脆讓Spring可以injection 給我們

2011年5月15日 星期日

[Design] Validation on Business, Service, Web layer

對是否把校驗當作商業邏輯這個問題,存在著正和反兩種意見,而Spring提供的驗證模式(和資料綁定)的設計對這兩種意見都不排斥。特別是,校驗應該不應該被強制綁定在Web層,而且應該很容易本地化並且可以方便地加入新的驗證邏輯。基於上述的考慮,Spring提供了一個Validator介面。這是一個基礎的介面並且適用於應用程序的任何一個層面。



* Reference
- 5. Validation, Data Binding, and Type Conversion