Estos son mis principios. Si a usted no le gustan, tengo otros

Spring MVC y Spring Security

Posted: June 13th, 2010 | Author: Edu | Filed under: Code, Java, Spring, Spring MVC | Tags: , , , | No Comments »
VN:F [1.9.2_1090]
Rating: 0.0/5 (0 votes cast)

En este post voy a explicar cómo proteger una aplicación Spring MVC utilizando el módulo Spring Security. Se trata de una guía muy ràpida y para nada seria. Se parte de la base de que tenemos un proyecto web Maven recien generado :-)

Dependencias a añadir al fichero pom.xml de Maven.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring</artifactId>
            <version>2.5.6.SEC01</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>2.5.6.SEC01</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>2.0.5.RELEASE</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>

Modificaciones de /WEB-INF/web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 
    <!-- Listener que inicializa el contexto de Spring -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- Ubicación del fichero de configuración de Spring -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <!-- Dispatcher Servlet -->
    <servlet>
        <servlet-name>springapp</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springapp</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
    <!-- Filtro de Spring Security que intercepta las llamadas a las URL de
         la aplicación -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

Contenido de /WEB-INF/applicationContext.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:security="http://www.springframework.org/schema/security"
    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
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-2.0.4.xsd">
 
    <!-- Configuración del acceso a las diferentes URL de la aplicación en función del
         rol del usuario. En este caso toda la aplicación está protegida y se requiere
         de un usuario con rol ROLE_USER para acceder -->
    <security:http auto-config="true">
        <security:intercept-url pattern="/**" access="ROLE_USER" />
    </security:http>
 
    <!-- Algunos usuarios de prueba. Posteriormente podremos cambiar el servicio para
         que vaya a buscar la información de los usuarios a otro lugar (BBDD) -->
    <security:authentication-provider>
        <security:user-service>
            <security:user name="admin" password="admin" authorities="ROLE_USER, ROLE_ADMIN" />
            <security:user name="user1" password="user1" authorities="ROLE_USER" />
            <security:user name="user1" password="user1" authorities="ROLE_USER" />
        </security:user-service>
    </security:authentication-provider>
 
</beans>

Una vez hecho esto, al acceder a cualquier recurso de la aplicación se nos mostrará la pantalla de login por defecto de Spring Security. Otro día veremos cómo personalizar esta página de login. Os dejo con una captura de la página:

Un saludo

VN:F [1.9.2_1090]
Rating: 0.0/5 (0 votes cast)

Spring Annotations Inject properties / Anotaciones Spring Inyectar properties

Posted: December 4th, 2009 | Author: Edu | Filed under: Java, Spring | Tags: , | No Comments »
VN:F [1.9.2_1090]
Rating: 0.0/5 (0 votes cast)

applicationContext.xml:

File parameters.properties / Fichero parameters.properties:

MyComponent.path=/some/path

Spring component / Componente gestionado por Spring:

import javax.annotation.PostConstruct;
import org.springframework.stereotype.Component;
 
@Component("MyComponent")
public class MyComponent {
 
    private String path;
 
    @PostConstruct
    public void loadPath() {
 
        System.out.println("Loading from " + this.path);
    }
 
    public String getPath() {
        return path;
    }
 
    public void setPath(String path) {
        this.path = path;
    }
}
VN:F [1.9.2_1090]
Rating: 0.0/5 (0 votes cast)

Simple Spring Proxy

Posted: November 23rd, 2009 | Author: Edu | Filed under: Design Patterns, Java, Spring | Tags: , , | No Comments »
VN:F [1.9.2_1090]
Rating: 0.0/5 (0 votes cast)

Simply a code I wrote today at my Spring Training / Simplemente un código que escribí hoy en el curso de Spring.

applicationContext.xml:

1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="UTF-8" ?>
<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="postProcessor" class="com.sourcerebels.test.postprocessor.PostProcessor"/>
           <bean id="someBusinessRule" class="com.sourcerebels.test.postprocessor.SomeBusinessRule" lazy-init="true">
               <property name="message" value="someBusinessRule executed"/>
           </bean>
</beans>

Advice:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.sourcerebels.test.postprocessor;
 
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
 
public class TransactionAdvice implements MethodBeforeAdvice, AfterReturningAdvice {
 
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println("Starting Transaction");
    }
 
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("Commit Transaction");
    }
}

BusinessRule interface:

1
2
3
4
5
6
package com.sourcerebels.test.postprocessor;
 
public interface BusinessRule {
 
    void run();
}

SomeBusinessRule class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.sourcerebels.test.postprocessor;
 
public class SomeBusinessRule implements BusinessRule {
 
    private String message;
 
    public void run() {
        System.out.println(message);
    }
 
    public String getMessage() {
        return message;
    }
 
    public void setMessage(String message) {
        this.message = message;
    }
}

Postprocessor:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.sourcerebels.test.postprocessor;
 
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
 
/**
 * @author edu@sourcerebels.com
 */
public class PostProcessor implements BeanPostProcessor {
 
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessBeforeInitialization");
        return bean;
    }
 
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessAfterInitialization");
        if (bean instanceof BusinessRule) {
            System.out.println("building proxy object");
            ProxyFactory proxyFactory = new ProxyFactory(bean);
            proxyFactory.addInterface(BusinessRule.class);
            proxyFactory.addAdvice(new TransactionAdvice());
            return proxyFactory.getProxy();
        }
        return bean;
    }
}

Main:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.sourcerebels.test.postprocessor;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class Main {
 
    public static void main(String[] args) {
 
        String[] paths = { "com/sourcerebels/test/postprocessor/applicationContext.xml" };
        ApplicationContext ctx = new ClassPathXmlApplicationContext(paths);
 
        BusinessRule negocio = (BusinessRule) ctx.getBean("someBusinessRule");
        negocio.run();
 
        negocio = (BusinessRule) ctx.getBean("someOtherBusinessRule");
        negocio.run();
    }
}
VN:F [1.9.2_1090]
Rating: 0.0/5 (0 votes cast)

Spring MVC. File Upload / Subir ficheros al servidor.

Posted: November 21st, 2009 | Author: Edu | Filed under: Java, Spring, Spring MVC | Tags: , , | No Comments »
VN:F [1.9.2_1090]
Rating: 0.0/5 (0 votes cast)

HTML code / Código HTML:

<form method="POST" enctype="multipart/form-data" action="./myControllerURL">
	<input type="file" name="file"/>
	<input type="submit" name="submit" value="File Upload - Subir fichero"/>
</form>

Spring configuration / Configuración Spring:

<bean id="multipartResolver"
	class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<property name="maxUploadSize" value="100000000"/>
</bean>

Controller code / código del controlador:

MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
 
MultipartFile file = multipartRequest.getFile("file");
 
InputStream inputStream = null;
OutputStream outputStream = null;
File tmpFile = null;
 
System.out.println("file.getOriginalFileName(): "
		+ file.getOriginalFilename());
System.out.println("size:" + file.getSize());
try {
 
	if (file.getSize() > 0) {
 
		tmpFile = File.createTempFile("document_", ".tmp");
 
		inputStream = file.getInputStream();
		outputStream = new FileOutputStream(tmpFile);
		int readBytes = 0;
		byte[] buffer = new byte[8192];
		while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) {
			outputStream.write(buffer, 0, readBytes);
		}
		outputStream.close();
		inputStream.close();
		System.out.println("Saved file: " + tmpFile.getAbsolutePath());
	}
 
} catch (IOException ioe) {
	// TODO - Manage the exception.
}
VN:F [1.9.2_1090]
Rating: 0.0/5 (0 votes cast)