스프링 중급 과정
// , value path , ,{"/path1","/path2"}
@RequestMapping(value = {"/profile/{groupId}/{userId}"})
// Controller , HttpMessageConverter , Response body 。
// , , ,
@ResponseBody
// PathVariable, RequestParam
public String profile(@PathVariable("groupId") String groupId,
@PathVariable("userId") int userId,
@RequestParam(value = "type", defaultValue = "1") int type,
@RequestParam(value = "key", defaultValue = "nowcoder") String key) {
}
##
$!{ / }
#*
*#
##.index 0 ,.count
#foreach($color in $colors)
Color$!(foreach.count)/$(foreach.index):$!(color)
#
//java
@RequestMapping(value = {"/vm"})
//model , html
public String news(Model model){
model.addAttribute("value1", "vv1");
List colors = Arrays.asList(new String[]{"RED", "GREEN", "BLUE"});
Map map = new HashMap();
for (int i = 0; i < 4; i++) {
map.put(String.valueOf(i), String.valueOf(i * i));
}
model.addAttribute("colors", colors);
model.addAttribute("map", map);
return "news";
}
// news.vm value1
Hello, VM
## ( )
$!{value1}## ,
$!{value2}
${value3}##
##for
#foreach ($color in $colors)
Color $!{foreach.index}/$!{foreach.count}:$!{color}
#end
#foreach($key in $map.keySet())
Number $!{foreach.index}/$!{foreach.count}:$!{key} $map.get($key)
#end
#foreach($kv in $map.entrySet())
Number $!{foreach.index}/$!{foreach.count}:$!{kv.key} $!{kv.value}
#end
User: $!{user.name}
User: $!{user.getName()}
#set($hello = "hello") ##
#set($hworld1 = "$!{hello} world")
#set($hworld2 = '$!{hello} world')
hworld1: $hworld1
hworld2: $hworld2
b. include 와 parse##header.vm
Title $!title
##news.vm
## title
#set($title = "nowcoder")
Include: #include("header.vm")
Parse: #parse("header.vm")
/* Include: TiTle $!title Parse: TiTle nowcoder
,include ,parse */
c. macro #macro(render_color, $color, $index)
Color By Macro $index, $color
#end
#foreach ($color in $colors)
#render_color($color, $foreach.index)
#end
요청 과 응답 a. 요청 매개 변수 분석, 쿠키 읽 기, http 요청 필드 와 파일 업로드 @RequestMapping(value = {"/request"})
@ResponseBody
//
public String request(HttpServletRequest req,
HttpServletResponse resp,
HttpSession session){
StringBuilder sb = new StringBuilder();
// ,
Enumeration headerNames = req.getHeaderNames();
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
sb.append(name + ":" + req.getHeader(name) + "
");
}
return sb.toString();
}
b. 응답 페이지 내용 반환, 쿠키 전송, http 필드 설정, headers@RequestMapping(value = {"/response"})
@ResponseBody
public String response(@CookieValue(value = "nowcoderid", defaultValue = "a") String nowcoderId,
@RequestParam(value = "key", defaultValue = "key") String key,
@RequestParam(value = "value", defaultValue = "value") String value,
HttpServletResponse resp) {
resp.addCookie(new Cookie(key,value));
resp.addHeader(key, value);
return "NowCoderId From COOkie: " + nowcoderId;}
301 로 재 설정: 영구적 으로 이동 합 니 다. 첫 번 째 방문 후 브 라 우 저 에 기록 하고 다시 방문 할 때 원래 주소 에 먼저 접근 하지 않 고 바로 방향 을 바 꾸 는 경 로 를 이동 합 니 다.302: 임시 이전, 직접적인 방식 return "redirect: /" @RequestMapping("/redirect/{code}")
public RedirectView redirect(@PathVariable("code") int code) {
RedirectView red = new RedirectView("/",true);
if (code == 301) {
red.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
}
return red;
}
오류 처리 @RequestMapping("/admin")
@ResponseBodypublic
String admin(@RequestParam(value = "key", required = false) String key){
if ("admin".equals(key)) {
return "Hello admin! ";
}
// , , ,
throw new IllegalArgumentException("Key ");
}
/* :Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Wed Nov 16 14:03:51 CST 2016
There was an unexpected error (type=Internal Server Error, status=500).
Key */
//
@ExceptionHandler()
@ResponseBody
public String error(Exception e) {
return "error: " + e.getMessage();
}
// :error: Key
IoC: 제어 반전 은 두 가지 유형 으로 나 뉘 는데 주입 (DI) 과 검색 (DL) 에 의존 하고 전자 응용 이 광범 위 하 다. IoC 는 보통 전자 를 말한다.// , ,
//Service.java
public String service(){
return "service()";
}
//Application.java
public String application(){
private Service service;
public Application(Service service){
this.service = service;
}
}
// , ,spring , ,
//Service.java
@Service
public String service(){
return "service()";
}
//Application.java
public String application(){
@AutoWired
private Service service;
}
}
AOP: 절단면 을 대상 으로 프로 그래 밍 하고 모든 업 무 를 처리 해 야 하 는 업무, 예 를 들 어 log 서비스 @Aspect
@Component
public class LogAspect {
private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);
@Before("execution(* com.nowcoder.controller.*Controller.*(..))")
public void beforeMethod(JoinPoint joinPoint) {
StringBuilder sb = new StringBuilder();
for (Object arg : joinPoint.getArgs()) {
sb.append("arg:" + arg.toString() + "|");
}
logger.info("before time: " + new Date());
logger.info("before method: "+ sb.toString());
}
@After("execution(* com.nowcoder.controller.IndexController.*(..))")
public void afterMethod() {
logger.info("after method: ");
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.