1. SpringMVC 기본 사항을 시작하여 HelloWorld 프로그램 만들기
1. 첫째, SpringMVC에서 필요한 JAR 패키지를 가져옵니다.
2. Web.xml 구성 파일에서 SpringMVC에 대한 구성 추가
<!-SpringMvcdispatcherServlet의 설정을 구성하고 매핑을 구성합니다-> <servlet> <servlet-name> springmvc </servlet-name> <servlet-class> org.springframework.web.servlet.dispatcherServlet </servlet-class> <anit-param> <param-name> contecconfiglopopod. <Param-value> classpath : SpringMvc-servlet.xml </param-value> </init-param> <!-<load-on-startup> 1 </load-on-startup>-> </servlet> <servlet-mapping> <servlet-name> springmvc </servlet-name> <url-pattern> </url-pattern> </url-pattern>
3. SRC에서 SpringMVC-Servlet.xml 구성 파일을 추가하십시오
<? xml 버전 = "1.0"alcoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xmlns : xsi = "http://ww.w.w3.org/2001/xmlschema-instance" xmlns : context = "http://www.springframework.org/schema/context"xmlns : mvc = "http://www.springframework.org/schema/mvc"xsi : skemalocation = "http://www.spremframframwork.org/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.sprampramework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd "> <!-패키지 및 서브 패키지를 스캔합니다-> 컨텍스트 : component-scan base-package ="test.sppringmvc "///> -> <mvc : default-servlet handler /> <! <!-접미사-> <속성 이름 = "접미사"value = ". jsp"/> </bean> </beans>
4. Web-INF 폴더에서 JSP라는 폴더를 작성하여 JSP보기를 저장합니다. hello.jsp를 만들고 몸에 "Hello World"를 추가하십시오.
5. 아래와 같이 패키지 및 컨트롤러를 만듭니다
6. 컨트롤러 코드를 쓰십시오
@controller @requestmapping ( "/mvc") public class mvccontroller {@requestmapping ( "/hello") public String hello () {return "hello"; }}7. 서버를 시작하고 http : // localhost : 8080/project name/mvc/hello를 입력하십시오
1. DispatcherServlet
DispatcherServlet은 web.xml 파일에 구성된 사전 컨트롤러입니다. 일치하는 요청을 가로 채기. 일치하는 규칙을 가로 채는 서블릿은 그 자체로 정의되어야합니다. 차단 된 요청은 해당 처리 규칙에 따라 대상 컨트롤러에 배포됩니다. 이것은 스프링 MVC를 구성하는 첫 번째 단계입니다.
2. InternalresourceviewResolver
이름 Resolver를보십시오
3. 위의 주석
@Controller는 스프링 컨텍스트에 콩을 등록 할 책임이 있습니다.
@requestmapping annotation 컨트롤러에 대해 처리 할 수있는 URL 요청을 지정합니다.
@제어 장치
스프링 컨텍스트에 콩을 등록 할 책임이 있습니다
@requestmapping
주석은 컨트롤러에 대해 처리 할 수있는 URL 요청을 지정합니다.
@requestbody
이 주석은 요청 요청의 본문 데이터의 일부를 읽고, 구문 분석을 위해 시스템에 의해 구성된 httpmessageconverter를 사용한 다음, 해당 데이터를 반환 할 객체에 바인딩 한 다음 컨트롤러의 메소드 매개 변수에 httpmessageconverter가 반환 한 객체 데이터를 바인딩하는 데 사용됩니다.
@ResponseBody
이 주석은 컨트롤러 메소드가 반응 객체의 신체 데이터 영역으로 반환 된 객체를 적절한 httpmessageconverter를 지정된 형식으로 변환 한 후 사용됩니다.
@modelattribute
메소드 정의 : 스프링 MVC에서 @ModelAttribute 주석을 사용하여 대상 처리 메소드를 호출하기 전에 메소드 수준에서 @ModelAttribute를 주석으로하는 메소드를 하나씩 호출합니다.
메소드 매개 변수를 입력하기 전에 @ModelAttribute 주석을 사용하십시오. 암시 적 개체에서 객체를 얻고 요청 매개 변수를 객체에 바인딩 한 다음 메소드를 매개 변수 개체에 전달하여 메소드를 모델에 추가하십시오.
@requestparam
@requestparam을 사용하여 요청 매개 변수를 요청 메소드로 전달합니다.
@pathvariable
URL 자리 표시기를 입력 매개 변수에 바인딩하십시오
@ExceptionHandler
메소드에 주석이 달성되면 예외가 발생하면 메소드가 실행됩니다.
@controlleradvice
컨트롤러를 글로벌 예외 처리 클래스로 만드십시오. 클래스에서 @ExceptionHandler 메소드로 주석이 달린 메소드는 컨트롤러에서 발생하는 모든 예외를 처리 할 수 있습니다.
// 자동으로 일치 @requestmapping ( "/person") public String toperson (문자열 이름, double age) {system.out.println (name+""+age); "안녕하세요"를 반환합니다. }1. 개인 엔티티 수업을 작성하십시오
패키지 test.springmvc.model; public class person {public string getName () {return name; } public void setName (문자열 이름) {this.name = 이름; } public int getage () {반환 연령; } public void 설정 (int Age) {this.age = age; } 개인 문자열 이름; 사적인 int 연령; }2. 컨트롤러에 메소드를 쓰십시오
// 자동으로 권투 @requestmapping ( "/person1") public String toperson (person p) {System.out.println (p.getName ()+""+p.getage ()); "안녕하세요"를 반환합니다. } // 매개 변수는 initBinder @RequestMapping ( "/date") 공개 문자열 날짜 (날짜 날짜) {System.out.println (날짜); "안녕하세요"를 반환합니다. } // 초기화 시점에서 유형 "문자열"을 "날짜"를 입력하도록 변환하십시오 @InitBinder public void initBinder (servletRequestDatabinder binder) {binder.registerCustomEditor (date.class, new CustomDateEditor (new SimpledateFormat ( "yyyy-mm-dd")); } // 매개 변수를 프론트 엔드 @requestmapping ( "/show") 공개 문자열 showperson (map <string, object> map) {person p = new Person (); map.put ( "p", p); P. 세트 (20); p.setName ( "jayjay"); "쇼"를 반환합니다. }프론트 데스크는 요청 도메인에서 "p"를 얻을 수 있습니다.
// ajax @requestmapping ( "/getperson")을 사용하여 매개 변수를 프론트 엔드로 전달합니다. 공개 void getperson (문자열 이름, printwriter pw) {pw.write ( "hello,"+name); } @requestmapping ( "/name") public String sayhello () {return "name"; }프론트 데스크는 다음 jQuery 코드로 호출합니다.
$ (function () {$ ( "#btn"). 클릭 (function () {$ .post ( "mvc/getperson", {이름 : $ ( "#name"). val ()}, function (data) {alert (data);});}); // @RequestMapping ( "/redirect") public string redirect () {return "Redirect : Hello"; }1. 2 개의 항아리 패키지를 가져와야합니다
2. SpringMVC 구성 파일을 추가하십시오
<!-업로드 설정-> <bean id = "multipartresolver"> <property name = "maxuploadsize"value = "102400000"> </property> </bean>
3. 방법 코드
@requestmapping (value = "/upload", method = requestmethod.post) public string upload (httpservletrequest req)는 예외 {multiparthttpservletrequest mreq = (multiparthttpservletrequest) req; multipartFile 파일 = mreq.getFile ( "file"); 문자열 filename = file.getoriginalFilename (); simpledateformat sdf = 새로운 simpledateformat ( "yyyymmddhhmmss"); fileoutputStream fos = 새 FileOutputStream (req.getSession (). getServletContext (). getRealPath ( "/")+"upload/"+sdf.format (new Date ())+filename.substring (filename.lastindexof ( '.')); fos.write (file.getBytes ()); fos.flush (); fos.close (); "안녕하세요"를 반환합니다. }4. 프론트 데스크 양식
<form action = "mvc/upload"method = "post"enctype = "multipart/form-data"> <input type = "file"name = "file"> <br> <input type = "value ="제출 "> </form>
@controller @requestmapping ( "/test") 공개 클래스 mvccontroller1 {@requestmapping (value = "/param") public String testrequestparam (@requestparam (value = "id") 정수 ID, @requestparam (value = "name") {system.out.println (id+"+이름); "/hello"를 반환합니다. }}1. RestController
@controller@requestmapping ( "/rest") 공개 클래스 restController {@requestmapping (value = "/user/{id}", method = requestmethod.get) public String get (@pathvariable ( "id") 정수 ID) {system.out.println ( "get"+id); "/hello"를 반환합니다. } @requestMapping (value = "/user/{id}", method = requestMethod.post) public String post (@PathVariable ( "id") 정수 ID) {System.out.println ( "post"+id); "/hello"를 반환합니다. } @requestmapping (value = "/user/{id}", method = requestMethod.put) public String put (@PathVariable ( "id") 정수 ID) {System.out.println ( "put"+id); "/hello"를 반환합니다. } @requestmapping (value = "/user/{id}", method = requestMethod.delete) public String delete (@pathvariable ( "id") 정수 ID) {System.out.println ( "delete"+id); "/hello"를 반환합니다. }}2. 양식 양식은 PUT 및 DELETE 요청을 보냅니다
Web.xml에서 구성하십시오
<!-hiddenhttpmethodfilter를 구성하고, 게시물 메소드를 넣거나 삭제하도록 포스트 메소드를 변환합니다-> <filter> <filter-name> hiddenhttpmethodfilter </filter-name> <filter-class> org.sprameframework.web.filter.hiddenhttpmethodfilter </filterclass>. <filter-name> hiddenhttpmethodfilter </filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
전경에서 다음 코드를 사용하여 요청을 생성 할 수 있습니다.
<form action = "REST/USER/1"메소드 = "post"> <입력 유형 = "hidden"name = "_ method"value = "put"> <입력 유형 = "value ="put "> </form> <form action ="rest/user/1 "method ="post "> <value ="post "> <comp action ="post/user/user/user/user/1 "method ="post ". value = "get"> </form> <form action = "rest/user/1"method = "post"> <input type = "hidden"name = "_ method"value = "delete"> <input type = "value ="delete "> </form>
1. 다음 JAR 패키지를 가져옵니다
2. 방법 코드
@controller @requestmapping ( "/json") public class jsoncontroller {@responsebody @requestmapping ( "/user") public user get () {user u = new user (); U.setID (1); U.setName ( "Jayjay"); u.setbirth (new date ()); u; }}1. 로컬 예외 처리 (컨트롤러)
@ExceptionHandler public model 및 exceptionHandler (예외 예 EX) {modelAndView mv = new ModelAndView ( "error"); mv.addoBject ( "예외", 예); System.out.println ( "TestExceptionHandler"); 리턴 MV; } @requestmapping ( "/error") public String error () {int i = 5/0; "안녕하세요"를 반환합니다. }2. 글로벌 예외 처리 (모든 컨트롤러)
@ControllerAdVicePublic 클래스 TestControllerAdvice {@ExceptionHandler public model and exception handler (예외) {modelAndView mv = new ModelAndView ( "error"); mv.addoBject ( "예외", 예); System.out.println ( "TestControllerAdvice에서"); 리턴 MV; }}3. 전 세계 예외를 다루는 또 다른 방법
SpringMVC 구성 파일로 구성하십시오
<!-단순한 구성 exceptionResolver-> <ean> <속성 이름 = "ExceptionMappings"> <props> <prop key = "java.lang.arithmeticexception"> error </prop> </props> </property> </bean>
오류는 오류 페이지입니다
1. MyInterceptor 클래스를 만들고 핸들러 인터셉터 인터페이스를 구현하십시오.
공개 클래스 MyInterceptor는 핸들러 인터셉터를 구현합니다 {@override public void attmpletion (httpservletrequest arg0, httpservletreponse arg1, 객체 Arg2, Exception Arg3)은 예외 {system.out.println ( "Aftercompletion"); } @override public void posthandle (httpservletrequest arg0, httpservletreponse arg1, object arg2, modelandview arg3)은 예외 {system.out.println ( "posthandle"); } @override public boolean prehandle (httpservletrequest arg0, httpservletreponse arg1, object arg2)은 예외 {system.out.println ( "prehandle")을 던졌습니다. 진실을 반환하십시오. }}2. SpringMVC 구성 파일로 구성됩니다
<!-인터셉터 설정-> <mvc : interceptors> <mvc : interceptor> <mvc : 매핑 경로 = "/mvc/**"/> <bean> </bean> gt; </mvc : 인터셉터> </mvc : 인터셉터>
3. 인터셉터 실행 순서
1. Hibernate-Validate에서 필요한 JAR 패키지를 가져옵니다
(선택되지 않음, 가져올 필요가 없습니다)
2. 엔티티 클래스 사용자를 쓰고 확인 주석을 추가하십시오
공개 클래스 사용자 {public int getId () {return id; } public void setid (int id) {this.id = id; } public String getName () {return name; } public void setName (문자열 이름) {this.name = 이름; } 공개 날짜 getBirth () {return birth; } public void setBirth (날짜 출생) {this.birth = birth; } @override public String toString () {return "user [id =" + id + ", name =" + name + ", birth =" + birth + "]; } private int id; @notempty 개인 문자열 이름; @past @datetimeformat (pattern = "yyyy-mm-dd") 개인 날짜 출생;}추신 : @past는 시간이 과거 가치 여야한다는 것을 의미합니다
3. JSP에서 SpringMVC 양식을 사용하십시오
<양식 : 양식 action = "form/add"method = "post"modelattribute = "user"> id : <form : <입력 경로 = "ID"/> <형식 : 오류 경로 = "id"/> <br> 이름 : <입력 경로 = "이름"/> <양식 : 오류 경로 = "이름"/> <br> 출생 : <입력 경로 = "형식"/> 경로 = "birth"/<form : 오류 경로 = "birth"/> <form : 오류 경로 = "birth"/> <입력 유형 = "제출"value = "제출"> </form : form>
추신 : 이름에 해당하는 경로
4. 컨트롤러의 코드
@controller@requestmapping ( "/form") public class formcontroller {@requestmapping (value = "/add", method = requestmethod.post) public String add (@valid user u, bindingResult br) {if (br.geterRorcount ()> 0) {return "Adduser"; } 반환 "Showuser"; } @requestmapping (value = "/add", method = requestmethod.get) public String add (map <string, object> map) {map.put ( "user", new user ()); "Adduser"를 반환합니다. }}추신:
1. ModelAttribute 속성이 JSP에서 사용되므로 요청 도메인에 "사용자"가 있어야합니다.
2.@유효한 수단 엔티티에 표시된 주석에 따라 매개 변수를 확인합니다.
3. 원본 페이지로 돌아가서 다시 발현하면 양식이 다시 발현됩니다.
5. 오류 메시지를 사용자 정의합니다
SRC 디렉토리에 locale.properties를 추가하십시오
notempty.user.name = name n't lempypast.user.birth = birth는 과거의 valuedeTimeformat.user.birth = 입력 형식이 잘못된 타임 피미치 chat.user.birth = 입력 형식이 잘못된 타임 피미치 chatch.user.id = 입력 형식이 잘못된 것입니다.
SpringMVC 구성 파일로 구성하십시오
<!-로케일 자원을 구성-> <bean id = "messageSource"> <property name = "basename"value = "locale"> </property> </bean>
6. 국제 디스플레이
SRC에서 Locale_ZH_CN.Properties를 추가하십시오
사용자 이름 = 계정 비밀번호 = 비밀번호입니다
locale.properties에 추가되었습니다
username = user namepassword = 비밀번호입니다
locale.jsp를 만듭니다
<body> <fmt : message key = "username"> </fmt : message> <fmt : message key = "password"> </fmt : message> </body>
SpringMVC로 구성됩니다
<!-JSP 페이지를 방문 할 수 있습니다-> <mvc : view-controller path = "/locale"view-name = "locale"/>
locale.jsp에 웹 -INF에서 직접 액세스하도록하십시오
마지막으로 Locale.jsp를 방문하여 브라우저 언어를 전환하고 계정 및 암호를 볼 수있는 언어도 전환되었습니다.
1. Test.springmvc.integrate 패키지를 생성하여 통합을 시연하고 다양한 유형을 만듭니다.
2. 사용자 엔티티 클래스
공개 클래스 사용자 {public int getId () {return id; } public void setid (int id) {this.id = id; } public String getName () {return name; } public void setName (문자열 이름) {this.name = 이름; } 공개 날짜 getBirth () {return birth; } public void setBirth (날짜 출생) {this.birth = birth; } @override public String toString () {return "user [id =" + id + ", name =" + name + ", birth =" + birth + "]; } private int id; @notempty 개인 문자열 이름; @past @datetimeformat (pattern = "yyyy-mm-dd") 개인 날짜 출생;}3. Userservice 클래스
@ComponentPublic class userErvice {public userervice () {system.out.println ( "Userservice 생성기 .../n/n/n/n/n/n/n/n/n/n"); } public void save () {system.out.println ( "save"); }}4. UserController
@controller @requestmapping ( "/integrate") public class userController {@autowired private userervice userervice; @requestmapping ( "/user") public string saveuser (@requestbody @modelattribute user u) {system.out.println (u); userervice.save (); "안녕하세요"를 반환합니다. }}5. 스프링 구성 파일
src 디렉토리에서 springioc configuration 파일 ApplicationContext.xml을 만듭니다
<? xml 버전 = "1.0"alcoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xmlns : xsi = "http://ww.w.w3.org/2001/xmlschema-instance" xsi : schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "xmlns : util ="http://www.springframework.org/schema/util " xmlns : p = "http://www.springframework.org/schema/p"xmlns : context = "http://www.springframework.org/schema/context"> <context : component-scan base-package = "test.springmvc.integrate"> 유형 = "주석"expression = "org.springframework.steretype.controller"/> <context : excludefilter type = "주석"expression = "org.springframework.bind.annotation.controllerAdvice"/> </context : component-scan> </bans>
web.xml에 구성을 추가하십시오
<!-springioc-> <layer> <layer-class> org.springframework.web.web.context.contextloaderListener </hareser-class> <coundxt-param> <param-name> ContextConfiglocation </param-name> <param-name> classpar : ApplicationMl </conte-valxtorcont.xml >xmlt.xmlt.xmlt.xmlt.xmlt.xmlt.xmlt.xmlt.xmlt.xmlt.xmlt.xmlt.xmlt.xml x.
6. SpringMVC에서 SpringMVC 및 SpringIOC가 동일한 개체의 중첩 관리를 방지하기 위해 SpringMVC에서 일부 구성을 만듭니다.
<!-패키지 및 하위 패키지 스캔-> <문맥 : Component-Scan Base-Package = "Test.Springmvc.integrate"> <Context : include filter type = "Annotation"expression = "org.springframework.steretype.controller"/> 컨텍스트 : filter type = "Annotation" expression = "org.springframework.web.bind.annotation.controlleradvice"/> </context : component-scan>
1. SpringMVC는 방법을 기반으로 개발되었으며 Struts2는 클래스를 기반으로 개발됩니다. SpringMVC는 컨트롤러의 URL과 메소드를 매핑합니다. 매핑이 성공한 후 SpringMVC는 메소드 만 포함하는 핸들러 객체를 생성합니다. 메소드 실행이 끝나고 공식 매개 변수 데이터가 파괴됩니다. SpringMVC의 컨트롤러 개발은 웹 서비스 개발과 유사합니다.
2. SpringMVC는 싱글 톤 개발을 수행 할 수 있으며 싱글 톤 개발을 사용하는 것이 좋습니다. struts2는 클래스의 멤버 변수를 통해 매개 변수를 수신합니다. 싱글 톤을 사용할 수 없으며 여러 사례 만 사용할 수 있습니다.
3. 실제 테스트 후 Struts2는 struts 태그를 사용하기 때문에 느립니다. Struts를 사용하는 경우 JSTL을 사용하는 것이 좋습니다.