아래에서는 사진 및 텍스트를 통해 사용자 로그인 및 등록 기능을 구현하기 위해 JavaweB의 예제 코드를 소개합니다. 살펴 보겠습니다.
1. Servlet+JSP+Javabean Development 모델 소개 (MVC)
Servlet+JSP+Javabean Mode (MVC)는 복잡한 웹 응용 프로그램을 개발하는 데 적합합니다. 이 모드에서 서블릿은 사용자 요청을 처리 할 책임이 있으며 JSP는 데이터 표시를 담당하며 Javabean은 데이터를 캡슐화 할 책임이 있습니다. Servlet+JSP+Javabean 모드 프로그램은 모듈간에 명확한 레벨을 가지며이 모드를 사용하는 것이 좋습니다.
여기서 우리는 가장 일반적으로 사용되는 사용자 로그인 등록 프로그램을 사용하여 Servlet+JSP+Javabean Development 모델을 설명합니다. 이 사용자 로그인 등록 프로그램 포괄적 인 사례를 통해 이전에 배운 XML, XPath, Servlet 및 JSP의 지식 포인트를 연결합니다.
2. MVC 아키텍처를 사용하여 웹 프로젝트를 만듭니다
MyEclipse에서 새로운 WebMVCFramework 프로젝트를 작성하고 프로젝트에서 요구하는 개발 패키지 (JAR PACKATE)를 가져오고 프로젝트에서 필요한 패키지를 만듭니다. Java 개발에서 아키텍처 수준은 패키지 형태로 반영됩니다.
| 프로젝트에 필요한 개발 패키지 (JAR 패키지) | ||
| 일련 번호 | 개발 패키지 이름 | 설명하다 |
| 1 | dom4j-1.6.1.jar | dom4j는 XML 파일을 조작하는 데 사용됩니다 |
| 2 | Jaxen-1.1-Beta-6.jar | XPath 표현을 구문 분석하는 데 사용됩니다 |
| 3 | Commons-Beanutils-1.8.0.jar | Bean 객체를 처리하기위한 공구 클래스 |
| 4 | 커먼즈 로깅 | Commons-Beanutils-1.8.0. 자 의존성 JAR 패키지 |
| 5 | jstl.jar | JSTL 태그 라이브러리 및 EL 식 종속성 패키지 |
| 6 | 표준. 자 | JSTL 태그 라이브러리 및 EL 식 종속성 패키지 |
좋은 Javaweb 프로젝트 아키텍처에는 위의 11 개의 패키지가 있어야하므로 각 계층 간의 책임이 명확 해집니다. Javaweb 프로젝트 아키텍처를 구축 할 때는 위의 1 ~ 11 순서로 패키지를 만듭니다 : 도메인 → dao → dao.impl → service → service.impl → web.controller → web.ui → web.filter → web.listener → util → junit.test. 패키지 레벨이 만들어지면 프로젝트 아키텍처가 결정됩니다. 물론 실제 프로젝트 개발에서는 완전히 기반을 두지 않을 수 있습니다.
| 프로젝트에 필요한 패키지 | |||
| 일련 번호 | 패키지 이름 | 설명하다 | 수준 |
| 1 | me.gacl.domain | 시스템을 저장하는 Javabean 클래스 (간단한 속성 만 포함하고 속성에 해당하는 Get and Get and Set Methods는 [Data Access Layer], [비즈니스 프로세싱 계층] 및 [Web Layer]에 제공되는 특정 비즈니스 처리 방법을 포함하지 않음) | 도메인 (도메인 모델) 층 |
| 2 | me.gacl. 다오 | 데이터베이스에 대한 액세스를 저장하는 작동 인터페이스 클래스 | 데이터 액세스 계층 |
| 3 | me.gacl. dao.impl | 데이터베이스에 액세스하는 작업 인터페이스를 저장하는 구현 클래스 | |
| 4 | me.gacl. 서비스 | 매장 처리 시스템 비즈니스 인터페이스 클래스 | 비즈니스 처리 계층 |
| 5 | me.gacl. service.impl | 처리 시스템 비즈니스 인터페이스 저장을위한 구현 클래스 | |
| 6 | me.gacl. web.controller | 서블릿은 시스템 컨트롤러로 저장됩니다 | 웹 계층 (프레젠테이션 계층) |
| 7 | me.gacl.web.ui | 사용자에게 사용자 인터페이스를 제공하는 Servlets (UI 참조) | |
| 8 | me.gacl.web.filter | 스토리지 시스템에 사용되는 필터 | |
| 9 | me.gacl.web.listener | 리스너는 시스템을 저장하는 데 사용되었습니다 | |
| 10 | me.gacl .util | [Data Access Layer], [비즈니스 처리 계층] 및 [웹 레이어]에 제공되는 시스템 저장을위한 일반 | |
| 11 | junit.test | 시스템 저장을위한 테스트 클래스 | |
위에서 언급했듯이 패키지 계층 구조를 생성하지만 프로젝트의 실제 상황을 기반으로 만들면이를 만들어야 할 수도 있습니다.
그의 가방, 이것은 프로젝트 요구에 따라 다릅니다.
SRC 디렉토리 (Category Directory)에서 사용자 데이터 저장 (DB.XML)을위한 XML 파일 (DB.XML)을 만듭니다.
Web-Inf 디렉토리에서 페이지 디렉토리를 만듭니다. 페이지 디렉토리는 시스템의 일부 보호 된 JSP 페이지를 저장합니다 (사용자가 URL 주소를 통해 직접 액세스 할 수 없음). 사용자 가이 보호 된 JSP 페이지에 액세스하려면 me.gacl.web.ui 패키지에서만 서블릿 만 사용할 수 있습니다.
생성 된 프로젝트는 다음 그림 (그림 -1)에 표시됩니다.
그림 -1
3. 계층 구조의 코드 쓰기
계층 구조의 코드는 [도메인 모델 레이어 (도메인)] → [Data Access Layer (DAO, DAO.IMPL)] → [비즈니스 프로세싱 레이어 (Service, Service.Impl)] → [Expression Layer (Web.Controller, Web.Ui, Web.Filter, Web.Listener)]의 순서로 작성됩니다. (junit.test)].
3.1. 도메인 계층을 개발하십시오
me.gacl.domain 패키지에서 사용자 클래스를 만듭니다
사용자 클래스의 특정 코드는 다음과 같습니다.
package me.gacl.domain; import java.io.serializable; import java.util.date;/*** @author gaCl*사용자 엔티티 클래스*/public class eplice emperments serializable {private static final long serialversionuid = -l; // 사용자 idprivate 문자열 ID; // 사용자 이름의 전자 메 이름; // user string private userpd; // 사용자 생일 개인 날짜 생일; public string getId () {return id;} public void setId (string id) {this.id = id;} public string getUserName () {return username;} public void setUserName (string username) {username = username;} public string getUserpwd () {usererpwd;} {this.userpwd = userpwd;} public string getEmail () {return email;} public void seteMail (문자열 이메일) {this.email = email;} public date getBirthday () {return return;} public void setbirthday (날짜) {this.birthday = 생일;}}}}}}3.2. 데이터 액세스 계층 개발 (DAO, DAO.IMPL)
me.gacl.dao 패키지에서 iuserdao 인터페이스 클래스를 만듭니다. 개발 인터페이스 클래스의 경우 문자 I을 클래스의 접두사로 사용하는 데 익숙해 져서 현재 클래스가 인터페이스라는 한 눈에 볼 수 있습니다. 이는 또한 좋은 개발 습관이기도합니다. 클래스 이름을 살펴보면 인터페이스인지 특정 구현 클래스인지 쉽게 구별 할 수 있습니다.
iuserdao 인터페이스의 특정 코드는 다음과 같습니다.
package me.gacl.dao; import me.gacl.domain.user; public interface iuserdao {/*** 사용자 이름과 비밀번호를 기반으로 사용자를 찾으십시오* @param username* @param userpwd* @return*/user find (string username, string userpwd); @param add (사용자); name* @param username* @return 사용자 찾은*/user find (string username);}인터페이스의 메소드 정의의 경우 특정 비즈니스에 따라 정의 해야하는 메소드 만 분석 할 수 있습니다. 그러나 비즈니스가 아무리 복잡하더라도 기본 CRUD (추가, 삭제, 수정 및 쿼리) 작업과 분리 할 수는 없습니다. DAO 계층은 데이터베이스와 직접 상호 작용하므로 DAO 계층 인터페이스는 일반적으로 추가, 삭제, 수정 및 쿼리를 추가하는 4 가지 관련 방법을 갖습니다.
me.gacl.dao.impl 패키지에서 userdaoimpl 클래스를 만듭니다
userdaoimpl 클래스는 iuserdao 인터페이스의 특정 구현 클래스입니다. 인터페이스의 구현 클래스의 이름 지정 메소드의 경우, 인터페이스 이름 (접두사 i 제거) + impl "또는"인터페이스 이름 + empl ": iuserdao (인터페이스) → userDaoimpl (구현 클래스) 또는 iuserdao (인터페이스) → iuserdaoimpl (iuserdaoimpl) 형식으로 이름 지정에 사용됩니다. 이것은 또한 개인 프로그래밍 습관이기도합니다. 내가 보는 대부분의 코드는 일반적으로 인터페이스의 특정 구현 클래스를이 두 형식 중 하나로 지정합니다. 어쨌든 인터페이스에 해당하는 구현 클래스가 한눈에 볼 수 있어야합니다.
userdaoimpl 클래스의 특정 코드는 다음과 같습니다.
ME.gacl.dao.impl; import java.text.simpledateformat; import org.domj.document; import org.domj.element; import me.gacl.dao.iuserdao; import me.gacl.domain.user; import me.gacl.util.xmlutils;/*** @AoTor Classe of iUSERDAO의 구현. gacl*/public class userdaoimpl은 iuserdao {@overridepublic user find (string username, string userpwd) {try {document docum @userpwd = ' "+userpwd+"'] "); if (e == null) {return null;} user user = new user (); user.setId (e.attributeValue ( "id")); user.seteMail (e.attributeValue ( "email")); user.setuserpwd (e.attributeValue ( "userpwd"); user.setusername (e.attributeValue ( "username"); e.attratt value (simpleat value = "); new simpledateformat ( "yyyy-mm-dd"); user.setbirthday (sdf.parse (birth)); return user;} catch (예외 e) {new new runtimeexception (e);}}@suppresswarnings ( "recrecation")@overridepublic void add (try inter user inter in); document.getRootElement (); element user_node = root.addelement ( "user"); // 사용자 노드를 만들고 rootuser_node.setAttributeValue ( "id", user.getId ()); user_node.setAtttributeValue ( "username", user.getusername ()); user_node.setattatttributevalue ( "userpwd", user. user.getEmail ()); simpledateformat sdf = new simpledateformat ( "yyyy-mm-dd"); user_node.setatttributevalue ( "생일", sdf.format (user.getbirthday ()); xmlutils.writexml (document);} {rash new runtimeexception (e);}}@overridepublic user find (string username) {try {document document = xmlutils.getDocument (); element e = (element) document.selectsingLenode ( "@username = '"+username+"']; if (e == null)} user null; user (); user.setId (e.attributeValue ( "id")); user.seteMail (e.attributeValue ( "email")); user.setuserpwd (e.attributeValue ( "userpwd"); user.setusername (e.attributeValue ( "username"); e.attratt value (simpleat value = "); new SimpledateFormat ( "yyyy-mm-dd"); user.setbirthday (sdf.parse (birth)); return user;} catch (예외 E) {throw new runtimeexception (e);}}}3.3. 개발 서비스 계층 (서비스 계층은 웹 계층에 모든 비즈니스 서비스를 제공합니다)
me.gacl.service 패키지에서 iuserservice 인터페이스 클래스를 만듭니다
iuserservice 인터페이스의 특정 코드는 다음과 같습니다.
ME.gacl.service; import me.gacl.gomain.user; import me.gacl.xception.userexistexception; public interface iuserService {/*** 등록 서비스 제공* @param user* @throws userexistException*/void RegisterSexception*/void RegisterSexception*/*** @parex user usereme* @parameme* @parematepd* @parexiStexception; @return*/user loginuser (String username, String userpwd);}me.gacl.service.impl 패키지에서 usererviceimpl 클래스를 만듭니다
usererviceimpl 클래스는 iuserservice 인터페이스의 특정 구현 클래스입니다. 특정 코드는 다음과 같습니다.
me.gacl.service.impl; import me.gacl.dao.iuserdao; import me.gacl.dao.impl.userdaoimpl; import me.gacl.domain.user; import me.gacl.exception.userexistexception.userexistexception; public userservice; public userervice; iuserdao userdao = new userDaoimpl ();@atrivePublic void registerUser (user user)는 userexistexception {if (userdao.find (userdao.find (user.getusername ()) {// Checked Exception // Compile-Time Exception에 대한 예외를 원한다. userexistException ( "등록 된 사용자 이름이 이미 존재합니다 !!!");} userDao.add (user);}@atrivepublic user loginuser (string username, string userpwd) {return userdao.find (username, userpwd);}}3.4. 웹 계층을 개발하십시오
3.4.1. 등록 기능을 개발하십시오
1. Me.gacl.web.ui 패키지 아래에 registeruiservlet을 작성하여 사용자에게 등록 인터페이스를 제공합니다.
사용자 요청을받은 후 RegisterUiservlet은 register.jsp로 점프합니다
RegisterUiservlet 코드는 다음과 같습니다.
packing me.gacl.web.ui; import java.io.ioexception; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpperpronge;/** 사용자가 등록 된 사용자 인터페이스를 제공하는 GaCl* Servlet* RegisterUiserVlet은 사용자의 등록 인터페이스를 출력 할 책임이 있습니다* 사용자가 registerUiservlet에 액세스 할 때 registerUiserVlet에 액세스 할 때 web-inf/pages directory*/public class registuiservlet httpservlet void doget (httpservletrowest)에서 register.jsp 페이지로 이동합니다. ServleTeXception, ioException {request.getRequestDispatcher ( "/web-inf/pages/register.jsp"). forward (요청, 응답);} public void dopost (httpservletrequest request, httpservletreponse responsk) servletexception, ioexception, ioxception (요청, 응답);2./web-inf/pages/directory에서 사용자 등록 JSP Page Register.jsp 작성
Web-Inf 디렉토리에있는 모든 JSP 페이지는 URL 주소를 통해 직접 액세스 할 수 없습니다.
개발 중에 외부 세계에서 직접 액세스하고 싶지 않은 프로젝트에 민감한 웹 리소스가있는 경우 이러한 민감한 웹 리소스를 웹 -INF 디렉토리에 넣어 외부 세계가 URL을 통해 직접 액세스하는 것을 금지 할 수 있습니다.
register.jsp 페이지의 코드는 다음과 같습니다.
<%@ page language = "java"pageencoding = "utf-"%> <! doctype html> <html> <head> <title> 사용자 등록 </title> </head> <body style = "text-align : center;"> <form action = "$ {pagecontext.ruquest.context path}/servlet/servergervlet" 메소드 = "post"> <table> <td> <td> username </td> <td> <input type = "text"name = "username"> </td> </tr> <td> <td> password </td> <td> <입력 = "password"name = "userpwd"> </td> <td> type = "password"name = "quictpwd"> </td> </td> <td> email </td> <td> <입력 유형 = "text"name "name" "email"> </td> </tr> <t> <td> 생일 </td> <td> <input type = "text" "name ="<td> <td> <td> <td> <td> <td> <td> type = "Reset"value = "clear"> </td> <td> <입력 유형 = "제출"value = "register"> </td> </tr> </table> </form> </body> </html> <form action = "$ {pagecontext.request.contextpath}/servlet/regis
3. me.gacl.web.controller 패키지에서 사용자 등록을 처리하기위한 RegisterServlet 작성
RegisterServlet은 다음과 같은 책임을집니다.
1. 클라이언트가 서버에 제출 한 양식 데이터를받습니다.
2. 양식 데이터의 합법성을 확인하십시오. 확인이 실패하면 register.jsp로 돌아와 오류 메시지를 반영하십시오.
3. 확인이 전달되면 서비스 계층에 전화하여 사용자를 데이터베이스에 등록하십시오.
RegisterServlet이 양식 데이터 및 확인 양식 데이터를 수신하도록 촉진하기 위해 등록 양식 데이터 검증을위한 RegisterFormBean을 설계 한 다음 WebUtils 도구 클래스를 작성하여 클라이언트가 제출 한 양식 데이터를 Formbean에 캡슐화합니다.
me.gacl.web.formbean 패키지에서 등록 양식 데이터를 확인하기위한 RegisterFormBean 생성
RegisterFormbean 코드는 다음과 같습니다.
packing me.gacl.web.formbean; import java.util.hashmap; import java.util.map; import org.apache.commons.beanutils.locale.converters.datelocaleconverter;/*** 캡슐화 된 사용자 등록 양식 Bean은 Register.jsp의 명단 입력에 해당합니다. register.jsp*의 양식 입력 항목* registerformbean의 책임은 register.jsp에서 양식 입력 항목의 값을 수신 할뿐만 아니라 양식 입력 항목의 값의 합법성 역할을합니다. @author gacl **/public class registerformbean {// register formbean의 속성에 해당합니다. 이름 = "username"/> private String username; // <input type = "prossive"name "="userpwd "/> private String userpwd; // <입력 유형 ="passwor "name ="quicatepwd "/> private string volictpwd; // <input type ="text "name ="email "/> private string email; <intor string ="텍스트 "/> eary ite onear ter it 검증이 실패 할 때의 사용자는*/private map <string, string> errors = new Hashmap <string, string> (); public map <string, string> geterRors () {return void setErrors (} public void setErrors (map <string, string> errors) {this.errors = errors =}/** 형식 입력 항목을 확인하는 데 책임이 있습니다. 사용자 이름은 비어있을 수 없으며,이면 -LETTER ABCDABCD * private String userpwd; 비밀번호는 비어있을 수 없으며 - 숫자 * 개인 문자열 volictpwd; 비밀번호는 두 번 * 개인 문자열 이메일과 동일해야합니다. 법적 사서함이라면 비어 있지 않고 비어있을 수 있습니다.* 개인 문자열 생일; 법적 날짜*/public boolean validate () {boolean isok = true; if (this.username = null || this.username.trim (). equals ( "")) {isok = false; errors.put ( "username", "username!") (! this.username.matches ( "[a-za-z] {,}")) {isok = false; errors.put ( "username", "사용자 이름은 -bit !!");}} if (this.userpwd == null || this.userpwd.trim ()). false; errors.put ( "userpwd", "password가 비어있을 수 없습니다 !!");} else {if (! this.userpwd.matches ( "// d {,}")) {isok = false; errors.put ( "userpwd", "비밀번호는 숫자가되어야합니다!");}}}}}}}}}}}}}}}}}}}}} 두 번 (this.confirmpwd! = null) {if (! this.confirmpwd.equals (this.userpwd)) {isok = false; errors.put ( "confictpwd", "두 번이 무효가되지 않는 경우,"}}}}}}}}}}}}}}}}}; 널이 아니라 비어있을 수 있습니다. if (this.email! = null &&! this.mail.trim (). equals ( "")) {if (! this.mail.matches ( "// w+@// w+(// w+)+") {isok = false; errors.put ( "이메일", "법적 메일 박스가 아님"); (this.birthday! = null &&! then.birthday.trim (). Equals ( ""))) {try {datelocaleconverter convert = new datelocaleConverter (); conver.convert (this.birthday); {생일에 {resok = "" "" "" 날짜 !! ");}} return isok;} public string getUserName () {return username;} public void setUsername (string username) {this.username = username;} public string getUserpwd () {return userpwd;} public void setuserpwd (string userpwd) {userpwd = userpwd = userpwd; getConfirmpwd () {return qualthpwd;} public void setconfirmpwd (string quickpwd) {this.confirmpwd = volictpwd;} public string geteMail () {return allead;} public void seteMail (문자열 이메일) {this.email = 이메일;} public string getBirthday ()}}}}}} {this.birthday = 생일;}}me.gacl.util 패키지에서 webutils 도구 클래스를 만듭니다. 이 도구 클래스의 기능은 클라이언트가 제출 한 양식 데이터를 Formbean에 캡슐화하는 것입니다.
package me.gacl.util;import java.util.Enumeration;import java.util.UUID;import javax.servlet.http.HttpServletRequest;import org.apache.commons.beanutils.BeanUtils;/*** @author gacl* Encapsulate the request parameters in the request object into bean*/public class WebUtils {/*** 요청 객체를 t 객체* @param request* @param clazz* @return*/public static <t> t RequestBean (httpservletrequest request, class <t> clazz) {try {t bean = clazz.newinstance (); enumeration <string> e = request.getparameternames (); while (e.hasmoreElements ()) {String name = (string) e.nextElement (); String value = reture.getParameter (name); beanutils.setProperty (bean, name, value);} catch (Exception e) {new runtimeexception (e);}}/*** uuid* @public string manyid () {retafe*/public string (retaine*/public string). uuid.randomuuid (). tostring ();}}마지막으로, 사용자 등록을 담당하는 RegisterServlet의 전체 코드를 살펴 보겠습니다.
Me.gacl.web.controller; import java.io.ioexception; import java.util.date; import javax.servlet.servletexception; import javax.servlet.http.httpervlet; import javax.servlet.http.htttp.htttp.htttpletrequest; 가져 오기; javax.servlet.http.httpervletresponse; import org.apache.commons.beanutils.beanutils; import org.apache.commons.beanutils.convertutils; import org.apache.commons.beanutil.locale.conconverters; import me.gacl.us me.gacl.exception.userexistexception; import me.gacl.service.iuserService; import me.gacl.service.impl.userserviceimpl; import me.gacl.util.webutils import me.gacl.web.formbean.registerformbean;/*** servlet handles registration*@author gacl*@author gacl handsor gacl. httpservlet {public void doget (httpservletrequest request, httpservletresponse 응답)을 servletexception, ioexception {// 클라이언트가 제출 한 양식 데이터를 registerformbean 객체에 캡슐화하십시오. Registerformbean formbean = awutils.requestbean (registerformbean.class); // class worth the form the form the form worl (formbean.validate () == false) {// 확인이 실패하면 // 디스플레이 요청에 대해 register.jsp 페이지의 양식 데이터를 캡슐화하는 양식 객체를 보내는 경우 register.jsp 페이지를 캡슐화합니다. register.jsprequest.getRequestDisPatcher ( "/web-inf/pages/register.jsp"). forward (요청, 응답); return;} user user = new user (); try {//convertutils.register(new datelocaleconverter (), date.class) (user, formbean); user.setid (webutils.makeid ()); // 사용자의 ID 속성을 설정하십시오 iuserservice service = new usererServiceImpl (); // 사용자 등록 서비스를 달성하기 위해 서비스 계층에서 제공 한 등록 된 사용자 서비스를 호출합니다. String Message = String.format ( "성공적으로 등록!! 그것은 몇 초 만에 로그인 페이지로 자동 이동합니다!! <meta http-equiv = 'Refresh'content = '; url =%s'/>", request.getContextPath ()+"/servlet/loginUiservlet"); request.setAttribute ( "message", message); request.getRequestDisPatcher ( "/message.jsp"). forward (요청, 응답);} catch (userexistException e) {formbean.geterrors (). Puted ( "username", "등록 된 사용자 ENSTS !! "); request.setAttribute ("formbean ", formbean); request.getRequestDispatcher ("/web-inf/pages/register.jsp "). Forward (요청, 응답);} catch (Exception e) {e.printstacktrace (); // 백그라운드 requiverstribute ( "메시지", "미안, 등록 실패 !!"); request.getRequestDispatcher ( "/message.jsp"). public void dopost (httpservletRequest 요청, httpervletResponse 응답);사용자가 등록 할 때 채워진 양식 데이터의 확인이 실패하면 서버는 요청 객체에 오류 메시지와 양식 데이터가있는 FormBean 객체를 저장 한 다음 register.jsp 페이지로 다시 보냅니다. 따라서 register.jsp 페이지에서 요청 객체에서 Formbean 객체를 꺼낸 다음 사용자가 작성한 양식 데이터를 해당 양식 항목에 다시 적용하고 양식 양식에서 오류가 발생할 때 프롬프트 메시지를 표시하여 사용자가 어떤 데이터를 채우는지 알 수 있습니다!
register.jsp 페이지를 수정하면 코드는 다음과 같습니다.
<%@ page language = "java"pageencoding = "utf-"%> <! doctype html> <html> <head> <title> 사용자 등록 </title> </head> <body style = "text-align : center;"> <form action = "$ {pagecontext.ruquest.context path}/servlet/servergervlet" 메소드 = "post"> <table> <td> username </td> <td> <%-el expression $ {}를 사용하여 요청 객체 (formbean.username) 및 오류 메시지 (formbean.errors.username)-%> <input type = "username" value = "$ {formbean.username}"> $ {formbean.errors.username} </td> </tr> <tr> <td> password </td> <td> <입력 유형 = "password"name = "userpwd" value = "$ {formbean.userpwd}"> $ {formbean.errors.userpwd} </td> </td> <td> 비밀번호 확인 </td> <td> <입력 유형 = "password"name = "volictpwd" value = "$ {formbean.confirmpwd}"> $ {formbean.errors.confirmpwd} </td> </td> </td> <td> email </td> <td> <입력 유형 = "text"name ""email " value = "$ {formbean.email}"> $ {formbean.errors.email} </td> </td> <tr> <td> 생일 </td> <td> <입력 유형 = "text"name = "생일" value = "$ {formbean.birthday}"> $ {formbean.errors.birthday} </td> </tr> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <input type = "value ="register "> </td> </td> </body> </body>이 시점에서 사용자 등록 기능이 개발되었습니다!
다음은 개발 된 사용자 등록 기능을 테스트합니다.
http : // localhost : 8080/webmvcframework/servlet/regis
입력 된 양식 항목이 확인 규칙을 준수하지 않으면 등록 할 수 없습니다. 작동 효과는 다음과 같습니다.
3.4.2. 로그인 기능을 개발하십시오
1. Me.gacl.web.ui 패키지 아래에 loginuiservlet을 작성하여 사용자에게 로그인 인터페이스를 제공합니다.
loginuiservlet이 사용자 요청을 받으면 login.jsp로 이동합니다.
loginuiservlet 코드는 다음과 같습니다.
package me.gacl.web.ui; import java.io.ioexception; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.httpp.httpp.http.http.http.http.http.http.http.htttp.http.http.http.http.http.http.http. javax.servlet.http.http.httpervletresponse;/*** @author gacl* loginuiservlet는 사용자를위한 로그인 인터페이스를 출력 할 책임이 있습니다* 사용자가 loginuiservlet에 액세스 할 때 login.jsp page in {public classe extends httpervlet httervlet httervlet httervle. doget (httpservletrequest 요청, httpservletreponse response)는 servletexception, ioexception {request.getRequestDispatcher ( "/web-inf/pages/login.jsp")를 던졌습니다 (요청, 응답);} public void dopost (httpserverquest 요청, httpservercence). {doget (요청, 응답);}}2. 사용자 로그인 로그인 작성/web-inf/pages/directory 아래로 로그인 .jsp 페이지
로그인 .jsp 페이지의 코드는 다음과 같습니다.
<%@ page language = "java"pageencoding = "utf-"%> <! doctype html> <html> <head> <title> 사용자 로그인 </title> </head> <body> <form action = "$ {pagecontext.Request.ContextPath}/servlet/loginservlet"method = "post"> usern "> 이름 = "사용자 이름"> <br/> 비밀번호 : <입력 유형 = "비밀번호"이름 = "비밀번호"> <br/> <입력 유형 = "제출"value = "로그인"> </form> </body> </html> <form action = "$ {pagecontext.request.contextPath}/servlet/loginservlet"method = "post"> login.jsp는 양식이 제출되어 처리를 위해 loginservlet에 전달되었음을 나타냅니다.
3. me.gacl.web.controller 패키지에서 사용자 로그인을 처리하기위한 LoginServlet 작성
loginservlet 코드는 다음과 같습니다.
package me.gacl.web.controller; import java.io.ioexception; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpervletrequest; import javax.servlet.http.httprspronge; me.gacl.domain.user; import me.gacl.service.iuserService; import me.gacl.service.impl.userserviceimpl;/*** 서블릿 핸들 사용자 로그인*@author gacl **/public class loginservlet httpservlet {httpsver void doget (httpervletrequest) servletexception, ioexception {// 사용자 문자열에 의해 채워진 로그인 사용자 이름을 얻습니다. username = request.getParameter ( "username"); // 사용자 문자열에 의해 채워진 로그인 암호를 가져옵니다. password); if (user == null) {String Message = String.format ( "죄송합니다, 사용자 이름 또는 비밀번호가 잘못되었습니다 !! 다시 로그인하십시오! 몇 초 안에 로그인 페이지로 자동 이동합니다 !! <meta http-equiv = 'Reformation'content = '; url =%s' ", request.getContextPath ()+"/servlet/loginUiServlet "); request.setAttribute ("message ", message); requestDispatcher ("/message.jsp "). 앞으로 (요청, 응답); request.getSession (). setAttribute ( "사용자", 사용자); 문자열 message = string.format ( "축하 : %s, 로그인이 성공했습니다!이 페이지는 초 안에 홈페이지로 이동합니다! user.getusername (), request.getContextPath ()+"/index.jsp"); request.setAttribute ( "message", message); request.get.getRequestDispatcher ( "/message.jsp"). public void dopost (httpervletrequest request, httpservletreconce) {doget (요청, 응답);}}이 시점에서 사용자 로그인 기능이 완료되었습니다.
아래에서 개발 된 사용자 로그인 기능을 테스트하고 URL 주소를 입력하십시오. http : // localhost : 8080/webmvcframework/servlet/loginuiservlet 로그인 .jsp 페이지에 액세스하려면 올바른 사용자 이름과 비밀번호를 입력하여 로그인하면 다음과 같습니다.
입력 한 사용자 이름과 비밀번호가 잘못된 경우 로그인을 성공적으로 로그인 할 수 없으며 작동 효과는 다음과 같습니다.
3.4.3. 취소 기능을 개발하십시오
me.gacl.web.controller 패키지에서 사용자 로그 아웃을 처리하기위한 로그 아웃 서비스를 작성하십시오.
로그 아웃 코드는 다음과 같습니다.
packing me.gacl.web.controller; import java.io.ioexception; import java.text.messageformat; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.httpervletrequest; import; javax.servlet.http.httpervletresponse; public class logoutservlet는 httpservlet {public void doget (httpservletrequest request, httpservletreponse response, httpservletreponse 응답)을 확장합니다. request.getSession (). removeAttribute ( "user"); // 문자열에는 단일 따옴표가 포함되어 있기 때문에 MessageFormat.format 메소드를 사용 하여이 경우 문자열을 스플릿으로 사용하면 문제가 발생합니다. //messageformat.format 메소드는 문자열의 단일 인용문 만 제거하고 Specified Placeholder String = MessageFormat.cormat (로그인)에서 내용을 2 위로 채우지 않을 것입니다. <meta http-equiv = 'refresh'content = '; url = {}'/> ", request.getContextPath ()+"/servlet/loginUiServlet "); system.out.println (tempStr); // output result : 성공적으로 로그 아웃! ! 몇 초 만에 로그인 페이지로 자동 이동합니다! ! <meta http-equiv = 새로 고침 content=;url={}/>System.out.println("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- content='';url={}''/>","index.jsp") can return normally * <meta http-equiv=''refresh'' content='';url=index.jsp'/>*/String tempStr = MessageFormat.format("Login successfully!! It will automatically jump to the login page in seconds!! <meta http-equiv=''refresh'' content='';url={}''/>", request.getContextPath()+"/servlet/LoginUIServlet");/*** Output result: *Login successfully! ! It will automatically jump to the login page for you in seconds! ! * <meta http-equiv='refresh' content=';url=/webmvcframework/servlet/LoginUIServlet'//System.out.println(tempStr);String message = String.format("Logout successfully!! Automatically jump to the login page in seconds!! <meta http-equiv='refresh' content=';url=%s'/>", request.getContextPath()+"/servlet/LoginUIServlet");request.setAttribute("message",message);request.getRequestDispatcher("/message.jsp").forward(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, 응답);}}用户登录成功后,会将登录的用户信息存储在session中,所以我们要将存储在session中的user删除掉,这样就可以实现用户注销了。
用户登录成功后就会跳转到index.jsp页面,在index.jsp页面中放一个【退出登陆】按钮,当点击【退出登陆】按钮时,就访问LogoutServlet,将用户注销。
index.jsp的代码如下:
<%@ page language="java" pageEncoding="UTF-"%><%--为了避免在jsp页面中出现java代码,这里引入jstl标签库,利用jstl标签库提供的标签来做一些逻辑判断处理--%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><!DOCTYPE HTML><html><head><title>首页</title><script type="text/javascript">function doLogout(){//访问LogoutServlet注销当前登录的用户window.location.href="${pageContext.request.contextPath}/servlet/LogoutServlet";}</script></head><body><h>孤傲苍狼的网站</h><hr/><c:if test="${user==null}"><a href="${pageContext.request.contextPath}/servlet/RegisterUIServlet" target="_blank">注册</a><a href="${pageContext.request.contextPath}/servlet/LoginUIServlet">登陆</a></c:if><c:if test="${user!=null}">欢迎您:${user.userName}<input type="button" value="退出登陆" onclick="doLogout()"></c:if><hr/></body></html>测试开发好的注销功能,效果如下:
到此,所有的功能都开发完成了,测试也通过了。
四、开发总结
通过这个小例子,可以了解到mvc分层架构的项目搭建,在平时的项目开发中,也都是按照如下的顺序来进行开发的:
1. 개발 환경을 구축하십시오
1.1 创建web项目
1.2 导入项目所需的开发包
1.3 创建程序的包名,在java中是以包来体现项目的分层架构的
2、开发domain
把一张要操作的表当成一个VO类(VO类只定义属性以及属性对应的get和set方法,没有涉及到具体业务的操作方法),VO表示的是值对象,通俗地说,就是把表中的每一条记录当成一个对象,表中的每一个字段就作为这个对象的属性。每往表中插入一条记录,就相当于是把一个VO类的实例对象插入到数据表中,对数据表进行操作时,都是直接把一个VO类的对象写入到表中,一个VO类对象就是一条记录。每一个VO对象可以表示一张表中的一行记录,VO类的名称要和表的名称一致或者对应。
3、开发dao
3.1 DAO操作接口:每一个DAO操作接口规定了,一张表在一个项目中的具体操作方法,此接口的名称最好按照如下格式编写:“I表名称Dao”。
├DAO接口里面的所有方法按照以下的命名编写:
├更新数据库:doXxx()
├查询数据库:findXxx()或getXxx()
3.2 DAO操作接口的实现类:实现类中完成具体的增删改查操作
├此实现类完成的只是数据库中最核心的操作,并没有专门处理数据库的打开和关闭,因为这些操作与具体的业务操作无关。
4、开发service(service 对web层提供所有的业务服务)
5、开发web层
以上内容是小编给大家介绍的JavaWeb实现用户登录注册功能实例代码(基于Servlet+JSP+JavaBean模式),希望对大家有所帮助!