thymeleaf 관련

기타 2014. 2. 4. 17:52


관련 expression

l  Simple expressions:

n  Variable Expressions: ${...}

n  Selection Variable Expressions: *{...}

u  사용 예 (th:object와 같이 선택[selection] 되어 있어야 한다.)

l  <div th:object="${session.user}">

l      <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>

l  </div>

n  Message Expressions: #{...}

n  Link URL Expressions: @{...}

l  Literals

n  Text literals: 'one text', 'Another one!',...

n  Number literals: 0, 34, 3.0, 12.3,...

n  Boolean literals: true, false

n  Null literal: null

n  Literal tokens: one, sometext, main,...

l  Text operations:

n  String concatenation: +

n  Literal substitutions: |The name is ${name}|

l  Arithmetic operations:

n  Binary operators: +, -, *, /, %

n  Minus sign (unary operator): -

l  Boolean operations:

n  Binary operators: and, or

n  Boolean negation (unary operator): !, not

l  Comparisons and equality:

n  Comparators: >, <, >=, <= (gt, lt, ge, le)

n  Equality operators: ==, != (eq, ne)

l  Conditional operators:

n  If-then: (if) ? (then)

n  If-then-else: (if) ? (then) : (else)

n  Default: (value) ?: (defaultvalue)

u  valuenull이면 deaufltvalue값을 사용하고 아니면 value값을 사용함

n  사용 예

u  'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))


springframework과 연동하면

  • th:field <select><input><textarea>등에 넣으면 자동 binding
  • *{{newDate}}와 같이 double-bracket syntax를 사용하면 Spring Conversion Service가 자동 연동 된다.


참고내용

1.     기본적으로 볼 것(springframework을 사용하면 아래 2개는 모두 보고 사용하길 추천함

두번째 링크에서 활용도 높은 새로운 기능 및 tag들이 있음)

A.     http://www.thymeleaf.org/

B.      Using Thymeleaf - http://www.thymeleaf.org/doc/html/Using-Thymeleaf.html

C.      Thymeleaf + spring 3 - http://www.thymeleaf.org/doc/html/Thymeleaf-Spring3.html

2.     참고로 볼 것

A.     http://en.wikipedia.org/wiki/Thymeleaf

B.      http://www.thymeleaf.org/thvsjsp.html

C.      http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd

D.     http://forum.thymeleaf.org/

E.      18. View technologies – Spring - http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/view.html




Posted by 파이팅야
,

This blog demonstrates how to setup and test webservice client codes written in Spring RestTemplate.

Obtaining the jar

I am using Spring 3.1 here and have to include the jar file from the spring-mvc-test project into the classpath. The project has since been incorporated into Spring 3.2. See the Spring documentation for details. The codes here are tested against Spring 3.1 and spring-mvc-test. The APIs may be somewhat different in Spring 3.2.

Restful webservice client

My webservice client communicates with the server via XML so I setup RestTemplate with JaxB marshaller and unmarshaller as follows:

    <bean id="exampleRestClient" >
        <property name="template" ref="exampleRestTemplate"></property>
        <property name="baseUrl" value="<server url>"></property>
    </bean>

    <!-- RESTful template and related beans -->
    <bean id="exampleRestTemplate">
        <property name="messageConverters">
            <list>
                   <ref bean="marshallingHttpMessageConverter"/>
            </list>
        </property>
    </bean>

    <bean id="marshallingHttpMessageConverter">
      <property name="marshaller" ref="jaxb2Marshaller" />
      <property name="unmarshaller" ref="jaxb2Marshaller" />
    </bean>

    <bean id="jaxb2Marshaller">
        <property name="contextPath">
                <value>com.blog.resttemplatetest.jaxb</value>
        </property>
        <property name="schema" value="classpath:myschema.xsd"/>
    </bean>

The webservice client implements the normal CRUD functions by delegating to its RestTemplate bean. I will focus on the put function here and demonstrate how to write unit test for it in next section.

@Component(“exampleRestClient”)
public class ExampleRestClient {

private RestTemplate template;
private String baseUrl; // base url

public ExampleResponse add(final ExampleData resource, final ExampleResponse response) {
return put(baseUrl, resource, response);
}

private ExampleResponse put(final String url, final ExampleData resource, final ExampleResponse response) {
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_XML);
final HttpEntity<ExampleData> requestEntity = new HttpEntity<ExampleData>(resource, headers);
final ResponseEntity<ExampleResponse> reponseEntity = template.exchange(url, HttpMethod.PUT, requestEntity,
response.getClass());
return reponseEntity.getBody();
}

// getters and setters

Note that instead of using the put() method in RestTemplate, I use its exchange() method in order to get the return response from the web service, as the RestTemplate#put method does not return anything. Both input and output classes ExampleData and ExampleResponse are JAXB objects generated via xjc from the example XML schemamyschema.xsd.

