Examples shows you how you can use @SessionAttributes to hold multiple session values.

@SessionAttributes multiple values

In this section we will see how you can use @sessionattributes to set multiple session values to it.

While developing the application using Spring MVC can use the @sessionattributes attribute to save some data. This session data can be used in the UI form.

In the following example we are using @sessionattributes to put two session values formdata andsomeCombobox. The correct way to use @sessionattributes for multiple values are:

@SessionAttributes({"formdata","someCombobox"})

Note that the variable are in curly braces.

Here is the complete list of the code:


import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

@Controller
@RequestMapping("/myform.htm")
@SessionAttributes({"formdata","someCombobox"})
public class TutorialController {


 
@RequestMapping(method = RequestMethod.GET)
   
public String showForm(   HttpServletRequest request,
                     
HttpServletResponse response,
                     
ModelMap model) {
         
MyFormDataClass t =   new MyFormDataClass();

      model
.put("formdata", t );

         
List list = new ArrayList();
         
//Add some values in list
          list
.put("Something");
         
//Add the list to the session
          model
.put("someCombobox", list );
         
return "AddEditForm";
   
}


       
@RequestMapping(method = RequestMethod.POST)
       
public String onSubmit(@ModelAttribute("formdata") MyFormDataClass t) {
               
System.out.println(t.getId());
               
return "redirect:tutorialsuccess.htm";
       
}
       
}

With the help of @SessionAttributes you can define multiple session variables.



http://www.roseindia.net/tutorial/spring/spring3/web/SessionAttributes-multiple-values.html
저작자 표시 비영리
신고
Posted by jeonguk



저작자 표시 비영리
신고
Posted by jeonguk

2012:02:01 11:20:07


저작자 표시 비영리
신고
Posted by jeonguk

TDD


1. 단위 테스트 프레임워크 중 하나
2. 문자 혹은 GUI 기반으로 실행됨
3. xUnit이라 불리는 스타일을 따른다.
   assertEquals(예상 값, 실제 값)
4. 결과는 성공(녹색), 실패(붉은색)중 하나로 표시

 
저작자 표시 비영리
신고

'Framework > JUnit' 카테고리의 다른 글

JUnit 테스트 프레임워크  (0) 2012.02.04
Posted by jeonguk

1. Method 1 – prop key

<beans ...>   <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/welcome.htm">welcomeController</prop> <prop key="/*/welcome.htm">welcomeController</prop> <prop key="/helloGuest.htm">helloGuestController</prop> </props> </property> </bean>   <bean id="welcomeController" class="com.common.controller.WelcomeController" />   <bean id="helloGuestController" class="com.common.controller.HelloGuestController" />   </beans>

2. Method 1 – value

 
<beans ...>
 
	<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
	   <property name="mappings">
		<value>
		   /welcome.htm=welcomeController
		   /*/welcome.htm=welcomeController
		   /helloGuest.htm=helloGuestController
		</value>
	   </property>
	</bean>
 
	<bean id="welcomeController" 
		class="com.common.controller.WelcomeController" />
 
	<bean id="helloGuestController" 
		class="com.common.controller.HelloGuestController" />
 
</beans>


  1. /welcome.htm –> welcomeController.
  2. /{anything}/welcome.htm –> welcomeController.
  3. /helloGuest.htm –> helloGuestController.












 

신고
Posted by jeonguk


Spring-All-Module.xml : Base 파일  설정

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
	<import resource="common/Spring-Common.xml"/>
        <import resource="connection/Spring-Connection.xml"/>
        <import resource="moduleA/Spring-ModuleA.xml"/>
  
</beans> 



import 해서 설정한다.

로딩은 

ApplicationContext context = new ClassPathXmlApplicationContext(Spring-All-Module.xml);



 
신고
Posted by jeonguk

 
1. Declares Components Manually

Normal bean.

package com.customer.dao;

public class CustomerDAO
{
     @Override
      public String toString() {
           return "Hello , This is CustomerDAO";
      }
}



DAO layer.

package com.customer.services;
 
import com.customer.dao.CustomerDAO;
 
public class CustomerService 
{
	CustomerDAO customerDAO;
 
	public void setCustomerDAO(CustomerDAO customerDAO) {
		this.customerDAO = customerDAO;
	}
 
	@Override
	public String toString() {
		return "CustomerService [customerDAO=" + customerDAO + "]";
	}
 
}


Bean configuration file (Spring-Customer.xml), a normal bean configuration in Spring.
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
	<bean id="customerService" class="com.customer.services.CustomerService">
		<property name="customerDAO" ref="customerDAO" />
	</bean>
 
	<bean id="customerDAO" class="com.customer.dao.CustomerDAO" />
 
