Spring

properties - 유효성검사, 에러메시지출력

H_eh 2022. 8. 5. 02:11

전체코드1전체코드2

[에러코드].[modelAttribute이름].[객체변수이름] = 메시지

//d1.prpperties
qqq.q1 = 3
qqq.q2 = spring

www.w1=5
www.w2=framework
  • WEB-INF > properties > properties 파일 생성
  • properties 를 이용해서 에러 메시지 출력 가능

 

SpController.java

@Controller
@PropertySources({
	@PropertySource("/WEB-INF/properties/d1.properties"),
	@PropertySource("/WEB-INF/properties/d2.properties")
})
public class SpController {
	
	@Value("${qqq.q1}")
	private int q1;
	@Value("${qqq.q2}")
	private String q2;
	
	@Value("${www.w1}")
	private int w1;
	@Value("${www.w2}")
	private String w2;
	
	@GetMapping("/t1")
	public String a1() {
		System.out.println(q1+q2+"/"+w1+w2);
		return "t1";
	}
}
  • 참조할 properties파일 경로를 지정해준다
  • q1 에 프로퍼티 qqq.q1 를 생성자 주입한다
  • "t1" 요청이 들어오면 저장된 프로퍼티를 콘솔에 출력한다

메시지 다국어, 재로딩 처리

ReloadableResourceBundleMessageSource

전체코드 

 

SpController.java

@Controller
public class SpController {
	@Autowired
	ReloadableResourceBundleMessageSource res;
	
	@GetMapping("/t1")
	public String t1(Model m) {
		String a1 = res.getMessage("aaa.a1", null, null);
		String b1 = res.getMessage("bbb.b1", null, null);
		
		Object a[]= {3, "하이"};
		String c1 = res.getMessage("aaa.a2", a, null);
		
		System.out.println(a1 + b1 + c1);
		
		m.addAttribute("a", a);
		
		return "t1";
	}
}
  • 메시지 객체(ReloadableResourceBundleMessageSource) 를 주입받고 getMessage()로 메시지를 출력한다

 

jsp에서 메시지 출력

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="spring" uri="http://www.springframework.org/tags" %> 

t1
<spring:message code="aaa.a1"/>
<spring:message code="bbb.b1"/>
<spring:message code="aaa.a2" arguments="${a }"/>

 


유효성 검사

전체코드

Data.java

@Size(min=3, max=10)
private String d1;

@Max(100)
private int d2;
  • 유효성을 검사할 데이터 설정

 

SpController.java

package co.jw.sol.controller;

@Controller
public class SpController {
	...	
	@PostMapping("/po")
	public String po(@Valid Data data1, BindingResult result) {
		System.out.println(data1.getD1()+"/"+data1.getD2());
		System.out.println(result);
		
		if(result.hasErrors()) {
			for(ObjectError obj:result.getAllErrors()) {
				System.out.println(obj.getDefaultMessage());
				System.out.println(obj.getCode());
				
				String [] codes = obj.getCodes();
				for(String s:codes) {
					System.out.println(s);
				}
				
				//어노테이션이름.
				if(codes[0].equals("Size.data1.d1")) {
					System.out.println("d1은 3~10글자를 쓸 수 있다");
				}
				else if(codes[1].equals("Max.data1.d2")) {
					System.out.println("d2는 100보다 클 수 없다");
				}
			}//obj end
			return "t1";
		}//hasErrors end
		return "success";
	}//po end
}
  • result.hasErrors()  : 유효성을 위반했을 때, 위반 결과값들을 다 가져온다

 

728x90
728x90