Spring MVC 1 File new Dynamic Web Project
Spring MVC 프로젝트 생성 1. File > new > Dynamic Web Project 2. Project name : Login 4 mvc 입력
Spring MVC의 환경 구성 1. http: //www. springsource. org/download/community/에서 Spring Framework의 다운 로드 2. 압축을 풀고 dist 폴더를 프로젝트 lib 폴더에 import 3. 기타 의존관계에 있는 필요한 library 파일 import
Spring MVC 프로젝트 생성 Web project를 Spring Project로 전환 1. 오른쪽 클릭>Spring Tools > Add Spring Project Nature
사용자 로그인 구성 Error 로그인화면 로그 인 사용자별 메인화면 로그아웃 View Controller Login. Form. Controll er Model login. Success. jsp Login. Validator User. Servise User. Dao login. jsp Data. Source User. Dt o
로그인 MVC 처리흐름 http: //Spring. User/login. html Handler. Mapping 컨트롤러 선택 요청 2 3 Dispa tcher Servlet 처리위임 Model. And. View 5 뷰 선택요청 View. Resolver Model. And. View 6 Login. Form. Controller 결과물 출력 <form action=“login. html”> login. jsp login. Success. jsp Controller 4 Model User. Servise User. Dao Model Data. Source
Spring MVC의 환경 구성 Ioc 컨테이너 : 웹 애플리케이션 컨텍스트 구성 Webroot의 /WEB-INF/web. xml 파일에 설정 root 애플리케이션 컨텍스트와 서블릿 애플리케이션 컨텍스트 설정 web. xml Io. C web-application 컨테이너 Context. Loader. Listener Dao data. Source Message. Sourc e application. Context*. xml [servlet-name]-servlet. xml
로그인 MVC 처리흐름 http: //Spring. User/login. html Handler. Mapping 컨트롤러 선택 요청 2 3 Dispa tcher Servlet 처리위임 Model. And. View 5 뷰 선택요청 View. Resolver Model. And. View 6 Login. Form. Controller 결과물 출력 <form action=“login. html”> login. jsp login. Success. jsp Controller 4 Model User. Servise User. Dao Model Data. Source jdbc. Template
회원관리table 생성 CREATE TABLE `member_tbl` ( `no` int(8) NOT NULL AUTO_INCREMENT, `id` varchar(10) NOT NULL, `pass` varchar(10) NOT NULL, `name` varchar(20) NOT NULL, `jumin` char(13) NOT NULL, `zip` char(7) DEFAULT NULL, `addr 1` varchar(100) DEFAULT NULL, `addr 2` varchar(50) DEFAULT NULL, `phone` varchar(20) DEFAULT NULL, `email` varchar(30) DEFAULT NULL, PRIMARY KEY (`no`) ) ENGINE=Inno. DB AUTO_INCREMENT=1 DEFAULT CHARSET=utf 8;
Dto (Data Transfer : Value) 객체 생성 1. 오른쪽 클릭>new >class 2. user. logic 입력 3. User. Dto 입력 User. Dto 4 5 7 6
전달 객체 gatter & setter 생성 1. 입력 User. Dto. java
모델 객체 gatter & setter 생성 4 1. 오른쪽클릭>Source>Generate Getter&Setter 2 5 3
Dao Interface 생성 2. 입력 1. src>우클릭>new >Inteface 3
Dao Interface 생성 1. 메서드 이름과 매개변수입력 User. Dto. java (User. Dto user );
Dao 구현 클래스 생성 2. 입력 1. src>user. dao>우클릭>new >class 6. Jdbc. Dao. Support 상속 3 4 7 5
Dao구현 클래스생성 User. Dto. java
SQL 파라미터 바인딩 방법 위치 파라미터 치환자 public void delete(String user. Id, String password) { template. update("delete from member_tbl where id=? AND pass=? ", user. Id, password ); } 이름 파라미터 치환자 INSQL=“Insert into member(id, name, pass) values ( : id, : name, : pass)” public void insert(User. Dto user) { Sql. Parameter. Source parameter. Source = new Bean. Property. Sql. Parameter. Source(user); template. update(INSQL, parameter. Source); id nam e pass jjin 김영 1234 jumi n addr } Sql. Parameter. Source 클래스( SQL User. Dto ) DB테이블의 필드이름과 User. Dto 객체의 속성 이름을 매핑(이름이 같은 필드만) Row. Mapper 클래스( Rs User. Dto ) Result. Set에서 값을 가져와 원하는 타입으로 매핑할 때 사용
Sql. Parameter. Source와 Row. Mapper INSQL=“Insert into member(id, pass, name) values ( : id, : pass, : name)” SQL Sql. Parameter. Source Dto id pass nam e jumi n addr jjin 1234 이현 상 … …. Row. Mapper Rs
SQL 작성 위치 파라메터 private static final String GETUSER_IDPASS = "SELECT * FROM member_tbl WHERE id = ? AND pass = ? "; private static final String GETUSER_ID = "SELECT * FROM member_tbl WHERE id = ? "; private static final String GETID = "select id from member_tbl where name=? and jumin=? "; private static final String GETPASS = "select pass from member_tbl where id=? and jumin=? "; 네임 파라메터 private static final String INSERT = "INSERT INTO member_tbl (id, pass, name, jumin, zip, addr 1, addr 2, phone, email)" + " VALUES(: Id, : pass, : name, : jumin, : zip, : addr 1, : addr 2, : phone, : email)"; private static final String UPDATE = "UPDATE member_tbl SET pass = : pass, zip = : zip, addr 1 = : addr 1, addr 2 = : addr 2, phone = : phone, email = : email WHERE id = : id";
Spring JDBC를 위한 jdbc. Template 클래스 Connection을 구하고, try-catch-finally로 자원을 관리하는 등 예외 처리 의 중복된 코드를 제거. JDBC를 위한 세 개의 템플릿 클래스 Jdbc. Template Jdbc. Dao. Support 기본적인 JDBC 템플릿 클래스. JDBC를 이용해서 데이터에 대한 접근을 제공. Named. Parameterjdbc. Template Simplejdbc. Template Prepared. Statement에서 위치 기반의 파라미터가 아닌 이름을 가진 파라미 터를 사용할 수 있도록 지원하는 템플릿 클래스. Jdbc. Template기능을 향상 - 위치와 이름 기반 파라메터 사용 Jdbc. Template 생성과 Data. Source 주입 Jdbc. Dao. Support 클래스의 get. Jdbc. Template(). query() 로 대체 private jdbc. Template template; public void set. Data. Source(Data. Source data. Source) { this. template = new jdbc. Template(data. Source); }
검색코드의 구현 위치 파라메터 private static final String GETUSER_IDPASS = "SELECT * FROM member_tbl WHERE id = ? AND pass = ? "; SQL User. Dto @Override Rs public User. Dto find. User(String user. Id, String password) {sqlparameter. Source Row. Mapper<User. Dto> mapper = new Bean. Property. Row. Mapper<User. Dto>(User. Dto. class); return get. Jdbc. Template(). query. For. Object(GETUSER_IDPASS, mapper, user. Id, password); } private static final String GETUSER_ID = "SELECT * FROM member_tbl WHERE id = ? "; public User. Dto find. User(String user. Id) { Row. Mapper<User. Dto> mapper = new Bean. Property. Row. Mapper<User. Dto>(User. Dto. class); return get. Jdbc. Template(). query. For. Object(GETUSER_ID, mapper, user. Id); } private static final String GETID = "select id from member_tbl where name=? and jumin=? "; public User. Dto find. Id(String me_name, String me_jumin) { Row. Mapper<User. Dto> mapper = new Bean. Property. Row. Mapper<User. Dto>(User. Dto. class); return get. Jdbc. Template(). query. For. Object(GETID, mapper, me_name, me_jumin); } private static final String GETPASS = "select pass from member_tbl where id=? and jumin=? "; public User. Dto find. Pass(String user. Id, String me_jumin) { Row. Mapper<User. Dto> mapper = new Bean. Property. Row. Mapper<User. Dto>(User. Dto. class); return get. Jdbc. Template(). query. For. Object(GETPASS, mapper, user. Id, me_jumin); }
생성, 수정, 삭제 코드 구현 네임 파라메터 private static final String UPDATE = "UPDATE member_tbl SET pass = : pass, zip = : zip, addr 1 = : addr 1, addr 2 = : addr 2, phone = : phone, email = : email WHERE id = : id"; public void update(User. Dto user) { Sql. Parameter. Source parameter. Source = new Bean. Property. Sql. Parameter. Source(user); get. Jdbc. Template(). update(User. Dao. Impl. UPDATE, parameter. Source); SQL User. Dto Rs } Sql. Parameter. Source private static final String INSERT = "INSERT INTO member_tbl (id, pass, name, jumin, zip, addr 1, addr 2, Row. Mapper phone, email)“ + " VALUES( : Id, : pass, : name, : jumin, : zip, : addr 1, : addr 2, : phone, : email )"; public void insert(User. Dto user) { Sql. Parameter. Source parameter. Source = new Bean. Property. Sql. Parameter. Source(user); get. Jdbc. Template(). update(User. Dao. Impl. INSERT, parameter. Source); } public void delete(String user. Id, String password) { get. Jdbc. Template(). . update("delete from member_tbl where id = ? AND pass = ? ", user. Id, password ); } 위치 파라메터 Dto 클래스를 매개변수로 Sql. Parameter. Source 클래스 객체를 생성하고, template. update 메서 드를 실행할 때 Dto 클래스 변수와 쿼리안의 (: 변수) 이름 같으면 DTO 의 내용이 SQL 파라메터에 자동 으로 매핑된다.
Sql. Parameter. Source와 Row. Mapper Dto 폼 Sql. Parameter. Source SQL Row. Mapper Rs
Service (Business)클래스 작성 <<Interface>> DAO User. Dao <<Interface>> Service User. Service 사용 Controlle r 사용 Business Logic Object Service Logic User. Service. Impl Object DAO Object User. Dao. Impl 획득 생성 Data Transfer public class User. Service. Impl implements User. Service { Object Value Object private User. Dao user. Dao; public void set. User. Dao(User. Dao user. Dao. Impl) { this. user. Dao = user. Dao. Impl; } } DI Data. Sour ce: Simplejdbc. Templa 직접생성te
Business interface 생성 4. 입력 1. src>user. logic >우클릭>new >Interface 2 5 3
Business interface 생성 2. 입력
Business 구현 클래스 작성 1. src>user. logic >우클릭>new >Interface 2. User. Service. Impl 입 력 4 3 5
Dao 구현객체 주입 <<Interface>> User. Service 사용 Controlle r <<Interface>> User. DAO 사용 Business Logic Object Service Logic User. Service. Impl Object DAO Object User. DAOImpl DI Data. Sour ce: jdbc. Template 직접생성 public class User. Service. Impl implements User. Service { private User. Dao user. Dao; 스프링 root 애플리케이션 컨텍스 public void set. User. Dao(User. Dao user. Dao. Impl) { this. user. Dao = user. Dao. Impl; } }
View 와 Controller 로그인 사용자별 메인화면 로그아웃 Login. Form. Controll er Model Login. Validator User. Servise User. Dao login. jsp Data. Source login. Success. jsp
View 1. jsp>우클릭>new >JSP File 2. login. jsp 입력 3
JSTL 정리 파일 작성 (jsp_header. jsp) JSTL과 style 을 모든 뷰에서 사용할 수있도록 별도의 파일에 저장하고 <inclkude> <%@ page session="false"%> <%@ taglib prefix="c" uri="http: //java. sun. com/jsp/jstl/core"%> <%@ taglib prefix="spring" uri="http: //www. springframework. org/tags"%> <%@ taglib prefix="form" uri="http: //www. springframework. org/tags/form"%> <%@ taglib prefix="f" uri="http: //java. sun. com/jsp/jstl/fmt" %> <link rel="stylesheet" type="text/css" href="css/loginstyle. css"> css 폴더생성 loginstyle. css Login_bg. gif 파일 copy
loginstyle. css 폴더생성 a: link{font-family: ""; color: black; text-decoration: none; } Login_bg. gif 파일 a: visited{font-family: ""; color: black; text-decoration: none; } copy a: hover{font-family: ""; color: black; text-decoration: underline; } h 4 {color: blue; font-family: 굴림; font-size: 14 px; font-weight: bold; } fieldset { border: 5 px solid #ccc; padding: 0 5 px; } #login. Area { margin-left: 5 px; width: 250 px; } #thisform { font-family: Georgia, serif; font-size: 11 px; color: #999; } #thisform label { font-family: 굴림, sans-serif; font-weight: bold; color: #660000; } #thisform p { margin: 5 px; } #ullog { list-style-type: none; margin-left: 5 px; padding: 0; font-family: 굴림: font-size: 12 px; } #lilog { display: inline; margin: 0 px 0 px; padding: 0 0; border: 1; font-family: 굴림; fontsize: 12 px; } #lilogb { display: inline; margin: 0 px 0 px; padding: 0 0; border: 1; font-family: 굴림; fontsize: 12 px; } * { padding: 0; margin: 0; }. id_blur { background: transparent url("login_bg. gif") top left}. id_focus { background: #ffffe 0 ; color: #003300 }. pw_blur { background: transparent url("login_bg. gif") bottom left}. pw_focus { background: #ffffe 0 ; color: #003300 }. clear { clear: both; background: none; } span. field. Error { color: red; font-size: 10 px; font-family: arial, sans-serif;
View (login. jsp) 생성 login. jsp_header. jsp
Login. jsp <body> <div id="login. Area" class="clear"> 또는 user. Dto <form: form model. Attribute="user" method="post" action="login. html"> <fieldset> <legend><h 4>로그인</h 4></legend> <spring: has. Bind. Errors name="user"> <span class="field. Error"> <c: for. Each var="err" items="${errors. global. Errors}" > <spring: message code="${err. code}" /> </c: for. Each> </span> </spring: has. Bind. Errors> 다음 페이지 내용 삽입 … <p><ul id="ullog"> <li id="lilogb"><a href="/Login 4 mvc/user. Entry. html">회원가입</a></li>| <li id="lilog"><a href="/Login 4 mvc/find. Id_form. html">아이디/</a> <a href="/Login 4 mvc/find. Pass_form. html" class="pwd">비밀번호 찾기 </a></li> </ul></p> </fieldset> </form: form> </div> </body>
Login. jsp <p><form: input path="id" size='12' maxlength='15' title="아이디 입력" onfocus="this. class. Name='id_focus'" on. Blur="if ( this. value == '' ) { this. class. Name='id_blur' }" class='id_blur' /></p> <p><span class="field. Error"> <form: errors path="id" /> </span> </p> <p><form: password path="pass" size='13' maxlength='15' title="비밀번호 입력" on. Focus="this. class. Name='pw_focus'" on. Blur="if ( this. value == '' ) { this. class. Name='pw_blur' }" class='pw_blur' /> <input type="submit" value="로그인" tabindex="4" /></p> <p><span class="field. Error"> <form: errors path="pass" /></span></p> 바인딩 된 속성 아니면 error
로그인 성공화면(login. Success. jsp) <%@ page language="java" content. Type="text/html; charset=UTF-8" page. Encoding="UTF-8"%> <%@ include file="/WEB-INF/jsp_header. jsp" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>로그인 성공화면</title> </head> <body> <div align="center" class="body"> <h 2>로그인화면</h 2> 환영합니다, ${login. User. name}씨! <a href="/Login 4 mvc/user. Edit. html? user. Id=${login. User. id}"><회원정보 수정></a> </div> </body> </html>
View 와 Controller 로그인 사용자별 메인화면 로그아웃 http: //Login 4 mvc/login. html 1 2 Login. Form. Controll er 3 5 4 login. Success. jsp 4 Login. Validator User. Servise User. Dao Data. Source login. jsp Model
Controller 설계 http: //Login 4 mvc/login. html 컨트롤러 선택 요청 Handler. Mapping 2 Dispa tcher Servlet login. Validator 3 처리위임 Login. Form. Controller Model. And. View Controller 뷰 선택요청 method="post“ action="login. html Model. And. View 6 결과물 출력 View. Resolver Use. Service User. Dao Data. Source jdbc. Template View (*. jsp) Controller
유효성체크(Validation 작성) 1. src>우클릭>new>class> 입력 3. login. jsp 입력 2 5 4
Validator package user. utils; public class Login. Validator implements Validator { @Override public boolean supports(Class<? > clazz) { return User. Dto. class. is. Assignable. From(clazz); } @Override public void validate( Object command, Errors errors) { User. Dto user = (User. Dto) command; if (!String. Utils. has. Length( user. get. Id() )) { errors. reject. Value("id", "error. required"); } if (!String. Utils. has. Length( user. get. Pass() )) { errors. reject. Value("pass", "error. required"); } if (errors. has. Errors()) { errors. reject("error. input. user"); } } }
Controller에서 Validator를 이용한 검증 public class Login. Controller { private Validator login. Validator; public void set. Login. Validator(Validator login. Validator) { this. login. Validator = login. Validator; } } @Request. Mapping(method = Request. Method. POST) public Model. And. View on. Submit(@Model. Attribute User user, Binding. Result binding. Result) { this. login. Validator. validate(user, binding. Result); Model. And. View model. And. View = new Model. And. View(); if (binding. Result. has. Errors()) { model. And. View. get. Model(). put. All( binding. Result. get. Model() ); return model. And. View; } try { DB 검색 …. . return model. And. View; } catch (Empty. Result. Data. Access. Exception e) { binding. Result. reject("error. login. user"); model. And. View. get. Model(). put. All( binding. Result. get. Model() ); return model. And. View; } }
메시지소스 생성 application. Context. xml <bean id="message. Source“ class="org. springframework. context. support. Resource. Bundle. Message. Source"> <property name="basenames“ value=“messages” /> </bean> View 에서 출력 <spring: has. Bind. Errors name="user"> <span class="field. Error"> <c: for. Each var="error" items="${errors. global. Errors}" > <spring: message code="${error. code}" /> </c: for. Each> </span> </spring: has. Bind. Errors> … <span class="field. Error"> <form: errors path="pass" /> </span>
컨트롤러 객체의 DI package user. controller; @Controller public class Login. Form. Controller { private User. Service user. Service; private Validator login. Validator; public void set. User. Service(User. Service user. Service) { this. user. Service = user. Service; } public void set. Login. Validator(Validator login. Validator) { this. login. Validator = login. Validator; } @Model. Attribute("user") public User. Dto set. Up. Form() { return new User. Dto(); } @Request. Mapping(method = Request. Method. GET) public String to. Login. View() { return "login"; } … 추가
컨트롤러 @Request. Mapping(method = Request. Method. POST) public Model. And. View on. Submit( @Model. Attribute("user") User. Dto user, Binding. Result binding. Result) { 1. 폼에서 데이터를 받아서 Dto에 저장 2. Dto 객체를 검증 this. login. Validator. validate(user, binding. Result); Model. And. View model. And. View = new Model. And. View(); if (binding. Result. has. Errors()) { model. And. View. get. Model(). put. All(binding. Result. get. Model()); 3. Error가 있으면 폼에 에러내용 전달 return model. And. View; 4. 없으면 사용자 검색 서비스 실행 } try { user. Dao. Impl Datasource User. Dto login. User = this. user. Service. get. User(user. get. Id(), user. get. Pass()); model. And. View. set. View. Name("login. Success"); model. And. View. add. Object("login. User", login. User); return model. And. View; 5. 사용자검색 성공하면 표시할 view 선정 6. View에 Dto 전달 7. 일치하는 ID 나 패스워드가 없는경우 8. 폼에 에러내용 전달 } catch (Empty. Result. Data. Access. Exception e) { binding. Result. reject("error. login. user"); model. And. View. get. Model(). put. All(binding. Result. get. Model()); return model. And. View; } } }
Context. Loader. Listener 설정화일 Default Bean. Factory - /WEB-INF/application. Context. xml Root Web. Application. Context에서 필요한 객체 bean을 정의한다. 클래스를 이용하여 다음 객체를 생성 data. Source - 데이터베이스 연결 정보를 관리하는 객체 use. Dao, user. Service – model 구성을 위한 객체 login. Validator – 입력폼의 정보를 검증하기 위한 객체 message. Source – 오류메세지를 관리하기 위한 객체
application. Context. xml 1. 우클릭>new>other 4. 입력 2 5 3
application. Context. xml <? xml version="1. 0" encoding="UTF-8"? > <beans xmlns …. <!-- Data Source --> <bean id="data. Source" class="org. springframework. jdbc. datasource. Driver. Manager. Data. Source" > <property name="driver. Class. Name"> <value>oracle. jdbc. driver. Oracle. Driver</value> </property> <property name="url"> <value>jdbc: oracle: thin: @168. 126. 146. 33: 1521: orcl</value> </property> <property name="username"> <value>jjin</value> </property> <property name="password"> <value>jjinpang</value> </property> </bean> … 다음 페이지 삽입 </beans>
객체생성과 관계설정(DI) <!-- User. Dao --> 의존관계정보 주입 <bean id="user. Dao" class="user. dao. User. Dao. Impl"> <property name="data. Source"> public void set. Data. Source(Data. Source data. Sourc <ref bean="data. Source" /> </property> this. template = new Jdbc. Template(data. Source </bean> } <!-- user. Service --> 의존관계정보 주입 <bean id="user. Service" class="user. logic. User. Service. Impl"> <property name="user. Dao"> public void set. User. Dao(User. Dao user. Dao) { <ref bean="user. Dao" /> </property> this. user. Dao = user. Dao; </bean> } <!-- Validator --> <bean id="login. Validator" class="user. utils. Login. Validator" /> <!-- Message. Source --> <bean id="message. Source" class="org. springframework. context. support. Resource. Bundle. Message. Source"> <property name="basenames"> <list><value>messages</value></list> </property> </bean>
Io. C 컨테이너 web. xml Context. Loader. Listener Root Web. Application. Context data. Sourc e user. Dao user. Servic e http: //Login 4 mvc/login. html Login. Validato r Message. Sour ce Handler. Mapping Login. Form. Controll er application. Context*. x ml View. Resolver [servlet-name]servlet. xml login. js p logsuccec. j sp
View 와 Controller 로그인 사용자별 메인화면 로그아웃 http: //Login 4 mvc/login. html 1 2 Login. Form. Controll er 3 4 Login. Validator 4 User. Servise login. jsp 5 login. Success. jsp Model
Dispatcher. Servlet 설정화일 Spring. User-servlet. xml 1. 우클릭>new>other 4. 입력 2 3 5
Dispatcher. Servlet 설정화일 (Login 4 mvcservlet. xml) <? xml version="1. 0" encoding="UTF-8"? > <beans xmlns="http: //www. springframework. org/schema/beans" xmlns: xsi="http: //www. w 3. org/2001/XMLSchema-instance" xmlns: p="http: //www. springframework. org/schema/p" xsi: schema. Location="http: //www. springframework. org/schema/beans/spring-beans-3. 0. xsd"> <!-- Handler. Mapping --> <bean id="handler. Mapping" class="org. springframework. web. servlet. handler. Simple. Url. Handler. Mapping"> <property name="mappings"> Login. html 요청이 입력되면 <props> login. Form. Controller 로 연결 <prop key="/login. html">login. Form. Controller</prop> </props> </property> </bean> … 추가 </beans>
Dispatcher. Servlet 설정화일 (Login 4 mvcservlet. xml) login. Form. Controller 객체 생 성 <!-- Controller --> 2개의 객체를 인수로 전달 <bean id="login. Form. Controller" class="user. controller. Login. Form. Controller" p: user. Service-ref="user. Service" p: login. Validator-ref="login. Validator"> </bean> login WEB-INF/jsp/login. jsp <!-- View. Resolver --> <bean id="internal. Resource. View. Resolver”class="org. springframework. web. servlet. view. Internal. Resource. View. Reso lver"> <property name="view. Class"> <value>org. springframework. web. servlet. view. Jstl. View</value> Handler. Mapping </property> <property name="prefix"> Login. Form. Control ler <value>WEB-INF/jsp/</value> </property> View. Resolver <property name="suffix"> <value>. jsp</value> logsuccec. j </property> login. jsp </bean> sp
실행 login. html
사용자 정보 수정 로그인화면 로그아웃 사용자별 메인화면 정보수정 사용자정보 수정화면 확인 http: //localhost: 8080/Login 4 mvc/user. Edit. html? user. Id=jjin 1 2 User. Edit. Form. Contr oller 3 4 User. Edit. Validator 4 user. Edit. jsp User. Servise 5 사용자정보 보기화면
로그인 성공화면(login. Success. jsp) <%@ page language="java" content. Type="text/html; charset=UTF-8" page. Encoding="UTF-8"%> <%@ include file="/WEB-INF/jsp_header. jsp" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>로그인 성공화면</title> </head> <body> <div align="center" class="body"> <h 2>로그인화면</h 2> 환영합니다, ${login. User. name}씨! <a href="/Login 4 mvc/user. Edit. html? user. Id=${login. User. id}"><회원정보 수정></a> </div> </body> </html>
Validator 작성 User. Edit. Validator. java User. Dto user = (User. Dto) command;
User. Edit. Form. Controller 작성 package user. controller; @Controller public class User. Edit. Form. Controller { private User. Service user. Service; private User. Edit. Validator user. Edit. Validator; private Message. Source message. Source; public void set. Message. Source(Message. Source message. Source) { this. message. Source = message. Source; } public void set. User. Service(User. Service user. Service) { this. user. Service = user. Service; } public void set. User. Edit. Validator(User. Edit. Validator user. Edit. Validator) { this. user. Edit. Validator = user. Edit. Validator; }
User. Edit. Form. Controller 작성 @Model. Attribute public User set. Up. Form( Http. Servlet. Request request ) { User. Dto user = new User. Dto(); //command (전달) 객체 생성 //get이 아니거나 데이터가 없을 경우 기본값 출력 Message. Source. Accessor accessor = new Message. Source. Accessor(this. message. Source); user. set. Id(accessor. get. Message("user. Id. default")); user. set. Name(accessor. get. Message("user. Name. default")); if (request. get. Method(). equals. Ignore. Case("GET")) { String user. Id = request. get. Parameter("user. Id"); try { user = this. user. Service. get. User. By. User. Id(user. Id); return user; } catch (Empty. Result. Data. Access. Exception e) { return user; } } else { return user; } }
User. Edit. Form. Controller 작성 @Request. Mapping(method = Request. Method. GET) public String to. User. Edit. View() { return "user. Edit"; } @Request. Mapping(method = Request. Method. POST) public Model. And. View on. Submit( @Model. Attribute User. Dto user, Binding. Result binding. Result) throws Exception { this. user. Edit. Validator. validate(user, binding. Result); //검증기 실행 Model. And. View model. And. View = new Model. And. View(); if (binding. Result. has. Errors()) { model. And. View. get. Model(). put. All(binding. Result. get. Model()); return model. And. View; } try { this. user. Service. update. User(user); model. And. View. set. View. Name("user. Entry. Success"); model. And. View. add. Object("user", user); return model. And. View; } catch (Data. Integrity. Violation. Exception e) { binding. Result. reject("error. duplicate. user"); model. And. View. get. Model(). put. All(binding. Result. get. Model()); return model. And. View; } }
View 작성(user. Edit. jsp) <%@ page language="java" content. Type="text/html; charset=utf-8" page. Encoding="utf-8"%> <%@ include file="/WEB-INF/jsp_header. jsp"%> <HTML> <HEAD> <TITLE> 회원 정보 수정 </TITLE> <META http-equiv="Content-Type" content="text/html; charset=utf-8"> <style type='text/css'> <!-a: link{font-family: ""; color: black; text-decoration: none; } a: visited{font-family: ""; color: black; text-decoration: none; } a: hover{font-family: ""; color: black; text-decoration: underline; } --> </style> <SCRIPT> function Zip. Code() { browsing_window = window. open("zip_form. jsp", "_zipinput", "height=300, width=600, menubar=no, directories=no, resizable=no, status=no, scrollbars=yes"); browsing_window. focus(); } </SCRIPT> </HEAD>
View 작성(user. Edit. jsp) <BODY> <center><font size='3'><b> 회원정보 수정 </b></font> <hr size='1' noshade width='600' align="center"> <spring: has. Bind. Errors name="user. Dto"> <font color="red"> <c: for. Each items="${errors. global. Errors}" var="error”> <spring: message code="${error. code}" /> </c: for. Each> </font> </spring: has. Bind. Errors> <form: form model. Attribute="user. Dto" Name='join. Form' Method='post' Action='/Login 4 mvc/user. Edit. html'> <TABLE border='2' width='600' cell. Spacing=0 cell. Padding=5 align=center> <TR> <TD bgcolor='cccccc' width='100' align='center'> <font size='2'>아 이 디</font> </TD> <TD bgcolor='cccccc'> <form: input path="id" max. Length='20' size='10' readonly='true' /> <span class="field. Error"> <form: errors path="id" /></span> </TD> </TR>
View 작성(user. Edit. jsp) <TR> <TD bgcolor='cccccc' align='center‘><font size='2'>비 밀 번 호</font></TD> <TD bgcolor='cccccc'> <form: password path="pass" maxlength="20" size='10' show. Password="true" /> <span class="field. Error"><form: errors path="pass" /></span> </TD> </TR> <TD bgcolor='cccccc' align='center’><font size='2'>비밀번호확인</font></TD> <TD bgcolor='cccccc'> <form: password path="pass 2" maxlength="20" size='10' value="${user. pass}" show. Password="true" /> <span class="field. Error"><form: errors path="pass 2" /></span> </TD> </TR> <TD bgcolor='cccccc' align='center‘><font size='2'>이 름</font></TD> <TD bgcolor='cccccc'> <form: input path="name" maxlength="20" size='10' readonly='true' /> <span class="field. Error"><form: errors path="name" /></span> </TD> </TR> <TD bgcolor='cccccc' align='center‘><font size='2'>주민등록번호</font></TD> <TD bgcolor='cccccc'> <form: input path='jumin' size='13' maxlength='13' readonly='true' /> <span class="field. Error"><form: errors path="jumin" /></span> </TD>
View 작성(user. Edit. jsp) <TR> <TD bgcolor='cccccc' align='center'> <font size='2'>우 편 번 호</font><span class="field. Error"> </TD> <TD bgcolor='cccccc'> <form: input path='zip' maxlength='7' size='7' /> <input On. Click='Zip. Code()' type='button' value='우편번호검색'><span class="field. Error"><form: errors path="zip" /></span> </TD> </TR> <TD bgcolor='cccccc' align='center'><font size='2'>주 소</font></TD> <TD bgcolor='cccccc'> <form: input maxlength='50' size='50' path='addr 1' /><span class="field. Error" ><form: errors path="addr 1" /></span><BR> <form: input maxlength='50' size='50' path='addr 2' /><span class="field. Error" ><form: errors path="addr 2" /></span> </TD> </TR> <TD bgcolor='cccccc' align='center'><font size='2'>전 화 번 호</font></TD> <TD bgcolor='cccccc'> <form: input type='text' maxlength='20' size='20' path='phone' /> <span class="field. Error" ><form: errors path="phone" /> </span> </TD> </TR> <TD bgcolor='cccccc' align='center'><font size='2'>E - M a i l</font></TD> <TD bgcolor='cccccc'> <form: input type='text' maxlength='50' size='50' path='email' /> <span class="field. Error" ><form: errors path="email" /></span> </TD> </TR> </TABLE>
View 작성(user. Edit. jsp) <hr size='1' noshade width='600' align="center"> <TABLE> <TR><TD colspan='2' align='center'><input type='submit' value='수정'></TD></TR> </TABLE> </form: form> </BODY> </HTML>
Success View(user. Entry. Success. jsp) <%@ page content. Type="text/html; charset=UTF-8"%> <%@ include file="/WEB-INF/jsp_header. jsp"%> <html> <head> <title>유저 등록 완료 화면</title> </head> <body> <div align="center" class="body"> <h 2>유저 등록 완료 화면</h 2> <b><font color="red">다음과 같이 유저 등록이 완료되었습니다. </font></b> <table border='1' width='600' cellpadding='0' cellspacing='0'> <tr height="40 px"> <td bgcolor='cccccc' width='100' align='center' >유저ID: </td><td>${user. id}</td> </tr> <tr height="40 px"> <td bgcolor='cccccc' width='100' align='center' >패스워드: </td><td>${user. pass}</td> </tr> <tr height="40 px"> <td bgcolor='cccccc' width='100' align='center' >이름: </td><td>${user. name}</td> </tr> <tr height="40 px"> <td bgcolor='cccccc' width='100' align='center' >주민번호: </td><td>${user. jumin}</td> </tr>
Success View(user. Entry. Success. jsp) <tr height="40 px"> <td bgcolor='cccccc' </tr> <tr height="40 px"> <td bgcolor='cccccc' </tr> </table> width='100' align='center' >우편번호: </td><td>${user. zip}</td> width='100' align='center' >주소: </td><td>${user. addr 1}</td> width='100' align='center' >상세주소: </td><td>${user. addr 2}</td> width='100' align='center' >전화번호: </td><td>${user. phone}</td> width='100' align='center' >E-MAIL: </td><td>${user. email}</td> <p><ul id="ullog" > <li id="lilogb"><a href="/Login 4 mvc/login. html">로그인</a></li>| </ul></p> </div> </body> </html>
Application. context, -servlet. xml 추가 <!-- Validator --> <bean id="login. Validator" class="user. utils. Login. Validator" /> <bean id="user. Entry. Validator" class="user. utils. User. Entry. Validator" /> <!-- Handler. Mapping --> <bean id="url. Mapping" class="org. springframework. web. servlet. handler. Simple. Url. Handler. Mapping"> <property name="mappings"> <props> <prop key="/login. html">login. Form. Controller</prop> <prop key="/user. Edit. html">user. Edit. Form. Controller</prop> </props> </property> </bean> <!-- Controller --> <bean id="login. Form. Controller" class="user. controller. Login. Form. Controller" p: user. Service-ref="user. Service" p: login. Validator-ref="login. Validator" > </bean> <bean id="user. Edit. Form. Controller" class="user. controller. User. Edit. Form. Controller" p: user. Service-ref="user. Service" p: user. Edit. Validator-ref="user. Edit. Validator" p: message. Source-ref="message. Source"> </bean>
Dao구현 클래스 수정 User. Dto. java
사용자 로그인 클래스다이어그램 Context. Loader. Listner Dispatcher. Servlet login. html(get) -application. Context. xml handler. Mapping (Simple. Url. Handler. Mapping) login. Validator (Login. Validator. java) login. Form. Controlle r (Login. Form. Controller. java) set. Login. Validator() set. User. Service( ) 사용 interface User. DAO Interface User. Service 사용 set. Up. Form() to. Login. View() on. Submit() internal. Resource. View. Res olver ( SInternal. Resource. View. Resolv er) login. html(post) Login. jsp User. Edit. html(get) login. Sucess. j sp 사용 User. Service (User. Service. Impl. java) user. Dao (User. Dao. Impl. java) set. User. Dao ( ) get. User. By. User. Id. And. Passw ord() entry. User(User user); set. Data. Source ( ) find. By. User. Id. And. Password() create(User user) User. Dto ㅋ Jdbc. Template() data. Source
component-scan 기능 컴퍼넌트 자동스캔 기능을 사용하여 Handler. Mapping과 controller 객체 생성을 생략한다. <context: cmponent-scan base-package="user. controller" /> @Controller 어노테이션이 표기된 Controller 자동 검색 객체(빈) 생성 <context: annotation-config/> @Autowire 표시된 참조객체 자동 DI Login 4 mvc-servlet. xml 수정
JSR 303 Bean Validation User. Dto 수정 hibernate @valid constraint Annotation @Length(min=, max=) @Max(value=) @Min(value=) @Not. Null @Not. Empty @Past @Future @Pattern(regex="regexp", flag=) @Range(min=, max=) @Size(min=, max=) @Assert. False @Assert. True @Valid @Email
컨트롤러 코드 수정. if (binding. Result. has. Field. Errors("id")||binding. Result. has. Field. Errors("p ass")) { Id 나 패스워드가 입력되지 않은 경 성공시 view 설정 View에 Dto 전달 Id 패스워드가 입력되었으나 틀린 경우 Error code 설정 Error code view에 전달
Login. jsp <body> <div id="login. Area" class="clear"> 또는 user. Dto <form: form model. Attribute="user" method="post" action="login. html"> <fieldset> <legend><h 4>로그인</h 4></legend> <spring: has. Bind. Errors name="user"> <span class="field. Error"> <c: for. Each var="err" items="${errors. global. Errors}" > <spring: message code="${err. code}" /> </c: for. Each> </span> </spring: has. Bind. Errors> 다음 페이지 내용 삽입 … <p><ul id="ullog"> <li id="lilogb"><a href="/Spring. Log. Han/user. Entry. html">회원가입</a></li>| <li id="lilog"><a href="/Spring. Log. Han/find. Id_form. html">아이디/</a> <a href="/Spring. Log. Han/find. Pass_form. html" class="pwd">비밀번호 찾기 </a></li> </ul></p> </fieldset> </form: form> </div> </body>
Id 찾기 로그인화면 로그아웃 사용자별 메인화면 정보수정 사용자정보 수정화면 확인 사용자정보 보기화면 아이디찾기 사용자등록 화면 사용자정보 보기화면 확인 http: //localhost: 8080/Login 4 mvc/user. Entry. html user. Entry. Success. jsp user. Entry. jsp 1 2 4 User. Entry. Form. Contr oller 3 User. Entry. Validator or @Valid 4 User. Servise 5
사용자 정보 수정 로그인화면 로그아웃 사용자별 메인화면 정보수정 아이디찾기 화면 확인 사용자정보 수정화면 확인 사용자정보 보기화면 아이디찾기 결과화면 http: //localhost: 8080/Login 4 mvc/find. Pass_for m. html find. Pass. Success. jsp find. Pass_form. jsp 1 2 Find. Pass. Form. Control ler 3 4 Find. Pass. Validator 4 User. Servise 5
b Http. Servlet. Request org. springframework. web. servlet. Dispatcher. Servlet Spring MVC Interceptor 1 JDBC ORM Interceptor 2 Interceptor 3 Io. C Container Controller Business Object Model. And. View Template - JSP - Velocity - Freemarker Interceptor 3 application. Context. xml Interceptor 2 action-servlet. xml Interceptor 1 DAO Page Control - dispatch - redirect Http. Servlet. Response
사용자 로그인 클래스다이어그램 Context. Loader. Listner Stripes. Dispatcher html(get) -application. Context. xml interface User. DAO handler. Mapping (Simple. Url. Handler. Mapping) login. Validator (Login. Validator. java) login. Form. Controlle r (Login. Form. Controller. java) set. Login. Validator() set. User. Service( ) 사용 Interface User. Service 사용 set. Up. Form() Mapper. Scanner. Config to. Login. View() urer persistence on. Submit() internal. Resource. View. Res olver ( SInternal. Resource. View. Resolv er) login. html(post) Login. jsp login. Sucess. j sp 사용 User. Service (User. Service. Impl. java) set. User. Dao ( ) get. User. By. User. Id. And. Passw ord() entry. User(User user); User. Dto ㅋ er. Edit. html(get) data. Source Account. Mapper. xml get. Account. By. Username() Account. Mapper. xml get. Account. By. Username. And. Pass get. Account. By. Username() word() get. Account. By. Username. And. Pass update. Account() word() insert. Account() update. Profile() insert. Account() insert. Profile() update. Profile() insert. Profile() sql. Session. Factor y set. Data. Source() data. Source
Account. Mapper 사용자 로그인 클래스다이어그램 Category. Mapper Account. Mapper. xml get. Account. By. Username() get. Account. By. Username. And. Pass word() update. Account() insert. Account() Product. Mapper update. Profile() insert. Profile() get. Product. List. By. Category get. Category. List() get. Category(String category. Id); Account. Service set. Account. Mapper() Catalog. Service set. Category. Mapper () Order. Service Setorder. Mapper set. Item. Mapper () set. Order. Mapper() set. Ssequence. Mapper() set. Line. Item. Mapper() () get. Product() Line. Item. Mapper search. Product. List() insert. Line. Item() Sequence. Mapper get. Sequence( ) Order. Mapper update. Sequence() get. Order() Item. Mapper insert. Order() update. Inventory. Quantity() insert. Order. Status() get. Inventory. Quantity(); get. Item. List. By. Product() get. Item() sql. Session. Factor y set. Data. Source() transaction. Mana ger set. Data. Source() data. Source
사용자 로그인 클래스다이어그램 Stripes. Dispatcher Abstract. Action. Bean set. Message() get. Context() set. Context() Account. Action. Bean Account. Mapper Account. Service Account. Mapper. xml get. Account. By. Username() get. Account. By. Username. And. Pass word() … set. Account. Mapper() Category. Mapper get. Category. List() Product. Mapper get. Category(String get. Product. List. By. Categor category. Id); y( ) get. Product() Item. Mapper search. Product. List() Catalog. Service set. Category. Mapper () update. Inventory. Quantity() get. Inventory. Quantity(); get. Item. List. By. Product() Line. Item. Mapper get. Item() insert. Line. Item() Sequence. Mapper Cart. Action. Bean Order. Service Setorder. Mapper Catalog. Action. Bean set. Item. Mapper () set. Order. Mapper() set. Ssequence. Mapp er() set. Line. Item. Mapper() get. Sequence( ) Order. Mapper update. Sequence() get. Order() insert. Order. Status() Order. Action. Bean sql. Session. Facto ry set. Data. Source( transaction. Mana ger set. Data. Source( ) ) data. Source
자바 기술 HTML 5 C++ Java java. Fx Jquery JSTL jsp Java Beans Spring Framework Mobile Hybrid Ajax Dreamweaver Boot. Strap App 실습 예제 : 회원인증 > 게시판 > 방명록
Spring framework I Java 객체지향 프로그래밍 Java bean Framework 입문 Spring framework 환경구성 l 객체지향 설계원칙 의존관계 제어의 역전 Ioc 7 개의 예제 Application Context, Io. C Container, Spring Container 3개의 예제로 구성 Spring framework 구조와 MVC 모델 Legacy Spring framework Hello World 예제 Error 메시지 시작 프로젝트 Maven, JDBC를 활용한 예제(회원관리시스템)
Spring 5. 0. 0
- Slides: 106