2012-08-23 3 views
1

저는 봄에 익숙하지 않아 CAS에서 작업하고 있습니다. 사용자 인증을 위해 데이터베이스를 쿼리해야하지만 서블릿을 컨트롤러로 사용하고 있습니다. 따라서 서블릿에 SimpleJdbcTemplate을 설정하고 데이터베이스를 쿼리하는 데 사용할 수있는 방법이 있는지 알아야합니다. web.xml 파일 또는 다른 파일을 구성하는 방법이있는 경우.서블릿 용 SimpleJdbcTemplate 설정

이미 감사합니다.

+0

왜 자바 컨트롤러 대신 서블릿을 사용하고 있습니까? –

+0

jasig - CAS를 사용하여 사용자의 유효성을 검사하는 경우 인증 방법을 CAS 서버에 구현해야합니다. 귀하의 질문은 데이터베이스 쿼리 인증을 구성하는 방법입니다. CAS 서버의 메소드? 또는 CAS 서버가 사용자 액세스의 유효성을 검사하면 사용자 권한 부여와 같은 다른 작업을 수행하려고합니까? – kothvandir

답변

3

Servlet 또는 Controller에 직접 JdbcTemplate을 삽입하거나 액세스하는 것은 좋지 않습니다.
중간에 DAO 층을 넣고 JdbcTemplate을 DAO에 삽입하는 것이 더 나은 방법입니다.
JdbcTemplate을 사용하려면 구성에 어딘가에 DataSource을 정의해야합니다 (xml 또는 주석을 통해 스프링 컨텍스트). 당신이 UserDao이있는 경우 UserDaoImpl이 당신의 서블릿에서 같은

public class UserDAOImpl implements UserDAO { 
    private JdbcTemplate jdbcTemplate; 
    //setter and getter for jdbcTemplate 

    public List<Map<String, Object>> getUsers() { 
     String query = "select * from user"; 
     return jdbcTemplate.queryForList(query, new HashMap<String, String>()); 
    } 
} 

보이는 당신, 지금

<bean class="com.xxx.dao.UserDAOImpl" id="userDAO"> 
    <property name="jdbcTemplate" ref="jdbcTemplate"/> 
</bean> 
<bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate"> 
    <constructor-arg ref="dataSource"/> 
</bean> 
and here you need to difine your "dataSource" there are multiple ways to configure it, You may get better help from google. 

을 다음과 같이
, 다음 봄 구성이 될 것입니다, 당신은이의 참조를 얻을 필요 다오 서블릿 클래스의 ServiceLocator

를 사용

... 
public UserDAO getUserDao() { 
    return ServiceLocator.getBean(UserDAO.class); 
} 
... 

다시 여러 가지 방법으로 ServiceLocator을 디자인 할 수 있습니다. 다음은 간단한 구현입니다.

public class ServiceLocator implements ApplicationContextAware { 

    private static ApplicationContext applicationContext; 

    /** 
    * @return Returns the applicationContext. 
    */ 
    public static ApplicationContext getApplicationContext() { 
     return applicationContext; 
    } 

    public static <T> T getBean(Class<T> requiredType) throws BeansException { 
     return getApplicationContext().getBean(requiredType); 
    } 

    /** 
    * @param applicationContext The applicationContext to set. 
    */ 
    public void setApplicationContext(ApplicationContext applicationContext) { 
     ServiceLocator.applicationContext = applicationContext; 
    } 

} 

마지막으로,이 모든 조각을 개별적 따라 읽을 필요가, 독립, 당신은 많이 얻을 구글이나 봄 포럼에서 정확한 도움이 될 것입니다.