Spring MVC 양식 처리 예제 다음 예제는 Spring의 Web MVC 프레임 워크를 사용하여 HTML 양식을 사용하는 간단한 웹 기반 응용 프로그램을 작성하는 방법을 보여줍니다.
테스트 프로젝트 구성
(1) 새로운 Java 웹 프로젝트를 만들고 SpringMVC 프로젝트에 필요한 몇 가지 JAR 패키지를 소개합니다. 필요한 프로젝트 구조 및 JAR 패키지는 다음과 같습니다.
①web.xml :
<web-app xmlns = "http://xmlns.jcp.org/xml/ns/javaee"xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance" xsi : schemalocation = "http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_3_3_1.xsd"3.1 "> <servlet> <servlet-name> springmvc </servletmvc </servlet-name> <Servlet-class> org.springframework.web.servlet.dispatcherServlet </servlet-class> <load-on-startup> 1 </load-on-startup> </servlet> <servlet-mapping> <servlet-name> springmvc </servlet-name> <url-fattern>* <filter> <filter-name> 캐릭터 encodingfilter </filter-name> <filter-class> org.springframework.web.filter.characterencodingfilter </filter-class> <init-param> <param-name> alcoding </param-name> <param-value </param-value> <filter-mapping> <filter-name> char
다음은 .html로 끝나는 URL 접미사를 가로 채고 처리하는 SpringMVC입니다.
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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/sprging-4.0.xtext-4 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd "> <context : component-scan base-package ="cn.zifangky <!-bean에 정의 된 주석을 활성화-> <mvc : 주석 구동/> <ean> <속성 이름 = "prefix"value = "/web-inf/"/> <property name = "접미사"value = ". jsp"/> </bean> </beans>
위의 구성 파일에서 <context : annotation-config />는 Bean에 정의 된 일부 주석을 활성화하고 <mvc : annotation-driven />은 SpringMVC의 일부 기본 구성을 활성화합니다. 구성 파일의 끝에서 논리보기와 실제보기 사이의 해당도 정의됩니다. 한마디로 위에서 정의 된 경로 접두사 및 접미사는 반환 된 논리보기에 제공됩니다. 이것이 실제 관점의 실제 경로입니다.
2. SpringMVC를 사용하여 양식을 처리하십시오
(1) 공식적으로 시작하기 전에 모델 및 열거 클래스를 만듭니다.
① 엔터티 사용자 :
패키지 cn.zifangsky.model; import java.time.localdate; import org.springframework.format.annotation.datetimeformat; public class user {private string name; 개인 문자열 비밀번호; 개인 문자열 작업; @dateTimeformat (Pattern = "yyyy-mm-dd") private localdate birthdate; 개인 성별 성별; 개인 문자열 국가; 개인 부울 흡연; 공개 문자열 getName () {return name; } public void setName (문자열 이름) {this.name = 이름; } public String getPassword () {return password; } public void setpassword (문자열 비밀번호) {this.password = password; } public String getJob () {return job; } public void setJob (문자열 작업) {this.job = job; } public LocalDate getBirthDate () {return irthdate; } public void setBirthDate (LocalDate BirthDate) {this.birthdate = birthdate; } 공개 성별 getgender () {return gender; } public void setgender (성별 성별) {this.gender = 성별; } public String getCountry () {return country; } public void setCountry (String Country) {this.country = 국가; } public boolean issmoking () {반환 흡연; } public void setsmoking (부울 흡연) {this.smoking = 흡연; }} ② "성별"을 나타내는 열거 계급 성별 :
패키지 CN.ZIFANGSKY.MODEL; 공개 열거 젠더 {남성, 여성;} 다음은 프로그램 실행 프로세스에 따라 SpringMVC의 양식 처리, 즉 전경 양식 작성> 컨트롤러 처리> 처리 결과보기 페이지에 따라 SpringMVC의 양식 처리를 간략하게 설명합니다.
(2) 테스트 프로젝트의 홈페이지 및 양식 양식 페이지 :
Home Page Index.jsp :
<% response.sendRedirect ( "form.html"); %>
여기의 홈페이지는 매우 간단하며 "form.html"으로 리디렉션되지만 Web.xml의 이전 구성을 통해 SpringMVC는이 요청을 특정 컨트롤러로 전송하여 처리를 위해 직접 양식 페이지로 직접 전송합니다. 컨트롤러의 특정 처리 로직은 아래에서 설명합니다.
form 양식 페이지 userform.jsp :
<%@ page language = "java"contenttype = "text/html; charset = utf-8"pageencoding = "utf-8"%> <%@ taglib uri = "http://www.springframework.org/tags/form"prefix = "mvc"%> <head> <meta http-equiv = "content-type"content = "text/html; charset = utf-8"> <title> 스프링 MVC 양식 처리 </title> </head> <body> <h2> 사용자 등록 </h2> <mvc : form modelattiption = "user"action = "result.html"> <td> <td> <td> <td> <td> Path = "Name"> 이름 : </mvc : label> </td> <td> <mvc : 입력 경로 = "name"/> </td> </tr> <td> <mvc : label path = "password"> 암호 : </mvc : label> </td> <td> <mvc : password "/td> </td> </td> </td> <td> <mvc : label path = "job"> work : </mvc : label> </td> <td> <mvc : textarea path = "job"/> </td> </tr> <td> <td> <mvc : label path = "birthdate"> 생일 : </mvc : label> </td> <mvc : input path : input path : input path : /> </td> </tr> <td> <td> <mvc : 레이블 경로 = "성별"> 성별 : </mvc : </mvc : </td> <td> <mvc : radiobuttons path = "젠더"항목 = "$ {genders}"/> </td> <td> <mvc : ladable Path = "Country"> Residence : </mvc : label> </td> <td> <mvc : select path = "country"items = "$ {country}"/> </td> </tr> <td> <mvc : label path = "흡연"> </tr> <tr> <td colspan = "2"> <input type = "제출"value = "제출"/> </td> </tr> </tr> </table> </mvc : form> </body> </html> 이 페이지를 Web-Inf 디렉토리에 넣으므로 URL을 통해이 파일에 직접 액세스 할 수 없습니다. 위에서 정의 된 "form.html"은 처리를 위해 컨트롤러로 전송 되고이보기 페이지를 표시해야합니다. 이것의 목적은 일부 개인 페이지가 승인없이 다른 개인 페이지에 액세스하는 것을 방지하는 것입니다. 위 파일에서는 다음과 같이하십시오.
(3) 비즈니스 로직 처리를위한 컨트롤러 클래스 usercontroller.java :
패키지 cn.zifangsky.controller; import org.springframework.stereotype.controller; import org.springframework.beb.bind.annotation.modelattribute; import org.springframework.bind.annotation.requestmapping; import org.springframework.web.servlet.modellelandview; cn.zifangsky.model.user; @controllerpublic class usercontroller {private static final string [] 국가 = { "중국", "일본", "북한", "미국"}; @requestmapping (value = "/form.html") public modelandView user () {modelAndView ModelAndView = new ModelAndView ( "userform"); ModelAndView.AdDoBject ( "사용자", new user ()); ModelAndView.AdDoBject ( "젠더", gender.values ()); ModelAndView.AddObject ( "국가", 국가); Return ModelandView; } @requestmapping (value = "/result.html") public model andview processUser (@ModelAttribute (value = "user") user u) {modelAndView modelAndView = new ModelAndView ( "userResult"); modelandview.addoBject ( "u", u); Return ModelandView; }} 두 가지 방법이 위에서 정의되어 있음을 알 수 있으며 그 기능은 "form.html"요청에 대한 실제 양식으로 전송하고 양식 양식을 처리하는 것입니다. 양식을 처리 할 때 @ModelAttribute 주석을 통해 사용자 유형 "U"를 받았는데, 이는 먼저 채워진 양식이며 다음은 양식의 표시입니다.
(4) 테스트 :
gorm 형식으로 채워서 :
resounds 결과는 다음과 같습니다.
userresult.jsp 페이지 :
<%@ page language = "java"contmenttype = "text/html; charset = utf-8"pageencoding = "utf-8"%> <%@ taglib uri = "http://www.springframework.org/tags/form"prefix = "mvc"%> html publ "-// w3c" html 4.01 전환 // en ""http://www.w3.org/tr/html4/loose.dtd"> html> http-equiv = "content-type"content = "text/html; <h2> 레지스터 결과 </h2> <table> <ttr> <td> 이름 : </td> <td> $ {u.name} </td> </td> <td> <td> 암호 : </td> <td> $ {u.password} </td> </tr> <td> Work : </td> <td> $ {u.job} </td> </td> <td> <td> 생일 : </td> <td> $ {u.birthdate} </td> </tr> <t> <td> 성별 : </td> <td> $ {u.gender} </td> <td> $ {u.country} </td> </td> </td> <td> 흡연 : </td> <td> $ {u.smoking} </td> </tr> </tab> </table> </body> </html>위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.