最近剛學了springmvc框架,感覺確實方便了不少,減少了大量的冗余代碼。就自己做了個小項目練練手,這是個初級的springmvc應用的項目,沒有用到mybatis,項目功能還算完善,實現了基本的增刪改查的功能。
項目環境:
-系統:win10
-開發環境:eclipseoxygenreleasecandidate3(4.7)
-jdk版本:java1.8(121)
-mysql:5.7
-spring:4.0
-tomcat:8.5
用到的技術:
springmvcspringjspjdbcjavabeanjsjstl
訪問地址:http://localhost:8080/你的項目名/all
聲明:我只是一個剛入門不久的新手,所寫代碼難免有出錯之處,如發現歡迎各位指出,謝謝大家。
下面就貼上詳細過程
1.首先創建一個web項目(dynamicwebproject)
項目名字就自己寫了,不再詳細寫
2. 這是我的已完成項目結構
我只是為了實現功能,沒有用到接口,只用了簡單的三個類,bean包下的實體類,dao層數據庫訪問類,controller層的界面控制類,
所有引用的jar包都在/webcontent/web-inf/lib文件夾下,這點與普通的java項目不同。
3. 具體java代碼
1.student類,實體類 首先要寫一個javabean,我的是student作為javabean,詳細代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
package bean; public class student { private integer id; //學生id private string name; //學生姓名 private double javascore; //java成績 private double htmlscore; //html成績 private double cssscore; //css成績 private double totalscore; public integer getid() { return id; } public void setid(integer id) { this .id = id; } public string getname() { return name; } public void setname(string name) { this .name = 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. studentdao,數據庫訪問操作類 然后是dao層即數據訪問層的代碼,這里使用的是spring封裝的一個類(jdbctemplate),里面有一些操作數據庫的方法,不用再自己寫大量重復代碼,只要寫sql語句。下面是具體代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
|
package dao; import java.sql.resultset; import java.sql.sqlexception; import java.sql.types; import java.util.list; import org.springframework.jdbc.core.jdbctemplate; import org.springframework.jdbc.core.rowmapper; import bean.student; public class studentdao { /** * @fields jdbctemplate : todo */ private jdbctemplate jdbctemplate; /** * spring提供的類 * * @param jdbctemplate * 返回值類型: void * @author janinus */ public void setjdbctemplate(jdbctemplate jdbctemplate) { this .jdbctemplate = jdbctemplate; } /** * 查詢所有學生 * * @return 返回值類型: list<student> * @author janinus */ public list<student> queryall() { string sql = "select id,name,javascore,htmlscore,cssscore from student" ; //將查詢結果映射到student類中,添加到list中,并返回 return jdbctemplate.query(sql, new studentmapper()); } /** * 通過姓名查詢 * * @param name * @return 返回值類型: list<student> * @author janinus */ public list<student> querybyname(string name) { string sql = "select id,name,javascore,htmlscore,cssscore from student where name like '%" + name + "%'" ; return jdbctemplate.query(sql, new studentmapper()); } /** * 添加學生 * * @param student * @return 返回值類型: boolean * @author janinus */ public boolean addstu(student student) { string sql = "insert into student(id,name,javascore,htmlscore,cssscore) values(0,?,?,?,?)" ; return jdbctemplate.update(sql, new object[] { student.getname(), student.getjavascore(), student.gethtmlscore(), student.getcssscore() }, new int [] { types.varchar, types. double , types. double , types. double }) == 1 ; } /** * 刪除學生 * * @param id * @return 返回值類型: boolean * @author janinus */ public boolean deletestu(integer id) { string sql = "delete from student where id = ?" ; return jdbctemplate.update(sql, id) == 1 ; } /** * 更新學生信息 * * @param student * @return 返回值類型: boolean * @author janinus */ public boolean updatestu(student student) { string sql = "update student set name=? ,javascore=?,htmlscore = ? ,cssscore = ? where id = ?" ; object stuobj[] = new object[] { student.getname(), student.getjavascore(), student.gethtmlscore(), student.getcssscore(), student.getid() }; return jdbctemplate.update(sql, stuobj) == 1 ; } /** * 返回總成績前n名學生 * * @param num * @return 返回值類型: list<student> * @author janinus */ public list<student> topnum( int num) { string sql = "select id,name,javascore+htmlscore+cssscore from student order by javascore+htmlscore+cssscore desc ,name asc limit ?" ; return jdbctemplate.query(sql, new rowmapper<student>() { @override public student maprow(resultset rs, int rownum) throws sqlexception { // todo auto-generated method stub student student = new student(); student.setid(rs.getint( 1 )); student.setname(rs.getstring( 2 )); student.settotalscore(rs.getdouble( 3 )); return student; } }, num); } /** * * studentmapper數據庫映射 * * @classname studentmapper * @author janinus * @date 2017年6月27日 * @version v1.0 */ class studentmapper implements rowmapper<student> { @override public student maprow(resultset rs, int rownum) throws sqlexception { // todo auto-generated method stub student student = new student(); student.setid(rs.getint( 1 )); student.setname(rs.getstring( 2 )); student.setjavascore(rs.getdouble( 3 )); student.sethtmlscore(rs.getdouble( 4 )); student.setcssscore(rs.getdouble( 5 )); return student; } } } |
3. studentcontroller ,前后端交互類 最后是與用戶交互有關的控制層studentcontroller類,這個類主要用來將前后端聯合,實現完整的交互。下面是具體代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
|
package controller; import org.springframework.context.applicationcontext; import org.springframework.context.support.classpathxmlapplicationcontext; import org.springframework.stereotype.controller; import org.springframework.ui.model; import org.springframework.web.bind.annotation.requestmapping; import bean.student; import dao.studentdao; @controller public class studentcontroller { /** * * 從數據庫中獲取全部學生信息,將數據返回給主頁index,jsp * * @param model * @return 返回值類型: string * @author janinus */ @requestmapping (value = "/all" ) public string queryall(model model) { applicationcontext context = new classpathxmlapplicationcontext( "applicationcontext.xml" ); //從ioc容器中獲取dao studentdao dao = (studentdao) context.getbean( "dao" ); model.addattribute( "students" , dao.queryall()); model.addattribute( "tops" , dao.topnum( 3 )); return "index.jsp" ; } /** * 通過姓名查找學生,使用模糊查找,將結果返回給index.jsp * * @param name * @param model * @return 返回值類型: string * @author janinus */ @requestmapping (value = "/querybyname" ) public string querybyname(string name, model model) { applicationcontext context = new classpathxmlapplicationcontext( "applicationcontext.xml" ); //從ioc容器中獲取dao studentdao dao = (studentdao) context.getbean( "dao" ); model.addattribute( "students" , dao.querybyname(name)); model.addattribute( "tops" , dao.topnum( 3 )); return "index.jsp" ; } /** * 添加新學生,并將結果返回給all頁面,由all轉發到主頁 * @param name * @param javascore * @param htmlscore * @param cssscore * @param model * @return 返回值類型: string * @author janinus */ @requestmapping (value = "/add" ) public string addstu(string name, string javascore, string htmlscore, string cssscore, model model) { applicationcontext context = new classpathxmlapplicationcontext( "applicationcontext.xml" ); studentdao dao = (studentdao) context.getbean( "dao" ); student student = new student(); student.setname(name); student.setjavascore( double .parsedouble(javascore)); student.sethtmlscore( double .parsedouble(htmlscore)); student.setcssscore( double .parsedouble(cssscore)); boolean result = dao.addstu(student); if (result) model.addattribute( "msg" , "<script>alert('添加成功!')</script>" ); else model.addattribute( "msg" , "<script>alert('添加成功!')</script>" ); return "all" ; } /** * 通過id刪除學生 * @param id * @param model * @return 返回值類型: string * @author janinus */ @requestmapping (value = "/deletebyid" ) public string deletebyid(string id, model model) { applicationcontext context = new classpathxmlapplicationcontext( "applicationcontext.xml" ); studentdao dao = (studentdao) context.getbean( "dao" ); boolean result = dao.deletestu(integer.parseint(id)); if (result) model.addattribute( "msg" , "<script>alert('刪除成功!')</script>" ); else model.addattribute( "msg" , "<script>alert('刪除成功!')</script>" ); return "all" ; } /** * * @param id * @param name * @param javascore * @param htmlscore * @param cssscore * @param model * @return 返回值類型: string * @author janinus */ @requestmapping (value = "/update" ) public string updatestu(string id, string name, string javascore, string htmlscore, string cssscore, model model) { applicationcontext context = new classpathxmlapplicationcontext( "applicationcontext.xml" ); studentdao dao = (studentdao) context.getbean( "dao" ); student student = new student(); student.setid(integer.parseint(id)); student.setname(name); student.setjavascore( double .parsedouble(javascore)); student.sethtmlscore( double .parsedouble(htmlscore)); student.setcssscore( double .parsedouble(cssscore)); boolean result = dao.updatestu(student); if (result) model.addattribute( "msg" , msg( "修改成功" )); else model.addattribute( "msg" , msg( "修改失敗" )); return "all" ; } /** * 要彈出的頁面消息 * @param msg * @return 返回值類型: string * @author janinus */ public string msg(string msg) { return "<script>alert('" + msg + "')</script>" ; } } |
所有的java代碼已經完成,下面只剩下具體的xml配置和前端頁面。
4.前端頁面
由于是一個簡單的小項目,我的js,css都在同一個頁面,沒有分開,只有兩個頁面,
1.index.jsp
主頁,截圖
編輯
詳細代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
|
<%@ page language= "java" contenttype= "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: center; } .all{ width: 40 %; margin: 20px 100px; text-align: center; height: 300px; float : left; } table{ width: 80 %; margin: 20px auto; font-size: 14px; overflow: auto; } #tab02{ width: 80 %; margin: 20px auto; font-size: 14px; } table th,table td{ border-bottom: 1px # 000 solid; line-height: 23px; } #edit_comm{ width: 500px; margin: 20px auto; border-left: 3px solid # 000 ; display: none; } #add_comm{ width: 500px; margin: 20px auto; border-left: 3px solid # 000 ; } #all_comm{ height:600px; } .edit_stu{ width:200px; height: 30px; background: #fff; font-family: "微軟雅黑 light" , "arial black" ; font-size: 18px; border: none; border-bottom: 1px solid # 000 ; margin: 20px 10px; } </style> <script src= "http://code.jquery.com/jquery-latest.js" ></script> <script type= "text/javascript" > $(function(){ $( "#cancel" ).click(function(){ $( "#add_comm" ).fadein(); $( "#edit_comm" ).fadeout(); }) $( "input" ).addclass( "edit_stu" ); }) function refush(){ window.location.href= "all" rel= "external nofollow" rel= "external nofollow" ; } function 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) return true ; else return false ; } function delete_stu(id){ var result = confirm( "是否刪除?" ); if (result) window.location.href= "deletebyid?id=" rel= "external nofollow" +id; } function 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(name); $( "#edit_java" ).val(java); $( "#edit_html" ).val(html); $( "#edit_css" ).val(css); $( "#add_comm" ).fadeout(); $( "#edit_comm" ).fadein(); } </script> <body> ${msg } <h1 align= "center" >學生管理</h1> <div id= "all_comm" class = "all" > <h2>所有學生</h2> <table id= "items" > <tr> <td>id</td> <td>名稱</td> <td>java分數</td> <td>html分數</td> <td>css分數</td> <td>操作</td> </tr> <c:foreach items= "${students }" var= "student" > <tr> <td id= "id${student.id }" >${student.id }</td> <td id= "name${student.id }" >${student.name }</td> <td id= "java${student.id}" >${student.javascore }</td> <td id= "html${student.id }" >${student.htmlscore }</td> <td id= "css${student.id}" >${student.cssscore }</td> <td ><a onclick= "delete_stu(${student.id})" >刪除</a>|<a onclick= "edit_stu(${student.id})" >編輯</a></td> </tr> </c:foreach> </table> <table id= "tab02" > <h2>前三名</h2> <tr> <td>排名</td> <td>id</td> <td>姓名</td> <td>總分數</td> </tr> <c:foreach items= "${tops }" var= "student" varstatus= "i" > <tr> <td>第${i.index+ 1 }名</td> <td id= "id${student.id }t" >${student.id }</td> <td>${student.name }</td> <td id= "name${student.id }t" >${student.totalscore }</td> </tr> </c:foreach> </table> 如不顯示請:<a onclick= "refush()" >點此刷新</a> </div> <div id= "add_comm" class = "all" > <h2>查找學生</h2> <form action= "querybyname" method= "post" > <input type= "text" placeholder= "學生姓名" name= "name" > <input type= "submit" value= "查找學生" > </form> <h2 id= "edit_title" >添加學生</h2> <form action= "add" method= "post" > <input type= "text" placeholder= "學生姓名" name= "name" /> <input type= "text" placeholder= "java成績" name= "javascore" /> <input type= "text" placeholder= "html成績" name= "htmlscore" /> <input type= "text" placeholder= "css成績" name= "cssscore" /> <input type= "submit" value= "確定添加" /> </form> </div> <div id= "edit_comm" class = "all" > <h2 id= "edit_title" >編輯學生</h2> <form action= "update" method= "post" > <input type= "text" placeholder= "要修改的id為" id= "edit_id" name= "id" value= "要修改的id為" readonly= "readonly" /><br> <input type= "text" placeholder= "學生姓名" id= "edit_name" name= "name" /> <input type= "text" placeholder= "java成績" id= "edit_java" name= "javascore" > <input type= "text" placeholder= "html成績" id= "edit_html" name= "htmlscore" /> <input type= "text" placeholder= "css成績" id= "edit_css" name= "cssscore" /> <input type= "submit" value= "確定修改" /> <input type= "button" value= "取消修改" id= "cancel" class = "edit_stu" /> </form> </div> </body> </html> |
2. login.jsp
1
2
3
4
5
6
7
8
9
10
11
12
|
<%@ page language= "java" contenttype= "text/html; charset=utf-8" pageencoding= "utf-8" %> <!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd" > <html> <head> <meta http-equiv= "content-type" content= "text/html; charset=utf-8" > <title>insert title here</title> </head> <body> <h1 align= "center" ><a href= "all" rel= "external nofollow" rel= "external nofollow" >進入主頁</a></h1> </body> </html> |
5. 詳細文件配置
1. applicationcontext.xml
這是spring的ioc容器的配置文件,用來實現依賴注入,下面是具體代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
<?xml version= "1.0" encoding= "utf-8" ?> <beans xmlns= "http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/xmlschema-instance" xmlns:context= "http://www.springframework.org/schema/context" xmlns:tx= "http://www.springframework.org/schema/tx" xmlns:aop= "http://www.springframework.org/schema/aop" xsi:schemalocation="http: //www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http: //www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http: //www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd" default -autowire= "byname" default -lazy-init= "true" > <!--數據庫數據源配置--> <bean id= "datasource" class = "org.springframework.jdbc.datasource.drivermanagerdatasource" > <!--加載驅動類--> <property name= "driverclassname" value= "com.mysql.jdbc.driver" ></property> <!--數據庫訪問地址--> <property name= "url" value= "jdbc:mysql://localhost:3306/test" ></property> <!--數據庫訪問用戶名--> <property name= "username" value= "root" ></property> <!--數據庫訪問密碼--> <property name= "password" value= "123123" ></property> </bean> <!-- spring 提供的數據庫事務管理 --> <bean id= "txmanager" class = "org.springframework.jdbc.datasource.datasourcetransactionmanager" > <property name= "datasource" ref= "datasource" ></property> </bean> <tx:annotation-driven transaction-manager= "txmanager" /> <!-- 配置javabean實體類 --> <bean id= "studentbean" class = "bean.student" > <!--屬性自動配置 --> </bean> <!--spring提供的數據庫訪問操作類 --> <bean id= "jdbctemplate" class = "org.springframework.jdbc.core.jdbctemplate" ></bean> <!-- dao層類 --> <bean id= "dao" class = "dao.studentdao" ></bean> <!-- 控制層類 ,這個配置無效--> <bean id= "controller" class = "controller.studentcontroller" > <property name= "dao" ref= "dao" ></property> </bean> </beans> |
2. springmvc-servlet.xml,spring mvc配置類,
為我們實現了servlet的大部分代碼,我們只需要寫業務實現即可。下面是具體代碼
1
2
3
4
5
6
7
8
9
10
11
12
|
<?xml version= "1.0" encoding= "utf-8" ?> <beans xmlns= "http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.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.springframework.org/schema/beans 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.0.xsd"> <!-- 自動掃描指定包下的類 --> <context:component-scan base- package = "controller" /> </beans> |
3. web.xml
這是web工程的配置文件,下面是主要代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
<?xml version= "1.0" encoding= "utf-8" ?> <web-app xmlns= "http://java.sun.com/xml/ns/javaee" xmlns:xsi= "http://www.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"> <!--配置字符編碼過濾器 ,由spring提供 --> <filter> <filter-name>encodingfilter</filter-name> <filter- class >org.springframework.web.filter.characterencodingfilter</filter- class > <init-param> <param-name>encoding</param-name> <param-value>utf- 8 </param-value> </init-param> </filter> <!-- 配置歡迎界面 --> <welcome-file-list> <welcome-file>/all</welcome-file> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> </welcome-file-list> <!-- 配置springmvc servlet --> <servlet> <servlet-name>springmvc</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-pattern>/</url-pattern> </servlet-mapping> </web-app> |
6.項目總結及附錄
這個項目是個我的日常練習項目,為了更加熟練,我把完整的過程又回顧了一遍,又熟悉了很多,
項目用的jar包附錄:
除了spring的包外,還有mysql-jbdc的jar包和jstl的jar包
下載地址:
spring框架jar包(可選版本):spring官網
mysql-jdbc.jar(可選版本):mysql官網
jstl.jar(可選版本):maven官方地址
以上就是本文關于spring mvc實現mysql數據庫增刪改查完整實例的全部內容,希望對大家有所幫助。如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://www.zhimengzhe.com/shujuku/MySQL/334084.html