SpringMVC + JSON RESTful 스타일 기반 서버 메모 구축
Maven 으로 새 프로젝트 를 선택 하여 ide 에 가 져 올 수도 있 고, ide 에서 직접 Maven 을 새로 만 들 수도 있 습 니 다.여 기 는 후 자 를 선택한다.eclipse javaEE 버 전, maven, Tomcat 를 다운로드 합 니 다.exlipse 는 maven 플러그 인 을 직접 설치 할 수 있 습 니 다. 주 소 는?http://m2eclipse.sonatype.org/sites/m2e。
Maven Project 를 새로 만 들 고 웹 프로젝트 를 구축 합 니 다. maven - archetype - webapp 형식 을 선택 하 십시오.GroupID 는 프로젝트 조직의 유일한 식별 자 이 며, 실제 JAVA 에 대응 하 는 가방 의 구 조 는 main 디 렉 터 리 에 있 는 자바 의 디 렉 터 리 구조 입 니 다.ArtifactID 는 프로젝트 의 유일한 식별 자 입 니 다. 실제 대응 하 는 프로젝트 의 이름 은 프로젝트 루트 디 렉 터 리 의 이름 입 니 다.
프로젝트 생 성 후 프로젝트 수정 Project Facets - > Dynamic web Module 버 전 2.5http://www.cnblogs.com/shangxiaofei/p/5447150.html
새 maven 프로젝트 를 만 든 후 pom. xml 에 필요 한 라 이브 러 리 를 추가 합 니 다.일반적으로 spring 과 관련 된 jar 가방 과 jackson (json 과 관련 된 기능 을 봉 인 했 고 comons - * 가 필요 하 다 는 튜 토리 얼 도 있 습 니 다. 잠시 사용 하지 않 았 습 니 다) 을 포함 합 니 다. 다른 라 이브 러 리 는 추가 할 필요 가 있 으 면 추가 합 니 다.간단 한 방법 은 pom. xml 의 Dependencies 페이지 를 열 고 add 를 선택 하여 해당 라 이브 러 리 를 검색 하면 됩 니 다.물론 인터넷 에서 모든 의존 항목 을 직접 복사 하 는 것 이 더 간단 하 다.
프로젝트 에 Tomcat 서버 를 연결 합 니 다.
술부 배치
mvc-dispatcher
/
이 탭 은 모든 Action 요청 경 로 를 수정 하 는 RESTful 스타일 개발 에 필요 한 것 입 니 다.
이 탭 은 Spring MVC 배포 요청 이 컨트롤 러 에 필요 한 Default Annotation Handler Mapping 과 AnnotationMethodHandler Adapter 인 스 턴 스 를 등록 하 였 습 니 다.@ Control 주해 의 전제 설정 을 확보 하 였 으 며, 머리 에 관련 주 소 를 추가 하지 않 으 면 오류 가 발생 할 수 있 습 니 다.xmlns:mvc="http://www.springframework.org/schema/mvc"
돌아 오 는 jsp 파일 경 로 를 주의 하 십시오. 이것 은 그리 중요 하지 않 습 니 다. 오류 만 발생 하지 않 으 면 됩 니 다.
데이터 수신 및 처리
controller 패키지 및 구현 클래스 BaseController (패키지 이름 WEB - INF / mvc - dispatcher - servlet. xml 에 설정 되 어 있 음) 를 추가 합 니 다.
@Controller
public class BaseController {
/*@RequestMapping(value="/fruit", method = POST)
RESTful , GET POST ,
method= 。*/
@RequestMapping("/index")
public String index() {
return "index";
}
@RequestMapping(value="/jsonfeed")
/*@ResponseBody Controller ,
HttpMessageConverter ,
Response body 。 。
:
html , ( json、xml ) */
public @ResponseBody MyJson getJSON() {
System.out.println("Your Message : ");
MyJson json = new MyJson();
json.setResult(1);
json.setInfo("apple");
return json;
}
@RequestMapping(value="/fruit", method = POST)
public @ResponseBody Fruits getFruit(@RequestBody Fruits fr) {
System.out.println("Your Message : "+fr);
Fruits fruit = new Fruits();
fruit.setNumber(fr.getNumber());
fruit.setFruit(fr.getFruit());
fruit.setStatus(1);
return fruit;
}
}
@ RequestMapping 과 @ Response Body 주해 의 역할 은 모두 주석 에 쓰 여 있 습 니 다. 여 기 는 주로 @ RequestBody 주 해 를 다시 한 번 말씀 드 리 겠 습 니 다.일반적으로 클 라 이언 트 가 POST 요청 을 보 내 는 요청 은 header 의 body 에 적 혀 있 습 니 다. 보통 JSON. stringify () 를 문자열 로 변환 하기 때문에 서버 가 post 요청 을 처리 할 때 @ PathVariable 주 해 를 사용 할 때 요청 데이터 의 속성 을 직접 가 져 올 수 없습니다. 그러나 @ RequestParam 주해 로 데 이 터 를 가 져 올 수 있 을 것 같 습 니 다 (다른 의존 이 필요 합 니 다). 여 기 는 잘 모 르 겠 습 니 다.좀 더 탐구 할 필요 가 있다.내 가 이 문 제 를 만 났 을 때 가장 먼저 생각 한 방법 은 문자열 을 자바 의 Map, List 또는 대상 등 데이터 구조 로 바 꾸 는 것 이다.그래서 저 는 Fruits 대상 을 만 들 었 습 니 다.
public class Fruits {
private int number;
private String fruit;
private int status;
public int getNumber() {
return number;
}
public void setNumber(int name) {
number = name;
}
public String getFruit() {
return fruit;
}
public void setFruit(String name) {
fruit = name;
}
public int getStatus() {
return status;
}
public void setStatus(int name) {
status = name;
}
}
프레임 은 자동 으로 JSON 과 대상 을 바 꿔 준다.이렇게 RESTful 스타일 을 기반 으로 한 Spring MVC 웹 서버 가 만 들 어 졌 습 니 다.다음 단 계 는 파일 을 어떻게 전송 하 는 지 조사 할 준비 가 되 어 있다.
클 라 이언 트 는 React Native 로 썼 습 니 다. 그 중에서 POST 가 요청 한 API 가 사용 하 는 fetch 입 니 다.
파일 업로드 서비스 추가
프로젝트 는 파일 업로드 기능 을 추가 하 라 고 요구 하여 기 존 프로젝트 를 바탕 으로 대응 하 였 다.이 강 좌 는 괜찮다.http://www.yiibai.com/spring_mvc/spring-mvc-file-upload-tutorial.html。
주로 pom. xml 에 comons. io 와 comons. fileupload 의존 도 를 추가 하고, 뮤 직 비디오 c - dispatcher - servlet 에 multipart Resolver 설정 을 추가 하 며, 업로드 파일 크기 제한 등 을 포함 합 니 다.
클 라 이언 트 가 파일 을 업로드 하 는 것 은 폼 에 있 기 때문에 여기에 대응 해 야 합 니 다. @ RequestParam ("files") 의 files 는 폼 에 자신 이 설정 한 속성 입 니 다.
마지막 으로 모든 xml 파일 과 처리 파일 이 올 라 온 controller 를 붙 여 주세요.
pom.xml
4.0.0
com.psh
xxxDemoServer
war
0.0.1-SNAPSHOT
xxxDemoServer Maven Webapp
http://maven.apache.org
junit
junit
3.8.1
test
org.springframework
spring-web
4.3.9.RELEASE
org.springframework
spring-webmvc
4.3.9.RELEASE
org.springframework
spring-beans
4.3.9.RELEASE
org.springframework
spring-expression
4.3.9.RELEASE
org.springframework
spring-core
4.3.9.RELEASE
org.springframework
spring-aop
4.3.9.RELEASE
org.springframework
spring-context
4.3.9.RELEASE
javax.servlet
javax.servlet-api
3.0.1
com.fasterxml.jackson.core
jackson-core
2.9.1
com.fasterxml.jackson.core
jackson-annotations
2.9.1
com.fasterxml.jackson.core
jackson-databind
2.9.1
commons-fileupload
commons-fileupload
1.3.2
commons-io
commons-io
2.5
xxxDemoServer
web.xml
xxxDemoServer
CharacterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceEncoding
true
CharacterEncodingFilter
/*
mvc-dispatcher
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
/WEB-INF/mvc-dispatcher-servlet.xml
1
mvc-dispatcher
/
org.springframework.web.context.ContextLoaderListener
applicationContext.xml
BaseController. java 세 션
@RequestMapping(value="/upload/audio", method = POST)
public @ResponseBody Fruits saveAudio(HttpServletRequest request,
@RequestParam("files") MultipartFile[] files) {
System.out.println("Your Message got ");
// Root Directory.
String uploadRootPath = request.getServletContext().getRealPath(
"upload");
System.out.println("uploadRootPath=" + uploadRootPath);
File uploadRootDir = new File(uploadRootPath);
//
// Create directory if it not exists.
if (!uploadRootDir.exists()) {
uploadRootDir.mkdirs();
}
//
List uploadedFiles = new ArrayList();
for (int i = 0; i < files.length; i++) {
MultipartFile file = files[i];
// Client File Name
String name = file.getOriginalFilename();
System.out.println("Client File Name = " + name);
if (name != null && name.length() > 0) {
try {
byte[] bytes = file.getBytes();
// Create the file on server
File serverFile = new File(uploadRootDir.getAbsolutePath()
+ File.separator + name);
// Stream to write data to file in server.
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
//
uploadedFiles.add(serverFile);
System.out.println("Write file: " + serverFile);
} catch (Exception e) {
System.out.println("Error Write file: " + name);
}
}
}
Fruits fruit = new Fruits();
fruit.setNumber(1);
fruit.setFruit("pineapple");
fruit.setStatus(1);
return fruit;
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.