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

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. 사용자의 요청을 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