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년 3월 22일 목요일
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;
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
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/" />
@Bean
public CommonsMultipartResolver multipartResolver (){
System.out.println("=======>>>>> DispatcherContext multipartResolver Called :");
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(10000000);
return multipartResolver;
}
}
Application.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>
------------------------------------------------------------------------*/<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();
}
}
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){
}
@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
}
@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";
}
}
<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>
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>
피드 구독하기:
글 (Atom)