</beans>

Run it
package com.common;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.customer.services.CustomerService;
 
public class App 
{
    public static void main( String[] args )
    {
    	ApplicationContext context = 
    	  new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});
 
    	CustomerService cust = (CustomerService)context.getBean("customerService");
    	System.out.println(cust);
 
    }
}

output

CustomerService [customerDAO=Hello , This is CustomerDAO]



2. Auto Components Scanning

Annotate with @Component to indicate this is class is an auto scan component.

package com.customer.dao;
 
import org.springframework.stereotype.Component;
 
@Component
public class CustomerDAO 
{
	@Override
	public String toString() {
		return "Hello , This is CustomerDAO";
	}	
}

 
DAO layer, add @Component to indicate this is an auto scan component also
package com.customer.services;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import com.customer.dao.CustomerDAO;
 
@Component
public class CustomerService 
{
	@Autowired
	CustomerDAO customerDAO;
 
	@Override
	public String toString() {
		return "CustomerService [customerDAO=" + customerDAO + "]";
	}
}

 
Put this “context:component” in bean configuration file, it means, enable auto scanning feature in Spring. The base-package is indicate where are your components stored, Spring will scan this folder and find out the bean (annotated with @Component) and register it in Spring container.
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-2.5.xsd">
 
	<context:component-scan base-package="com.mkyong.customer" />
 
</beans>

Run it







package com.common;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.customer.services.CustomerService;
 
public class App 
{
    public static void main( String[] args )
    {
    	ApplicationContext context = 
    	   new ClassPathXmlApplicationContext(new String[] {"Spring-AutoScan.xml"});
 
    	CustomerService cust = (CustomerService)context.getBean("customerService");
    	System.out.println(cust);
 
    }
}


output
 
CustomerService [customerDAO=Hello , This is CustomerDAO]

 
This is how auto components scanning works in Spring.
 
Custom auto scan component name
 
By default, Spring will lower case the first character of the component – from ‘CustomerService’ to ‘customerService’. And you can retrieve this component with name ‘customerService’
 
CustomerService cust = (CustomerService)context.getBean("customerService");

 
To create a custom name for component, you can put custom name like this :
@Service("AAA")
public class CustomerService
...
 
Now, you can retrieve it with this name ‘AAA’.

CustomerService cust = (CustomerService)context.getBean("AAA");
 
 
Auto Components Scan Annotation Types

In Spring 2.5, there are 4 types of auto components scan annotation types

  • @Component – Indicates a auto scan component.
  • @Repository – Indicates DAO component in the persistence layer.
  • @Service – Indicates a Service component in the business layer.
  • @Controller – Indicates a controller component in the presentation layer.


So, which one to use? It’s really doesn’t matter. Let see the source code of @Repository,@Service or
@Controller.








 
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
 
	String value() default "";
 
}

 
 

You will noticed that all @Repository,@Service or @Controller are annotated with @Component.
So, can we use just @Component for all the components for auto scanning? Yes, you can, and Spring
will auto scan all your components with @Component annotated.

It’s working fine, but not a good practice, for readability, you should always declare
@Repository,@Service or @Controller for a specified layer to make your code more easier to read,
as following :

 
DAO layer

package com.customer.dao;
 
import org.springframework.stereotype.Repository;
 
@Repository
public class CustomerDAO 
{
	@Override
	public String toString() {
		return "Hello , This is CustomerDAO";
	}	
}

 
Service layer
package com.customer.services;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import com.customer.dao.CustomerDAO;
 
@Service
public class CustomerService 
{
	@Autowired
	CustomerDAO customerDAO;
 
	@Override
	public String toString() {
		return "CustomerService [customerDAO=" + customerDAO + "]";
	}
 
}
 

 








신고
Posted by jeonguk

Spring framework의 DI 디자인패턴에는 두가지 타입이 있다.

1. Setter Injection
2. Constructor Injection


 
 1. Setter Injection
 
A helper class with a setter method.

package com.mkyong.output;
 
import com.mkyong.output.IOutputGenerator;
 
public class OutputHelper
{
	IOutputGenerator outputGenerator;
 
	public void setOutputGenerator(IOutputGenerator outputGenerator){
		this.outputGenerator = outputGenerator;
	}
 
}



A bean configuration file to declare the beans and set the dependency via setter injection (property tag).

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
	<bean id="OutputHelper" class="com.mkyong.output.OutputHelper">
		<property name="outputGenerator">
			<ref bean="CsvOutputGenerator" />
		</property>
	</bean>
 