Writing unit test for webservice client

spring-mvc-test provides a mock server class MockRestServiceServer to support client testing. For example, to test the put add method in our ExampleRestClient:

...
import static org.springframework.test.web.client.RequestMatchers.method;
import static org.springframework.test.web.client.RequestMatchers.requestTo;
import static org.springframework.test.web.client.ResponseCreators.withSuccess;
...

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:example-test.xml" })
public class StorefrontRestClientTest {
    private MockRestServiceServer mockServer;

    @Autowired
    private ExampleRestClient service;

    @Before
    public void setUp() {
        mockServer = MockRestServiceServer.createServer(service.getTemplate()); // (1)
    }

    private String loadXmlFile(final String filename) throws IOException {
        // load xml file into String ...
    }

    @Test
    public void testAddReturnCorrectResponse() throws Exception {

        final ObjectFactory factory = new ObjectFactory();
        final String responseXml = loadXmlFile("/test/expectedResponse.xml");

        mockServer.expect(requestTo(service.getBaseUrl()))
                  .andExpect(method(HttpMethod.PUT))
                  .andRespond(withSuccess(responseXml, MediaType.APPLICATION_XML)); // (2)

        final ExampleData exampleData= factory.createExampleData();
        final ExampleResponse response = (ExampleResponse) service.add(exampleData, new ExampleResponse());
        assertEquals(200, response.getStatus()); // (3)
        assertEquals(12345, response.getID()); // (3)
        mockServer.verify(); // (4)
    }
    ...
// file: expectedResponse.xml
<?xml version="1.0" encoding="UTF-8"?>
<tns:exampleResponse xmlns:tns="http://" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.example.com/example example.xsd ">
  <tns:status>200</tns:status>
  <tns:ID>12345</tns:ID>
</tns:exampleResponse>

Note:

  1. Instantiate mock server with the RestTemplate to be tested
  2. This sets the expectations on the request and mocks the response to be returned, in this case the Xml string stored in file expectedResponse.xml (above).  Note the static imports required at the top of the codes forrequestToaddExpect and andResponse.
  3. Junit assertions as would normally included.
  4. Call verify() method to ensure that expectations are being met.

imrt static 매번하기 귀찮으면
eclipse Window>Preferences>Java>Editor>Content Assist>Favorites 에 다음의 내용 추가하면 됨
org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
org.springframework.test.web.client.match.MockRestRequestMatchers.*;
org.springframework.test.web.client.response.MockRestResponseCreators.*;
org.junit.Assert.*;

참고 url



Posted by 파이팅야
,

lombok

풀그림 2013. 11. 26. 20:00


Lombok features overview

val
Finally! Hassle-free final local variables.
@NonNull
or: How I learned to stop worrying and love the NullPointerException.
@Cleanup
Automatic resource management: Call your close() methods safely with no hassle.
@Getter / @Setter
Never write public int getFoo() {return foo;} again.
@ToString
No need to start a debugger to see your fields: Just let lombok generate a toString for you!
@EqualsAndHashCode
Equality made easy: Generates hashCode and equals implementations from the fields of your object.
@NoArgsConstructor@RequiredArgsConstructor and @AllArgsConstructor
Constructors made to order: Generates constructors that take no arguments, one argument per final / non-null field, or one argument for every field.
@Data
All together now: A shortcut for @ToString@EqualsAndHashCode@Getter on all fields, and @Setter on all non-final fields, and@RequiredArgsConstructor!
@Value
Immutable classes made very easy.
@SneakyThrows
To boldly throw checked exceptions where no one has thrown them before!
@Synchronized
synchronized done right: Don't expose your locks.
@Getter(lazy=true)
Laziness is a virtue!
@Log
Captain's Log, stardate 24435.7: "What was that line again?"
@Delegate
Don't lose your composition.
experimental features
Here be dragons: Extra features which aren't quite ready for prime time yet.



References

1.     Lombok site : http://projectlombok.org/

2.     Lombok features : http://projectlombok.org/features/index.html

3.     Lombok annotion 설명 : http://jnb.ociweb.com/jnb/jnbJan2010.html

4.     Project Lombok - http://projectlombok.org

5.     Lombok API Documentation - http://projectlombok.org/api/index.html

6.     Project Lombok Issues List - http://code.google.com/p/projectlombok/issues/list

7.     Use Lombok via Maven - http://projectlombok.org/mavenrepo/index.html

8.     Project Lombok Google Group - http://groups.google.com/group/project-lombok

9.     Reviewing Project Lombok or the Right Way to Write a Library - http://www.cforcoding.com/2009/11/reviewing-project-lombok-or-right-way.html

10.   Morbok: Extensions for Lombok - http://code.google.com/p/morbok

11.   Using Project Lombok with JDeveloper - http://kingsfleet.blogspot.com/2009/09/project-lombok-interesting-bean.html


Posted by 파이팅야
,