방금 최근에 SpringMVC 프레임 워크를 배웠으며 실제로 훨씬 더 편리하고 많은 중복 코드를 줄인다 고 생각합니다. 나는 연습하기 위해 작은 프로젝트를했다. 기본 SpringMVC 응용 프로그램 프로젝트입니다. mybatis는 사용되지 않습니다. 프로젝트 기능은 상당히 완료되며 추가, 삭제, 수정 및 검색의 기본 기능이 실현됩니다.
프로젝트 환경 :
-시스템 : Win10
-개발 환경 : eclipseoxygenreleasecandidate3 (4.7)
-jdk 버전 : Java1.8 (121)
-mysql : 5.7
-스프링 : 4.0
-TOMCAT : 8.5
사용 된 기술 :
springmvcspringjspjdbcjavabeanjsjstl
액세스 주소 : http : // localhost : 8080/프로젝트 이름/모두
성명서 : 방금 시작한 초보자 일 뿐이며 필연적으로 내가 쓴 코드에 오류가 있습니다. 당신이 그것을 찾으면, 그것을 지적하십시오, 모두 감사합니다.
자세한 프로세스는 아래에 게시됩니다
1. 먼저 웹 프로젝트 생성 (DynamicWebProject)
나는 프로젝트 이름을 직접 썼습니다
2. 이것은 완성 된 프로젝트 구조입니다
방금 함수를 사용했는데 인터페이스를 사용하지 않았습니다. 3 개의 간단한 클래스, Bean 패키지 아래의 엔티티 클래스, DAO 계층 데이터베이스 액세스 클래스 및 컨트롤러 계층의 인터페이스 제어 클래스 만 사용했습니다.
참조 된 모든 JAR 패키지는/WebContent/Web-Inf/Lib 폴더에 있으며 일반적인 Java 프로젝트와 다릅니다.
3. 특정 Java 코드
1. 학생 수업, 엔티티 클래스는 먼저 Javabean을 작성해야합니다. 내 것은 Javabean으로 학생입니다. 자세한 코드는 다음과 같습니다.
패키지 Bean; 공개 클래스 학생 {개인 정수 ID; // 학생 ID 개인 문자열 이름; // 학생 이름 Private Double Javascore; // Java 점수 개인 Double HtmlScore; // HTML 점수 개인 CSSSCORE; // CSS 점수 개인 이중 총체; 공개 정수 getId () {return id; } public void setId (정수 ID) {this.id = id; } public String getName () {return name; } public void setName (문자열 이름) {this.name = 이름; } public double getjavascore () {return javascore; } public void setjavascore (Double Javascore) {this.javascore = Javascore; } public double gethtmlscore () {return htmlscore; } public void sethtmlscore (double htmlscore) {this.htmlscore = htmlscore; } public double getcssscore () {return cssscore; } public void setcssscore (double cssscore) {this.cssscore = cssscore; } public double getTotalScore () {return totalscore; } public void settoTalscore (Double TotalScore) {this.totalscore = TotalScore; }}2. 학생 DAO, 데이터베이스 액세스 작업 클래스는 DAO 계층의 코드, 즉 데이터 액세스 계층입니다. 다음은 Spring (JDBCTEMPLATE)이 캡슐화 한 클래스입니다. 여기에는 데이터베이스 작동 방법이 포함되어 있습니다. 스스로 반복 된 코드를 많이 쓸 필요는 없으며 SQL 문을 작성하십시오. 특정 코드는 다음과 같습니다.
패키지 dao; import java.sql.resultset; import java.sql.sqlexception; import java.sql.types; import java.util.list; import org.spramframework.jdbc.core.jdbctemplate; import org.spramepramework.core.core.core.core.core.core.core.core.core.core.core.core.core.core.core.core.core.core. StudentDao { / ** * @fields jdbctemplate : todo * / private jdbctemplate jdbctemplate; / ** * 스프링에 의해 제공된 클래스 * * @param jdbctemplate * 반환 값 유형 : void * @author janinus */ public void setjdbctemplate (jdbctemplate jdbctemplate) {this.jdbctemplate = jdbctemplate; } / ** * 모든 학생 쿼리 * * @return 반환 값 유형 : List <tudent> * @author janinus * / public list <tudent> QueryAll () {String sql = "select id, name, javascore, htmlscore, cssscore"; // 쿼리 결과를 학생 클래스에 매핑하고 목록에 추가 한 다음 return jdbctemplate.query (sql, new StudentMapper ()); } / ** * 이름으로 쿼리 * * @param name * @return return value 유형 : list <student> * @author janinus * / public list <tudent> querybyname (string name) {string sql = "select id, name, javascore, htmlscore, '%' + name +"%' "; return jdbctemplate.query (sql, new Studentmapper ()); } / ** * 학생 추가 * * @param 학생 * @return 반환 가치 유형 : Boolean * @author janinus * / public boolean addstu (학생 학생) {String SQL = "학생 (ID, 이름, Javascore, HtmlScore, cssscore) 값 (0,?,?,?)에 삽입하십시오. return jdbctemplate.update (sql, new Object [] {whitity.getname (), whiting.getjavascore (), withle.gethtmlscore (), without.getcssscore ()}, new int [] {type.varchar, type.double, types.double, type.double, types.double}) == 1; } / ** * 학생 삭제 * * @param id * @return 반환 값 유형 : boolean * @author janinus * / public boolean deletestu (정수 ID) {String sql = "id =??"; jdbctemplate.update (sql, id) == 1; } / ** * 학생 정보 업데이트 * * @param 학생 * @return 반환 가치 유형 : boolean * @author janinus * / public boolean updatestu (학생 student) {문자열 sql = "업데이트 학생 세트 이름 =?, javascore =?, htmlscore =?, cssscore =?"; Object stuobj [] = new Object [] {student.getName (), whiting.getJavascore (), whiting.gethtmlScore (), whening.getCssScore (), withy.getId ()}; jdbctemplate.update (sql, stuobj) == 1; } / ** * 상위 N 학생의 총 점수를 반환 * * @param num * @return return value 유형 : list <tudent> * @author janinus * / public list <tudent> topnum (int num) {int num) {string sql = "select id, name, javascore+htmlscore+cssscore+htmlscore+cssscore desc+cssscore desc. return jdbctemplate.query (sql, new rowmapper <student> () {@override public student maprow (restet rs, int rownum) 던지기 sqlexception {// todo auto-autoceated method student student = new student (); student.setid (rs.getint (1)); Student.setName (2)); student.settotalscore (Rs.getDouble (3)); } / ** * * StudentMapper 데이터베이스 매핑 * * @ClassName StudentMapper * @Author Janinus * @Date 2017 년 6 월 27 일 * @version v1.0 * / class StudentMapper Implements rowMapper <tudent> {@Override public student maprow (resto rs, int rownum) sqlexcection {// to a auto gender encception (); student.setid (rs.getint (1)); Student.SetName (Rs.GetString (2)); Student.setjavascore (Rs.getDouble (3)); 학생 .sethtmlscore (rs.getDouble (4)); Student.setcssScore (Rs.getDouble (5)); 반품 학생; }}}3. StudentController, 프론트 엔드 상호 작용 클래스는 최종적으로 사용자 상호 작용과 관련된 Control Layer StudentController 클래스입니다. 이 클래스는 주로 프론트 엔드와 백엔드를 결합하여 완전한 상호 작용을 달성하는 데 사용됩니다. 특정 코드는 다음과 같습니다.
패키지 컨트롤러; import org.springframework.context.applicationcontext; import org.springframework.context.support.classpathxmlapplicationcontext; import org.spramework.stereotyp.controller; import org.springframework.ui.model; import org.springframework.web.bind.annotation.requestmapping; import bean.student; import dao.studentdao; @controllerpublic 클래스 StudentController { /** * * 데이터베이스에서 모든 학생 정보를 가져 와서 홈 페이지 인덱스, jsp * * @param model * /@param model * /@author anime * /@author. @requestmapping (value = "/all") public String QueryAll (모델 모델) {ApplicationContext Context = new ClassPathXmlApplicationContext ( "ApplicationContext.xml"); // get dao studentdao dao = (windentDao) context.getBean ( "dao"); model.addattribute ( "학생", dao.queryall ()); model.addattribute ( "tops", dao.topnum (3)); "index.jsp"를 반환합니다. }/** * 이름으로 학생을 찾고, 퍼지 검색을 사용하고, 결과를 index.jsp * * @param model * @param model * @return return value 유형으로 반환합니다 : string * @author janinus */@requestmapping (value = "/querybyname") public string querybyname (문자열 이름, 모델 모델) classPathXmlApplicationContext ( "ApplicationContext.xml"); // IOC 컨테이너에서 DAO를 얻습니다. StudentDao dao = (StudentDao) context.getBean ( "dao"); model.addattribute ( "학생", dao.querybyname (name)); model.addattribute ( "tops", dao.topnum (3)); "index.jsp"를 반환합니다. }/** * 새 학생 추가 및 모든 페이지로 결과를 홈 페이지로 전달한 모든 페이지에 결과를 반환합니다. * @param name * @param javascore * @param htmlscore * @param cssscore * @param model * @return return value type : string * @author janinus */ @valuequestmapping (value = "") public string (string javascore, string javascore, string). htmlScore, String CssScore, 모델 모델) {ApplicationContext context = new ClassPathXmlApplicationContext ( "ApplicationContext.xml"); StudentDao dao = (StudentDao) context.getBean ( "dao"); 학생 학생 = 신입생 (); 학생 .setName (이름); Student.setjavascore (Double.parsedouble (Javascore)); 학생 .sethtmlscore (double.parsedouble (htmlscore)); Student.setcssScore (Double.parsEdouble (CSSSCORE)); 부울 결과 = dao.addstu (학생); if (result) model.addattribute ( "msg", "<cript> alert ( 'successly!') </script>"); else model.addattribute ( "msg", "<cript> alert ( 'successly!') </script>"); "모두"를 반환합니다. }/** * id * @param id * @param model * @param value 유형 : string * @author janinus */@requestmapping (value = "/deletebyid") public string deletebyid (String id, model model) {ApplicationContext context = new classpathxmlapplicationContext ( "ApplicationContxt.xml"); StudentDao dao = (StudentDao) context.getBean ( "dao"); 부울 결과 = dao.deletestu (integer.parseint (id)); if (result) model.addattribute ( "msg", "<cript> alert ( 'Delte Delete!') </script>"); else model.addattribute ( "msg", "<cript> alert ( 'delte delete!') </script>"); "모두"를 반환합니다. }/** * * @param id * @param name * @param javascore * @param htmlscore * @param cssscore * @param model * @return return value 유형 : string * @author janinus */@requestmapping (value = "/update") public string updatestu (String id, String jav jav jav jav javscore, string htmlscore,, string css) {ApplicationContext context = new ClassPathXmlApplicationContext ( "ApplicationContext.xml"); StudentDao dao = (StudentDao) context.getBean ( "dao"); 학생 학생 = 신입생 (); student.setid (integer.parseint (id)); 학생 .setName (이름); Student.setjavascore (Double.parsedouble (Javascore)); 학생 .sethtmlscore (double.parsedouble (htmlscore)); Student.setcssScore (Double.parsEdouble (CSSSCORE)); 부울 결과 = dao.updatestu (학생); if (result) model.addattribute ( "msg", msg ( "modified success")); else model.addattribute ( "msg", msg ( "수정 실패")); "모두"를 반환합니다. }/** * 페이지 팝업 * @param msg * @return return value 유형 : string * @author janinus */public string msg (String msg) {return "<cript> alert ( '" + msg + ") </script>"; }}모든 Java 코드가 완료되었으며 특정 XML 구성 및 프론트 엔드 페이지 만 아래에 남아 있습니다.
4. 프론트 엔드 페이지
간단한 작은 프로젝트이므로 내 JS와 CSS는 모두 같은 페이지에 있으며 분리되지 않은 두 페이지 만 있습니다.
1. index.jsp
홈페이지, 스크린 샷
편집하다
자세한 코드 :
<%@ page language = "java"contmenttype = "text/html; charset = utf-8"pageencoding = "utf-8"%> <%@ taglib prefix = "fn"uri = "http://java.sun.com/jsp/jstl/functions"%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %> <! doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title> 학생 관리 </title> </head> <style type = "text/css"> body {text- align : centre em; } .all {너비 : 40%; 마진 : 20px 100px; 텍스트 정렬 : 센터; 높이 : 300px; 플로트 : 왼쪽; } 표 {너비 : 80%; 마진 : 20px 자동; 글꼴 크기 : 14px; 오버플로 : 자동; } #tab02 {너비 : 80%; 마진 : 20px 자동; 글꼴 크기 : 14px; } 표 TH, 표 TD {Border-Bottom : 1PX #000 SOLID; 라인 높이 : 23px; } #edit_comm {너비 : 500px; 마진 : 20px 자동; 왼쪽 경계 : 3px 고체 #000; 디스플레이 : 없음; } #add_comm {너비 : 500px; 마진 : 20px 자동; 왼쪽 경계 : 3px 고체 #000; } #all_comm {높이 : 600px; } .edit_stu {너비 : 200px; 높이 : 30px; 배경 : #fff; Font-Family : "Microsoft Ya Black Light", "Arial Black"; 글꼴 크기 : 18px; 국경 : 없음; 국경 바닥 : 1px 고체 #000; 마진 : 20px 10px; } </style> <script src = "http://code.jquery.com/jquery-latest.js"> </script> <script type = "text/javaScript"> $ (function () {$ ( "#cancel"). click (function () {$ ( "#add_comm"). }) $ ( "input"). addClass ( "edit_stu"); repush () {window.location.href = "all"= "external nofollow"rel = "external nofollow"; } 함수 add_reg () {var name = $ ( "#add_edit_name"). val (); var javascore = $ ( "#add_edit_java"). val (); var htmlScore = $ ( "#add_edit_html"). val (); var cssscore = $ ( "#add_edit_css"). val (); var namenot = name! = null && name! = ''; var javascorenot = javascore! = null && javascore! = ''; var htmlscorenot = htmlscore! = null && htmlscore! = ''; var cssscorenot = cssscore! = null && cssscore! = ''; if (namenot & javascorenot && htmlscorenot && cssscorenot) true; 그렇지 않으면 거짓을 반환합니다. } function delete_stu (id) {var result = 확인 ( "삭제 되었습니까?"); if (result) window.location.href = "deleteById? id ="rel = "external nofollow" +id; } 함수 edit_stu (id) {var name = $ ( "#name"+id) .text (); var java = $ ( "#java"+id) .text (); var html = $ ( "#html"+id) .text (); var css = $ ( "#css"+id) .text (); $ ( "#edit_id"). val (id); $ ( "#edit_name"). val (이름); $ ( "#edit_java"). val (java); $ ( "#edit_html"). val (html); $ ( "#edit_css"). val (css); $ ( "#add_comm"). fadeout (); $ ( "#edit_comm"). fadein (); . <td> css score </td> <td> 운영 </td> </td> </tr> <c : foreach items = "$ {whitod}"var = "student"> <td> <td id = "id $ {student.id}"> $ {student.id} </td> <td id = "studl}"> $ {$ {studl} " <td id = "java $ {student.id}"> $ {student.javascore} </td> <td id = "html $ {withle.id}"> $ {without.htmlscore} </td> <td id = "css $ {student.id}"> $} </td>} </td>} onclick = "delete_stu ($ {whient.id})"> delete </a> | <a onclick = "edit_stu ($ {wiching_stu ($ {wiching.id})"> edit </a> </td> </tr> </c : foreach> </table> <tab02 "> <h2> Top </h2> <tr> <td> <td> <td> id </td> <td> name </td> <td> 총 점수 </td> </tr> <c : foreach items = "$ {tops}"var = "student"varstatus = "i"> <tr> <td> $ {i.index+1} name </td> <td id = "id $} t} t. . <h2> indin </h2> <form action = "querybyname"method = "post"> <input type = "text"placeholder = "student name"name = "name"> <input type = "value ="value = "value"> </form> <h2 id = "edit_title"> ad add "> <input" "텍스트". 이름 "이름" /> <입력 유형 = "텍스트"자리 표시기 = "java score"name = "javascore" /> <input type = "text"placeholder = "html score"name = "htmlscore" /> <입력 유형 = "텍스트"css score "name ="cssscore "는"csssscore "를 확인합니다. </form> </div> <div id = "edit_comm"> <h2 id = "edit_title"> 편집 학생 </h2> <form action = "update"method = "post"> <input type = "text"placeholder = "id는"id = "edit_id"name = "id"value = "readonly ="is "readonly ="is "id"id " type = "text"placeholder = "학생 이름"id = "edit_name"name = "name" /> <input type = "text"placeholder = "java score"id = "edit_java"name = "javascore"> <input type = "text"placeholder = "html score"id = "edit_html"name = "htmlscore" / / / /> 자리 표시기 = "CSS 스코어"ID = "edit_css"이름 = "CSSSCore"/> <입력 유형 = "제출"value = "수정 확인"/> <입력 유형 = "버튼"value = "취소 수정"/> </form> </div> </body> </html>2. login.jsp
<%@ page language = "java"contmenttype = "text/html; charset = utf-8"pageencoding = "utf-8"%> <! doctype html public "-// w3c // dtml 4.01 Transitional // en" "http://www.w3.org/tr/tr/html4/loose.dtd"> html> html> http-tequiv ="content-type "content ="text/html; charset = utf-8 "> <title> insert </head> <hre <href =" "" "" "" "" "" "" rel = "외부 nofollow"rel = "외부 nofollow"> 홈페이지를 입력하십시오 </a> </h1> </body> </html>
5. 자세한 파일 구성
1. ApplicationContext.xml
이것은 종속성 주입을 구현하는 데 사용되는 Spring의 IOC 컨테이너의 구성 파일입니다. 다음은 특정 코드입니다.
<? 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 : "http://www.springframework.org/schema/tx"xmlns : aop = "http://www.springframwork.org/schema/op" xsi : schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.xsd http://www.springframework.org/schema/contet http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd "default-autowire ="byname "default-lazy-init ="true ">-database data councor-<bean id ="id id = "id id eource"> 클래스-> <property name = "driver className"value = "com.mysql.jdbc.driver"> </property> <!-데이터베이스 액세스 주소-> <property name = "url"value = "jdbc : mysql : // localhost : 3306/test"> </propert> <!-Database Access User Name-> vaction ""> <!-데이터베이스 액세스 암호-> <속성 이름 = "property name"value = "123123"> </property> </bean> <!-스프링으로 제공되는 데이터베이스 트랜잭션 관리-> <bean id = "txmanager"> <property name = "dataSource"ref = "dataSource"> </property> </bean> <tx : transaction-drives infiven-mmanager = "txmanager". Javabean Entity Class-> <Bean id = "StudentBean"> <!-속성 자동 구성-> </bean> <!-데이터베이스 액세스 작업 클래스 스프링-> <bean id = "jdbctemplate"> </bean> <!-dao layer class-> <bean id = "dao"> <속성 이름 = "dao"ref = "dao"> </property> </bean> </beans>
2. SpringMVC-Servlet.xml, Spring MVC 구성 클래스,
우리는 대부분의 서블릿 코드를 구현했으며 비즈니스 구현 만 작성하면됩니다. 아래는 특정 코드입니다
<? 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 : p = "http://www.springframework.org/schema/p"xmlns : context = "http://www.springframework.org/schema/context"xsi : schemalocation = "http://www.springfrfringext.org/schema/schema/schema/schema/schema/schema http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3 지정된 패키지 아래의 클래스-> <context : component-scan base-package = "컨트롤러" /> < /beans>
3. web.xml
이것은 웹 프로젝트의 구성 파일이며 다음은 주요 코드입니다.
<? xml version = "1.0"encoding = "utf-8"?> <web-app xmlns = "http://java.sun.com/xml/ns/javaee"xmlns : xsi = "http://ww.w.w3.org/2001/xmlschema-instance" xsi : schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><! <filter-name> encodingFilter </filter-name> <filter-class> org.springframework.web.filter.characterencterencododingfilter </filter-class> <init-param> <param-name> encoding </param-name> <param- value> utf -8 </init-param> </init-param> </init-param> <! 인터페이스-> <welcome-file-list> <welcome-file>/all </welcome-file> <welcome-file> index.html </welcome-file> index.htm.htm.htm </welcome-file-list> <!-springmvc servlet-> <servlet> <servlet-name> springmvc </servvc </servvc </servvc </servvc </servvc </servvc </servvc </servvc </servvc </servvc </servvc </servvc </servvc </servvc </servvc </servvc <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-pattern>/</url-pattern> </servlet-mapping>
6. 프로젝트 요약 및 부록
이 프로젝트는 나의 일일 연습 프로그램입니다. 더 능숙하기 위해, 나는 완전한 과정을 다시 검토하고 그것에 대해 많이 익숙해졌습니다.
프로젝트에 사용되는 JAR 패키지에 대한 부록 :
스프링 패키지 외에도 MySQL-JBDC JAR 패키지 및 JSTL JAR 패키지도 있습니다.
주소 다운로드 :
Spring Framework Jar 패키지 (선택적 버전) : Spring 공식 웹 사이트
mysql-jdbc.jar (선택 버전) : mysql 공식 웹 사이트
jstl.jar (선택 버전) : Maven 공식 주소
위는 MySQL 데이터베이스의 추가, 삭제, 수정 및 검색을 구현하는 Spring MVC의 전체 예제에 대한이 기사의 전체 내용입니다. 모든 사람에게 도움이되기를 바랍니다. 관심있는 친구들은이 사이트를 계속 참조 할 수 있습니다.
스프링에서 웹 모듈 구성에 대한 자세한 설명
SpringMVC REST 스타일 소개 및 구현 코드 예제
SpringMVC 인터셉터는 단일 사인온을 구현합니다
단점이 있으면 메시지를 남겨 두십시오. 이 사이트를 지원해 주신 친구들에게 감사드립니다!