<bean id="CsvOutputGenerator" class="com.mkyong.output.impl.CsvOutputGenerator" />
<bean id="JsonOutputGenerator" class="com.mkyong.output.impl.JsonOutputGenerator" />
 
</beans>


You just injects a ‘CsvOutputGenerator’ bean into ‘OutputHelper’ object via a setter method (setOutputGenerator).


2. Constructor Injection

This DI method will injects the dependency via a constructor.

A helper class with a constructor.

package com.mkyong.output;
 
import com.mkyong.output.IOutputGenerator;
 
public class OutputHelper
{
	IOutputGenerator outputGenerator;
 
        OutputHelper(IOutputGenerator outputGenerator){
		this.outputGenerator = outputGenerator;
	}
}



A bean configuration file to declare the beans and set the dependency via constructor injection (constructor-arg tag).

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
	<bean id="OutputHelper" class="com.mkyong.output.OutputHelper">
		<constructor-arg>
			<bean class="com.mkyong.output.impl.CsvOutputGenerator" />
		</constructor-arg>
	</bean>
 
<bean id="CsvOutputGenerator" class="com.mkyong.output.impl.CsvOutputGenerator" />
<bean id="JsonOutputGenerator" class="com.mkyong.output.impl.JsonOutputGenerator" />
 
</beans>


You just injects a ‘CsvOutputGenerator’ bean into ‘OutputHelper’ object via a constructor.


참조 사이트 : http://en.wikipedia.org/wiki/Dependency_injection

 
신고
Posted by jeonguk
1. Presendtation Layer
    어플리케이션 중에서 화면을 담당하는 부분
    보통 GUI(Graphic User Interface)부분이라 칭함
    화면을 통하여 사용자로부터 입력을 받거나, 사용자에게 정보를 보여주는 역할

    요구되는 기술
    - 화면 구성요소를 나타내는 방법
       메뉴, 버튼, 각종 화면 콘트롤을 나타내는 방법
    - 화면을 구성하는 방법 - 각종 화면 구성요소를 배치하는 방법
    - 화면으로부터 받은 명령을 처리하는 방법 - 화면 컨트롤의 이벤트를 처리하는 방법
    - 다른 Layer에게 입력받은 명령이나 데이터를 전달하는 방법

2. Business Logic Layer
    사용자로부터 받은 입력을 기준으로 주어진 로직에 따라 각종 일 처리를 담당하는 부분
    일을 처리하는 로직을 통상 비지니스 로직이라 칭함

    요구되는 기술
    - 하나의 로직 상태를 여러 화면과 공유하는 방법
    - 데이터 Layer에 데이터를 주고 받는 방법
    - 여러 프로세스를 병렬로 처리하는 방법

3. Persistence Layer
    데이터를 영구적으로 저장하거나, 저장된 장소에서 데이터를 가져오는 역할을 담당
   
    요구되는 기술
    - 데이터를 파일에 저장, 수정, 삭제하는 방법
    - 데이터를 데이터베이스에 저장, 수정, 삭제하는 방법
    - 데이터베이스에 연결하고 연결을 유지하는 방법

4. Integration Layer
    어플리케이션이 다른 부분과 연동하거나, 통신을 할 필요가 있을 경우, 이에 대한 처리를 담당하는 부분
    위의 사항에 해당하는 부분이 없는 단독 어플리케이션일 경우는 이 Layer가 있을 필요 없음

    요구되는 기술
    - 통신 방법
    - 통신 프로토콜
    - 분산 객체 호출 방법
    - 비동기식으로 외부 시스템에 내용 전달하는 방법

신고

'Framework' 카테고리의 다른 글

어플리케이션 Layer의 종류  (0) 2012.01.17
Posted by jeonguk





1. 사용자의 요청을 DispatcherServlet이 받는다.
2. 요청을 처리해야하는 Controller를 찾기 위해 DispatchServlet은 HandlerMapping에 대한 질의를 시작하고 HandlerMapping은 URL 패턴을 Controller 객체에 매핑하여 Controller를 찾아낸다.
3. DispatcherServlet은 찾은Controller에게 요청을 전달하고 Controller는 서비스계층의 인터페이스를 호출하여 적절한 비지니스 로직을 수행한다.
4. Controller는 비지니스 로직의 수행결과로 받아낸 도메인모델 객체와 함께 뷰이름을 ModelAndView 객체에 저장하여 리턴한다.
5. DispatcherServlet은 응답할 View객체를 찾기위해 ViewResolver에게 질의를 한다.
6. DispatcherServlet은 찾아낸 View객체에 요청을 전달한다.
7. 뷰는 ModelAndView객체에 있는 도메인모델 객체를 이용하여 화면을 구성한다.
신고
Posted by jeonguk