欢迎来到 IT实训基地-南通科迅教育
咨询电话:0513-81107100
springmvc学习指南-springmvc的CRUD入门
2017/4/20
南通科迅教育
498
南通Web前端设计培训学校 南通哪里学Web前端比较好

整合过springmvc项目的人都知道,web.xml有这样一段用于配置springmvc的,如下面所示。

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!-- springmvc的配置 -->
<servlet>
    <servlet-name>springDispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:config/springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
 
<servlet-mapping>
    <servlet-name>springDispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

实际上,这是springmvc整合的入口,用于充当控制器的作用:即用于处理前端的请求并进行分发(如转发,重定向等操作)。而springmvc学习指南前三章讲的就是dispatcherServlet的由来(从分Controller的功能讲起到最后将各个同属于一个实体的Controller整合到同一个Controller中)。附:希望博友们有空可以读读(很是浅显易懂!)

 

今晚就跟各位分享一下我根据自己的理解,动手写了一个纯粹的springmvc的CRUD操作,而不整合后端持久层框架(即Dao层)和前端的模板,只是模拟演示一下罢了(其实,这个过程下来,再去整合Dao和前端模板是相当简单的:因为Dao其实就是提供数据库访问的操作,你可以弄个纯的jdbc,整个c3p0的Jdbc,甚至是hibernate,mybatis等等;而前端则只是为了实现异步交互操作,你可以弄个jquery-easyui,jsp+ajax+jquery,jerbrick-template,freemarker等等)。好了,下面就开始介绍我这个小案例的整体项目结构吧!

\

 

介绍的实体包括:“实体”目录(Category)和“实体”书籍(Book),两者是一对多的关系。即一个目录下面有多本书,一本书只属于一个目录。

下面是它们的model类(其实就是一个很简洁的POJO)的代码(注意,为了缩减篇幅,省略了属性的getter、setter方法):

 

?
1
2
3
4
5
6
7
8
packagecom.steadyjack.server.model;
 
publicclassCategory {
    privateLong id;
    privateString name;
 
    //getter setter方法
}

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
packagecom.steadyjack.server.model;
 
publicclassBook {
    privateLong id;
     
    privateString title;
     
    privateString isbn;
     
    privateString author;
     
    privateLong categoryId;
 
<span style="white-space:pre">  </span>//getter setter方法
}

下面是后端Categoryservice接口和BookService及其实现:

 

CategoryService:

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
packagecom.steadyjack.server.service;
 
importjava.util.List;
 
importcom.steadyjack.server.model.Category;
 
publicinterfaceCategoryService {
     
    List<category> getCategoryList();
     
    Category getCategoryById(Long id);
}
</category>

 

 

CategoryServiceImpl
?
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
packagecom.steadyjack.server.service.impl;
 
importjava.util.ArrayList;
importjava.util.List;
 
importorg.springframework.stereotype.Service;
 
importcom.steadyjack.server.model.Category;
importcom.steadyjack.server.service.CategoryService;
 
@Service("categoryService")
publicclassCategoryServiceImplimplementsCategoryService {
     
    privateList<category> categoryList=newArrayList<>();
     
    publicCategoryServiceImpl() {
        Category category=newCategory();
        category.setId(1L);
        category.setName("java类书籍");
         
        Category categorySec=newCategory();
        categorySec.setId(2L);
        categorySec.setName("web框架类书籍");
         
        categoryList.add(category);
        categoryList.add(categorySec);
    }
     
    @Override
    publicList<category> getCategoryList() {
        returncategoryList;
    }
 
    @Override
    publicCategory getCategoryById(Long id) {
        Category currentCategory=null;
        for(Category category:categoryList){
            if(category.getId()==id) {
                currentCategory=category;
                break;
            }
        }
        returncurrentCategory;
    }
 
}
</category></category>

BookService:

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
packagecom.steadyjack.server.service;
 
importjava.util.List;
 
importcom.steadyjack.server.model.Book;
 
publicinterfaceBookService {
     
    Book saveBook(Book book);
     
    voidupdateBook(Book book);
     
    voiddeleteBook(Long id);
     
    List<book> getAllBooks();
     
    Book getBook(Long id);
     
}
</book>

 

