Pokazywanie postów oznaczonych etykietą Spring examples. Pokaż wszystkie posty
Pokazywanie postów oznaczonych etykietą Spring examples. Pokaż wszystkie posty

czwartek, 13 grudnia 2012

Spring examples #2 - Testing Controller using Spring MVC with session scope

Sometimes there is need to store user session data in a session object. There are two choices for that. We can add session scope to a specific object or to whole controller. For testing purposes it is easier (however, not better) to choose the second option. Let us add some annotations to controller:
@Controller
@Scope("session")
public class MyController {

 @Autowired
 SomeSingletonFromContext singleton;

 SessionObject sessionObject = new SessionObject();

 @RequestMaping("/my.htm")
 public void myRequest(HttpServletRequest, HttpServletResponse) {
  ServletOutputStream out = response.getOutputStream();
  response.setContentType("application/json");
  response.setHeader("Cache-Control", "no-cache");
  out.print("Hello Session User");
 }
}
In the tricky part we will enable session for testing. The context configuartion below is our "access point" for controller testing class. Note the 'import' tag pointing to default servlet configuration.



  
      
          
              
                  
              
          
      
  

  


In the servlet-context we need to scan for controller:



Finally we have to set up our test:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({
 "file:path/to/test-context-as-above.xml"})
public class MyControllerTest {
 
    private MockHttpServletRequest request;
    private MockHttpServletResponse response;
    
    @Autowired
    private MyController myController;
 
    @Before
    public void setUp() {
     request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();        
    }

    @Test
    public void testSubmit() throws Exception {

     request.setMethod("POST");
        request.setRequestURI("/my.htm");
        request.addParameter("param", "value");
        
        @SuppressWarnings("unused")
        final ModelAndView mavBack = new AnnotationMethodHandlerAdapter()
            .handle(request, response, controller);
        
        assertEquals(response.getContentType(), "application/json");

    }
}
That's all.

wtorek, 17 lipca 2012

Spring examples #1 - beginning with spring


I decided to prepare for Spring certification. Therefore, in the series of 'Spring examples' posts I will introduce and clean up the most important Spring concepts.

The source code for this post is available at:
git clone git@bitbucket.org:marpiech/iseqspringcore.git

Prerequisities:
- eclipse: download 'Eclipse IDE for Java EE Developers' from http://www.eclipse.org/downloads/
- maven: download it from http://maven.apache.org/download.html or by sudo apt-get install maven2 
- m2eclipse: in eclipse Help -> Marketplace -> Maven integration for Eclipse -> install
- SpringSource Tool Suite: in eclipse Help -> Marketplace -> STS -> install

First, we have to create directory structure. bash
mkdir iseqspringcore
cd iseqspringcore
mkdir -p src/{test,main}/{java,resources}
Next, we need to set up maven.
nano pom.xml
and paste:


 4.0.0

 com.intelliseq
 spring-tutorial
 1.0

 Spring Tutorial Part 1
Now, we have to prepare eclipse project. bash
mvn install
mvn eclipse:eclipse

Let's switch to eclipse.
File -> Import -> General -> Existing Projects into workspace
RightClick on Project -> Configure -> Convert to maven project

Add maven repository to pom.xml

 
       central
       Maven Repository Switchboard
       default
       http://repo1.maven.org/maven2
       
         false
       
   

RightClick on Project -> Maven -> Add Dependency -> org.springframework, spring-context
Have a look at pom.xml and in project at Maven Dependencies set of libraries.

In src/main/java create package com.intelliseq.springexamples.core Create application-context.xml in the com.intelliseq.springexamples package. There are two two types of bean instantiation through setters: classic one and modern one (see below).


 
  
  
 

 

 
  
 
Let's create Person class in the com.intelliseq.springexamples.core package.
package com.intelliseq.springexamples.core;

public class Person {
 
 private String firstName;
 private String familyName;
 
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public void setFamilyName(String familyName) {
  this.familyName = familyName;
 }

 @Override
 public String toString() {
  return firstName + " " + familyName;
 }
}
And finally let's create application runner class SpringApp in the com.intelliseq.springexamples.core package. The SpringApp class uses application-context through ClassPathXmlApplicationContext class.
package com.intelliseq.springexamples.core;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringApp {

 public static void main (String[] args) {
  ApplicationContext context =
       new ClassPathXmlApplicationContext(new String[] {"com/intelliseq/springexamples/application-context.xml"});
  Person person = (Person) context.getBean("person");
  System.out.println(person);
  Person modernPerson = (Person) context.getBean("person-modern");
  System.out.println(modernPerson);
 }
 
}
Run Spring App and voila.