2012년 11월 26일 월요일

spring security grantedauthorityimpl deprecated

Spring Security  grantedauthorityimpl deprecated

grantedauthorityimpl  to SimpleGrantedAuthority



       userAuthorities.add (new SimpleGrantedAuthority(String role));



Example 


  Vector<GrantedAuthority> userAuthorities = new Vector<GrantedAuthority>();
          
  List<UserRole> userRole = userService.getUserRole(params);
      
  ListIterator<UserRole> userRoleLiterator =  userRole.listIterator();
          
  while (userRoleLiterator.hasNext()){
         String tempRole = userRoleLiterator.next().getAuthority();
         userAuthorities.add(new  SimpleGrantedAuthority (tempRole));
  }



  위와 같이 GrantedAuthorityImpl 대신 SimpleGrantedAuthority 를 사용하면 된다

2012년 11월 21일 수요일

addressDao

package com.examples.dao;
import org.apache.ibatis.annotations.CacheNamespace;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.examples.vo.AddressVO;
@CacheNamespace(implementation=org.mybatis.caches.ehcache.EhcacheCache.class)
Public interface AddressDAO{
 String GET_ADDRESS_BY_ID = "SELECT * FROM vw_address WHERE id = #{addressId}";
 String INSERT_ADDRESS  = "INSERT into address (building,street,location,town,postCode,countyId,countryId,notes,createdOn,createdBy,active)
               VALUES (#{building},#{street},#{location},#{town},#{postCode},#{countyId},#{countryId},#{notes},sysdate(),#{createdBy},1)";
 String UPDATE_ADDRESS    = "UPDATE address set building=#{building},countyId=#{countyId}, street=#{street},location=#{location},town=#{town},postCode=#{postCode},notes=#{notes},modifiedOn=sysdate(),modifiedBy=#{modifiedBy},countryId=#{countryId} where id= #{id}";
 String DELETE_ADDRESS    = "DELETE from address WHERE id = #{addressId}";

        @Select(GET_ADDRESS_BY_ID)
        @Options(useCache=true)
        public AddressVO doSelectAddress(long addressId) throws Exception; 
        @Insert(INSERT_ADDRESS)
 @Options(useGeneratedKeys = true, keyProperty = "id", flushCache=true)
 public int doCreateAddress(AddressVO address) throws Exception;
 @Update(UPDATE_ADDRESS)
 @Options(flushCache=true)
 public int doUpdateAddress(AddressVO address) throws Exception;
 @Delete(DELETE_ADDRESS)
 @Options(flushCache=true)
 public int doDeleteAddress(long addressId) throws Exception;
}

package com.examples.dao;
import java.util.List;
import org.apache.ibatis.annotations.CacheNamespace;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.examples.vo.AddressVO;
import com.examples.vo.CandidateVO;
import com.examples.vo.EmployerVO;
import com.examples.vo.PersonVO;
@CacheNamespace(implementation=org.mybatis.caches.ehcache.EhcacheCache.class)
public interface CandidateDAO {
 String GET_CANDIDATE_BY_ID="select c.* from candidate c where id=#{id} and active=1"; 
 String GET_CANDIDATES_BY_USER_COMPANY = "select * from vw_company_candidate where companyId=#{companyId} and active=1";
 String GET_CANDIDATE_BY_ID_AND_USER_COMPANY = "select * from vw_company_candidate where companyId=#{companyId} and id=#{candidateId} and active=1";
 String INSERT_CANDIDATE = "INSERT INTO candidate (" +
   " personId,addressId,employerId,clientId,basic,ote,met," +
   " reference,exclusive,createdOn,createdBy,active," +
   " priority,code,offers,referredBy,statusId,salCurrencyId,salTenureId) " +
    "VALUES " +
      " (#{person.id},#{address.id},#{employer.id},#{client.id}," +
      " #{basic},#{ote},#{met},#{reference}," +
      " #{exclusive},sysdate(),#{createdBy},1,#{priority}," +
      " #{code},#{offers},#{referredBy},#{statusId},#{salCurrencyId},#{salTenureId})";
 String UPDATE_CANDIDATE = "UPDATE candidate SET " +
      " personId=#{person.id}, addressId=#{address.id}, employerId=#{employer.id}, clientId=#{client.id}," +
      " basic=#{basic}, ote=#{ote},met=#{met},reference=#{reference}," +
      " exclusive=#{exclusive},modifiedOn=sysdate(),modifiedBy=#{modifiedBy},active=#{active},priority=#{priority}," +
      " code=#{code},offers=#{offers},referredBy=#{referredBy},statusId=#{statusId}, " +
      " salCurrencyId=#{salCurrencyId},salTenureId=#{salTenureId} where id=#{id}";
 String DELETE_CANDIDATE = "update candidate set active=0 where id=#{candidateId}";
 String MAP_CANDIDATE_SECTOR = "insert ignore into candidate_sector(sectorId,candidateId) values (#{sectorId},#{candidateId})";
 @Select(GET_CANDIDATES_BY_USER_COMPANY)
 @Results(value = {
  @Result(property="id", column="id"),
  @Result(property="person",  column="personId",  javaType=PersonVO.class, mailto:one=@One(select=%22com.examples.dao.PersonDAO.doSelectPerson")),
  @Result(property="address", column="addressId", javaType=AddressVO.class, mailto:one=@One(select=%22com.examples.dao.AddressDAO.doSelectAddress"))
 })
 public List<candidatevo> doSelectCandidatesByCompany(long companyId);
 @Select(GET_CANDIDATE_BY_ID)
 @Results({
    @Result(property="id",     column="id"),
    @Result(property="person", column="personId",   javaType=PersonVO.class, mailto:one=@One(select=%22com.examples.dao.PersonDAO.doSelectPerson")),
    @Result(property="address",column="addressId",  javaType=AddressVO.class, mailto:one=@One(select=%22com.examples.dao.AddressDAO.doSelectAddress")),
                         @Result(property="sectors", column="id",   javaType=List.class,many=@Many(select = "com.examples.dao.SectorDAO.doSelectSectorsByCandidate"))
    })

        public CandidateVO doSelectCandidateById(long candidateId);
 @Insert(INSERT_CANDIDATE)
 @Options(useGeneratedKeys = true, keyProperty = "id", flushCache=true)
 public int doCreateCandidate(CandidateVO candidate) throws Exception;

        @Update(UPDATE_CANDIDATE)
 @Options(flushCache=true)
 public int doUpdateCandidate(CandidateVO candidate) throws Exception;
 @Delete(DELETE_CANDIDATE)
 @Options(flushCache=true)
 public int doDeleteCandidate(long candidateId) throws Exception;

        @Insert(MAP_CANDIDATE_SECTOR)
 public void doMapCandidateSector(@Param("sectorId") long sectorId, @Param("candidateId") long candidateId);
}
</candidatevo>

mybatis



    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
       <property name="driverClassName" value="oracle.jdbc.OracleDriver" />
       <property name="url" value="jdbc:oracle:thin:@:1521:" />
       <property name="username" value="" />
       <property name="password" value="" />
    </bean>

    <bean id="transactionManager"    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
          <property name="dataSource" ref="dataSource" />
       </bean>
   
   
       <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
          <property name="dataSource" ref="dataSource" />
          <property name="configLocaltion" value="/WEB-INF/spring/mybatis.xml"></property>
          <property name="mapperLocations" value="com/sbs/news/article/mapper/*.xml" />
       </bean>

<configuration>
 <typeAliases>
  <typeAlias type="com.sbs.news.model.Article" alias="Article"/>
 </typeAliases>

    <mappers>
        <mapper resource="maps/UserDao.xml" />
    </mappers>
</configuration>

spring security 사용상 주의점

Spring3에서 Security 사용

다음과 같을때 유용하다.
1. 관리자에게 권할 별로 접근 메뉴가 다르다(일반운영자, 최종관리자)
2. 동시접속로그인을 제한한다.

url별로 접근 제한을 할 수 있고 권한에 대해 인증을 할 수 있고 로그아웃, 로그인, 세션생성, 비밀번호체크등 많은 클래스파일 작업이 필요없다.


참조 : http://static.springsource.org/spring-security/site/docs/3.0.x/reference/springsecurity-single.html

1. web.xml 편집

1.1 contextConfigLocation 에 security.xml을 추가한다.
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/applicationContext.xml
            classpath:security-context.xml
        </param-value>
    </context-param>


* 여기서 주의할 점은 servlet에서 적용한 contextConfigLocation에 사용하지 말아야 한다. 
이부분에 대해서는 http://actionscripter.tistory.com/28 를 참조 바란다.

    <servlet>
        <servlet-name>Servlet</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                classpath:web-context.xml
                classpath:security-context.xml<!-- 이곳에 이렇게 넣지 마세요 -->
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>




1.2  springSecurityFilterChain 의 filter와 filter-mapping 을추가 

<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>

이로서 web.xml 수정되었다. 
이렇게 적용한후 실행을 하게되면 
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'springSecurityFilterChain' is defined 부분의 에러가 발생한다.

springSecurityFilterChain 을 정의해 주어야 한다는 내용인데 web.xml의 contextConfigLocation 에서 정의된 security-context.xml 파일을 수정하자


2. applicationContext-security.xml 편집
2.1 http 설정

<http auto-config='true'>
    <intercept-url pattern="/**" access="ROLE_USER" />
</http>

그릭 다시 실행을 하면  No bean named 'org.springframework.security.authenticationManager' is defined 이 발생한다.

2.2
<authentication-manager>
    <authentication-provider>
      <user-service>
        <user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
        <user name="bob" password="bobspassword" authorities="ROLE_USER" />
      </user-service>
    </authentication-provider>
  </authentication-manager>

을 함께 넣어주면 실제적으로 로그인 페이지가 뜨는 것을 확인할 수 있다.
이때 로그인을 하기위해서는 authentication-provider 에서 정의된 user name 과 password 를 넣어주면 된다.



[security-context.xml] ################################################################################################
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-3.0.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- ***************************************************************************** -->
    <!-- This context file exists for developers to enter in their own security configurations. -->
    <!-- ***************************************************************************** -->
    <http auto-config='true'>
        <intercept-url pattern="/**" access="ROLE_USER" />
    </http>
    
    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
                <user name="bob" password="bobspassword" authorities="ROLE_USER" />
            </user-service>
        </authentication-provider>
    </authentication-manager>
</beans:beans>

security xml sample

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
  xmlns:beans="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-3.0.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-3.1.xsd">
    <debug/>      
    
 
          
    <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <beans:property name="driverClassName" value="oracle.jdbc.OracleDriver" ></beans:property>
    <beans:property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" ></beans:property>
    <beans:property name="username" value="spring" ></beans:property>
    <beans:property name="password" value="cs550" ></beans:property>
 </beans:bean>
    <http pattern="/images/**"    security="none"/>
    <http pattern="/ckeditor/**"  security="none"/>
    <http pattern="/jquery/**"    security="none"/>
    <http pattern="/grid/**"      security="none"/>
 <http pattern="/css/**"       security="none"/>
 <http pattern="/resources/**" security="none"/>

 <http auto-config="true" use-expressions="true" >
    
        <intercept-url pattern="/login"  access="permitAll"/>
  <intercept-url pattern="/logout" access="permitAll"/>
  <intercept-url pattern="/denied" access="hasRole('ROLE_USER')"/>
  <intercept-url pattern="/**"     access="hasRole('ROLE_USER')"/>
  <intercept-url pattern="/user"   access="hasRole('ROLE_USER')"/>
  <intercept-url pattern="/admin"  access="hasRole('ROLE_ADMIN')"/>

  <form-login login-page="/login"
   authentication-failure-url="/login/failure"
   default-target-url="/"/>

  <access-denied-handler error-page="/denied"/>

  <logout invalidate-session="true"
   logout-success-url="/logout/success"
   logout-url="/logout"/>
      
    </http>
    <authentication-manager>
       <authentication-provider>
          <jdbc-user-service data-source-ref="dataSource"
               users-by-username-query="select username,password, enabled from users where username=?"
         authorities-by-username-query="select u.username, ur.authority from users u,authorities ur
              where u.username = ur.username and u.username =?"
          />
       </authentication-provider>
    </authentication-manager>     
  
</beans:beans>

2012년 4월 30일 월요일

ibatis procedure call

<parameterMap id="myParamMap" class="java.util.Map"> 
<parameter property="username" mode="IN" /> 
<parameter property="roles1" jdbcType="ORACLECURSOR" mode="OUT" /> 
<parameter property="roles2" jdbcType="ORACLECURSOR" mode="OUT" /> 
<parameter property="roles3" jdbcType="ORACLECURSOR" mode="OUT" /> 

</parameterMap

2012년 4월 26일 목요일

procedure SimpleJdbcCall


String procedureName = "procedure name";

this.procCall = new SimpleJdbcCall(jdbcTemplate)
                  .withProcedureName(procedureName)
                  .withoutProcedureColumnMetaDataAccess()
                  .useInParameterNames("year","buildId","ofSavings")
           
                  .declareParameters(
                new SqlParameter("",Types.VARCHAR),
                new SqlParameter("",Types.VARCHAR),
                new SqlParameter("",Types.VARCHAR),
                new SqlOutParameter("",Types.VARCHAR),
                new SqlOutParameter("",Types.VARCHAR));


Map in  = new HashMap<String,Object>();

in.put("parameter Id", parameterValue);
in.put("parameter Id", parameterValue);
in.put("parameter Id", parameterValue);
in.put("parameter Id",  parameterValue );
in.put("parameter Id",  parameterValue);
                 
Map out = procCall.execute(in);

return out;

jQuary Ajax Sample dataType 'json'


$.ajax({
    type: "POST",
    url: "<ContextRoot>/ajaxcall.dol",
    data: param,
    dataType: 'json',
    success: function(result){
     alert ("success");
      var count = result.data.length;

                   var sampleData = result.data[?].?????;
     
    },
    error: function() {
    alert("호출에 실패했습니다.");
    }
    });


@Controller
public Class SampleController {

    @Requestmapping (value="ajaxcall.do",method=RequestMethod.POST)

    public String  sampleHandle (){
      Map <String,Object> resultMap = new HashMap<String,Object>();
     
      // method Function Start
      // method Result Value
       
         resultMap.put ("data",Object);
      // method Function end


      String returnValue =  util.buildJson((HashMap) resultMap);
      return returnValue;
   }
}

2012년 3월 22일 목요일

SpringFramework 3.0 higher @ResponseBody Return Encoding Code UTF-8(한글문제) 해결방안

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;

public class UTF8StringBeanPostProcessor implements BeanPostProcessor {

    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
       
        if(bean instanceof StringHttpMessageConverter){ 
            MediaType mediaType = new MediaType("text", "plain", Charset.forName("UTF-8")); 
            List<MediaType> types = new ArrayList<MediaType>(); 
            types.add(mediaType); 
            ((StringHttpMessageConverter) bean).setSupportedMediaTypes(types); 
        } 
       
        return bean;
    }

    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        return bean;
    }

}









SpringContext.xml



 <bean
      class="com.weems.common.append.config.UTF8StringBeanPostProcessor"></bean>


web.xml

 <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>





Example :


@Controller
@RequestMapping ("home")

public class HomeController {

       @RequuestMapping (value="/response.do",method=RequestMethod.GET)
       public @ResponseBody String responseHandle (){
             String returnString = "한글 땡땡땡 or UTF-8 Code ";
             return returnString;
       }
     
}



or  ResponseEntity Use

   HttpHeaders responseHeaders = new HttpHeaders();
   responseHeaders.setContentType(MediaType.APPLICATION_JSON);

   String returnString = "한글 땡땡땡 or UTF-8 Code ";
   return new   ResponseEntity<Domain>
          (returnString,responseHeaders,HttpStatus.CREATED);



2012년 2월 21일 화요일

Failed to convert property value of type org.springframework.web.multipart.commons.CommonsMultipartFile to required type java.lang.String for property attach

Spring Error Messages : Failed to convert property value of type org.springframework.web.multipart.commons.CommonsMultipartFile to required type java.lang.String for property attach;
nested exception is java.lang.IllegalStateException: Cannot convert value of type [org.springframework.web.multipart.commons.CommonsMultipartFile] to required type [java.lang.String] for property attach: no matching editors or conversion strategy found;

 Spring FileUpload Method convert property value of type missmatch

Domain.java

public class Domain {
     String name; 
     String file;    // => to  CommonsMultipartFile file;

    ..  getter  and setter ..
}

Controller.java
public class uploadController {

               public String uploadHandle(@RequestParam ("file") MultipartFile file ){
                       // more method Control;
               }
}

upload.jsp

<form  method="post" action="upload.do" commandName="domain" 
                                 enctype="multipart/form-data >
<input  type="text" id="name" name="name" />
<input  type="file" id="file" name="file" />
<input type="sumit" value="transfer"  />
</form>
 



 

2012년 2월 20일 월요일

SpringFramework Annotation Config and ResourceRegister

Webinitializer.java
// Comment WebApplicationInitilizer = > Servlet 3.0
public class WebInitializer implements WebApplicationInitializer {

    public void onStartup(ServletContext container) throws ServletException {
       
        // Create the 'root' Spring application Context
        AnnotationConfigWebApplicationContext root
                                       = new AnnotationConfigWebApplicationContext();
        // Application.java
        root.register(Application.class);
       
        // Manager the life cycle if the root application context
        container.addListener(new ContextLoaderListener (root));

        // Create the dispatcher servlet's Spring application context
        AnnotationConfigWebApplicationContext dispatcherContext
                                       = new AnnotationConfigWebApplicationContext();
        // DispatcherContext.java
        dispatcherContext.register(DispatcherContext.class);

        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher =
                                    container.addServlet("dispatcher", new     
                                                                         DispatcherServlet(dispatcherContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");

     }
}


DispatcherContext.java

@Configuration
@EnableWebMvc

@ImportResource({})
@ComponentScan (basePackages = "com.company.show" ,
 excludeFilters = {},includeFilters={})

public class DispatcherContext extends WebMvcConfigurerAdapter {

    private Environment environment;


    // View Resolver Setting
    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the  
                                                /WEB-INF/views directory -->
    <beans:bean  

                 class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    @Bean
    public InternalResourceViewResolver internalResourceViewResolver (){
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
   
    // Resource Setting
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
        // Exercise
        registry.addResourceHandler("/css/**").addResourceLocations("/css/");
        registry.addResourceHandler("/images/**").addResourceLocations("/images/");
      }
        // This same configuration Spring servlet-context.xml
        <!-- Handles HTTP GET requests for /resources/** by efficiently serving up 
                static  resources in the ${webappRoot}/resources directory -->
         <!-- Handles HTTP GET requests for /resources/** config/DispatcherContext.java 

                    Class=addResourceHandlers Append select choice  -->
         //<resources mapping="/resources/**" location="/resources/" />
         //<resources mapping="/jquery/**"    location="/jquery/" />
         //<resources mapping="/css/**"       location="/css/" />

       
     /* ----------------------------------------------------------------------
     <beans:bean id="multipartResolver" 
           class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
         <beans:property name="maxUploadSize">
              <beans:value>10000000</beans:value>
         </beans:property>
      </beans:bean>
      ------------------------------------------------------------------------*/
     @Bean
    public CommonsMultipartResolver multipartResolver (){
       
        System.out.println("=======>>>>> DispatcherContext multipartResolver Called :");
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver.setMaxUploadSize(10000000);
        return multipartResolver;
    }


   

}

Application.java

@Configuration
@EnableTransactionManagement(mode=AdviceMode.ASPECTJ)
public class Application {
}

2012년 2월 19일 일요일

Spring ValidationUtils email Checker

public class DomainValidation implements Validator {
     public boolean supports(Class<?> clazz) {
            return Domain.class.isAssignableFrom(clazz);
     }

     public void validate (Object target , Errors errors ){
                  Domain domain = (Domain) target;
                   ValidationUtils.rejectIfEmptyOrWhitespace(errors, "category", 
                           "required.category","category required !");
                  ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", 
                           "required.email","Email required !");
                  if (!isValidEmailAddress(board.getEmail())) errors.rejectValue("email",
                                                                   "email.invalid", "Email address is invalid");   

      }

      public boolean isValidEmailAddress(String emailAddress){
        String expression="^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+
                                  [A-Z]{2,4}$";
        CharSequence inputStr = emailAddress;
        Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(inputStr);
        return matcher.matches();
    } 



}

Neither BindingResult nor plain target object for bean name 'domain' available as request attribute

Spring framework  validation form error :

@Controller
public ValidationController {
     @RequrstMapping (value="addForm.do",method=RequestMethod.GET
     public String addFormHandle (Model model){
              Domain domain = new Domain();            //  required domain annotation valid
              model.addAttribute ("domain",domain);   //  required domain annotation valid                    return "addForm";
      }

     @RequestMapping(value="addForm.do",method=RequestMethod.POST
      public String addFormPostHandle (@ModelAttribute Domain domain,BindingResult result ){
              if (result.hashErrors ()) {
                   return "addForm";
              } else {
                   return "done.jsp";
              }
    }
}

addForm.jsp

 <form:form  method="post" action="addForm.do" commandName="domain"   enctype="multipart/form-data">

     <table>
         <tr>
            <td><form:input  id="test" /></td><td><form:errors path="test" /></td>
         </tr>
     </table>
 </form:form>

Domain.java

public Domain {
    @NotEmpty
    String test;
    .... getter and setter
}

2012년 1월 2일 월요일

basic spring security

web.xml
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

   <display-name>Spring MVC Application</display-name>
   
    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
              /WEB-INF/spring/root-context.xml
              /WEB-INF/spring/security.xml
        </param-value>
    </context-param>
   
    <!-- Spring MVC -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
   
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Spring Security -->
    <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>

</web-app>


servlet-context.xml (dispatcher-servlet.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
   
    <!-- Enables the Spring MVC @Controller programming model -->
   
   
    <annotation-driven />
    <context:component-scan base-package="com.company.demo" />
   

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>
   
</beans:beans>


security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
  xmlns:beans="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-3.0.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <debug/>              
    <http auto-config="true">
        <intercept-url pattern="/**" access="ROLE_USER"/>
    </http>
   
   
    <authentication-manager>
     <authentication-provider>
      <user-service>
        <user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
        <user name="bob" password="12345" authorities="ROLE_USER" />
      </user-service>
     </authentication-provider>
   </authentication-manager>
</beans:beans>

example. Controller
@Controller
public class HomeController {

    @RequestMapping (value="/",method=RequestMethod.GET)
    public String home(Locale locale,Model model){
       
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        String formattedDate = dateFormat.format(date);
       
        model.addAttribute("serverTime", formattedDate );
        return "home";
    }
}


No bean named 'springSecurityFilterChain' is defined

spring security 설정중에 실수 하기 쉬운것

web.xml에 security 설정중에 -- security.xml을 servletContext에 넣으면
예)
<servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                          /WEB-INF/spring/servlet-context.xml
                          /WEB-INF/spring/security.xml
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
이렇게 Servlet 안에 넣으면 서버 초기화시에 security.xml 을 잘 설정하였다고 하더라도
No bean named 'springSecurityFilterChain' is defined 메시지가 출력되는것은


security.xml 은 Context root 에 설정이 되어야 하기 때문에 발생한다
따라서 설정은 다음과 같이
    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
              /WEB-INF/spring/root-context.xml
              /WEB-INF/spring/security.xml
        </param-value>
    </context-param>
설정하면 문제없이 초기화 된다 ..


security.xml 최소 설정
<http>
        <intercept-url pattern="/**" access="ROLE_USER" />
</http>