BookServiceImpl:

 

?
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
packagecom.steadyjack.server.service.impl;
 
importjava.util.ArrayList;
importjava.util.List;
 
importorg.springframework.stereotype.Service;
 
importcom.steadyjack.server.model.Book;
importcom.steadyjack.server.service.BookService;
 
@Service("bookService")
publicclassBookServiceImplimplementsBookService {
     
    privateList<book> bookList=newArrayList<>();
     
    publicBookServiceImpl() {
        Book book=newBook();
        book.setTitle("java编程思想");
        book.setIsbn("10086");
        book.setAuthor("高司令");
        book.setCategoryId(1L);
         
        Book bookSec=newBook();
        bookSec.setTitle("spring实战");
        bookSec.setIsbn("10010");
        bookSec.setAuthor("约翰逊");
        bookSec.setCategoryId(1L);
         
        saveBook(book);
        saveBook(bookSec);
    }
     
    @Override
    publicBook saveBook(Book book) {
        book.setId(getNextId());
        bookList.add(book);
        returnbook;
    }
 
    @Override
    publicvoidupdateBook(Book book) {
        intsize=bookList.size();
        Book updateBook=null;
        for(inti=0;i<size;i++){ book=""if=""override=""public=""updatebook="bookList.get(i);"> getAllBooks() {
        returnbookList;
    }
 
    @Override
    publicBook getBook(Long id) {
        for(Book book : bookList){
            if(id==book.getId()) {
                returnbook;
            }
        }
        returnnull;
    }
     
    //获取主键的方式
    publicLong getNextId(){
        Long id=0L;
        for(Book book : bookList){
            if(book.getId()>id) {
                id=book.getId();
            }
        }
        returnid+1;
    }
 
    @Override
    publicvoiddeleteBook(Long id) {
        intsize=bookList.size();
        for(inti=0;i<size;i++){ id="=bookList.get(i).getId())"if=""pre="">
 
  以上各个方法的含义我就不注释了,其函数名就可以体现其意思了!<p> </p><p>  下面是后端的Controller类,主要是实现了BookController,如果还想实现CategoryController,可以自己参照BookController的实现。</p><p> </p><preclass="brush:java;">packagecom.steadyjack.server.controller;
 
importjava.util.HashMap;
importjava.util.List;
 
importorg.apache.commons.logging.Log;
importorg.apache.commons.logging.LogFactory;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.stereotype.Controller;
importorg.springframework.ui.Model;
importorg.springframework.web.bind.annotation.ModelAttribute;
importorg.springframework.web.bind.annotation.PathVariable;
importorg.springframework.web.bind.annotation.RequestMapping;
 
importcom.steadyjack.server.model.Book;
importcom.steadyjack.server.model.Category;
importcom.steadyjack.server.service.BookService;
importcom.steadyjack.server.service.CategoryService;
 
 
@Controller
@RequestMapping("/book")
publicclassBookController {
     
    privatestaticfinalLog logger=LogFactory.getLog(BookController.class);
     
    //分工合作:而不要因为是一个案例而将全部功能整合在了bookService  --  你认真对待,再简单的案例都可以成为一个项目
     
    @Autowired
    privateBookService bookService;
     
    @Autowired
    privateCategoryService categoryService;
 
    @RequestMapping("/list")
    publicString listBooks(Model model){
        logger.info("获取书籍列表");
         
        List<book> bookList=bookService.getAllBooks();
        HashMap<long, category=""> categoryMap=newHashMap<>();
         
        if(bookList!=null&& bookList.size()>0) {
            for(Book book : bookList){
                Long id=book.getCategoryId();
                categoryMap.put(id,categoryService.getCategoryById(id));
            }
        }
         
        model.addAttribute("bookList", bookList);
        model.addAttribute("categoryMap", categoryMap);
        return"BookList";
    }
     
     
    @RequestMapping("/input")
    publicString inputBook(Model model){
        logger.info("输入书籍信息");
         
        List<category> categoryList=categoryService.getCategoryList();
        model.addAttribute("categoryList", categoryList);
         
        return"BookInput";
    }
     
    @RequestMapping("/edit/{id}")
    publicString editBook(@PathVariableLong id,Model model){
        logger.info("编辑书籍信息");
         
        Book book=bookService.getBook(id);
        List<category> categoryList=categoryService.getCategoryList();
         
        model.addAttribute("categoryList", categoryList);
        model.addAttribute("book", book);
        return"BookEdit";
    }
     
    @RequestMapping("/save")
    publicString saveBook(@ModelAttributeBook book){
        logger.info("保存书籍信息");
         
        bookService.saveBook(book);
        return"redirect:/book/list";
    }
     
    @RequestMapping("/update")
    publicString updateBook(@ModelAttributeBook book){
        logger.info("保存修改后的书籍信息");
         
        bookService.updateBook(book);
        return"redirect:/book/list";
    }
     
    @RequestMapping("/delete/{id}")
    publicString deleteBook(@PathVariableLong id){
        logger.info("删除书籍信息");
         
        bookService.deleteBook(id);
        return"redirect:/book/list";
    }
     
}
</category></category></long,></book></pre>
<br>
上面的Controller还整合了Log的功能。
<p> </p>
<p>完了后端的实现,下面配置一下web.xml和springmvc的配置文件(其实,这应该属于第2步,第一步应该是放jar包,然后第三步才是上面的步骤!!!!)</p>
<p>先放入jar包WEB-INF下的lib文件夹中,可以来这里下载:springmvc的crud案例需要的jar包</p>
<p>然后配置一下web.xml:</p>
<p> </p>
<preclass="brush:java;"><!--?xml version="1.0"encoding="UTF-8"?-->
    <display-name>springStudyGuide-springmvc04</display-name>
 
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
 
    <!-- springmvc的配置 -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:config/springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
 
    <!-- 配置字符编码为UTF-8-->
    <filter>
        <filter-name>characterEncodingFilter</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>
         
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
     
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
     
 
</web-app></pre>
<br>
然后是springmvc的配置(配置文件叫: springmvc.xml):
<p> </p>
<p> </p>
<preclass="brush:java;"><!--?xml version="1.0"encoding="UTF-8"?-->
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
     
    <!-- 扫描包 -->
    <context:component-scan base-package="com.steadyjack.server">
     
    <!-- 为了能够使用RedirectAttributes 注解 -->
    <mvc:annotation-driven>
     
    <!-- 配置试图解析器 -->
    <beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix"value="/WEB-INF/jsp/"></property>
        <property name="suffix"value=".jsp"></property>
    </bean>
     
</mvc:annotation-driven></context:component-scan></beans>
</pre>
<br>
好了,基本上没啥了,接下来是前端几个.jsp文件了:
<p> </p>
<p>BookList.jsp:</p>
<p> </p>
<preclass="brush:java;"><%@ page language="java"contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
</pre>
<meta content="text/html; charset=UTF-8"http-equiv="Content-Type">
<title></title>
<base head=""href="<%=basePath%>">
<h2>-----书籍列表-----</h2>
<c:foreach items="${bookList }"var="book">
<p>编号:  ${book.id}<br>
名称:  ${book.title}<br>
条形码:  ${book.isbn}<br>
作者:  ${book.author}<br>
所属目录:  ${categoryMap[book.categoryId].name}</p>
<h5>修改书籍信息</h5>
<h5>删除书籍信息</h5>
</c:foreach><br>
<br>
<h4>添加书籍</h4>
</size;i++){></size;i++){></book>

BookInput.jsp:

 

 

?
1
2
3
4
5
6
7
8
<%@ page language="java"contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core"%>
 
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

BookEdit.jsp:
?
1
2
3
4
5
6
7
8
<%@ page language="java"contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core"%>
 
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
77
关闭
先学习,后交费申请表
每期5位名额
在线咨询
免费电话
QQ联系
先学习,后交费
TOP
您好,您想咨询哪门课程呢?
关于我们
机构简介
官方资讯
地理位置
联系我们
0513-91107100
周一至周六     8:30-21:00
微信扫我送教程
手机端访问
南通科迅教育信息咨询有限公司     苏ICP备15009282号     联系地址:江苏省南通市人民中路23-6号新亚大厦三楼             法律顾问:江苏瑞慈律师事务所     Copyright 2008-