0% found this document useful (0 votes)
19 views

Spring MVC学习指南(第2版)

Spring MVC is a Java web framework that uses the model-view-controller pattern. It allows building web applications easily and integrates with other Spring projects like Spring Core. Spring MVC handles requests and returns model data to the view for rendering. It uses DispatcherServlet to handle requests and responses and works with technologies like Servlets, JSPs, and Java for the web tier.

Uploaded by

Peihsuan Lin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Spring MVC学习指南(第2版)

Spring MVC is a Java web framework that uses the model-view-controller pattern. It allows building web applications easily and integrates with other Spring projects like Spring Core. Spring MVC handles requests and returns model data to the view for rendering. It uses DispatcherServlet to handle requests and responses and works with technologies like Servlets, JSPs, and Java for the web tier.

Uploaded by

Peihsuan Lin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 341

Spring MVC Spring Web MVC

Model-View-Controller Web Spring MVC

Spring MVC Java Web 13 5


Spring 2 MVC Spring MVC
JSTL
Spring MVC Tomcat Spring Tool Suite
Maven Servlet JavaServer Pages

Spring MVC Web


Spring MVC Java Web
Paul Deck Java Spring
How Tomcat Works

IBM 2004

IBM
Spring MVC Spring Web Spring MVC MVC
Model-View-Controller
Web Swing JavaFX

Web Spring MVC Spring Web MVC


Spring MVC Java Web

Spring MVC Spring Servlet JSP JavaServer Page 3


Spring MVC 1 Spring C
D Servlet JSP Servlet JSP
Budi Kurniawan Servlet and JSP A Tutorial second Edition

HTTP Servlet JSP Web

HTTP Web
W3C HTTP HTTP HTTP 0.9
HTTP 1.0 HTTP 1.1 HTTP 1.1 RFC 2616 HTTP 1.1
HTTP 2015 5 HTTP/2 1.1
HTTP HTTP HTTP/2 HTTP2

1.1 HTTP

HTTP 0.9 1991


HTTP 1.0 1996
HTTP 1.1 1997 1999
HTTP/2 2015 5
Web 24 HTTP Web

URL

URL HTTP HTTP URL

HTTP URL

URL http://yahoo.ca http://192.168.1.9

http://google.com http://173.194.46.35
ping IP

IP
IP example.com example.org

URL host http://yahoo.com


host http://mail.yahoo.com host
www http://www.domainName
http://domainName

HTTP 80 80 Web
Web 80 Tomcat
8080

2
localhost

URL context Web

context

context index.html index.htm


default.htm URL

key/value
& value value
/

HTTP

HTTP
HTTP 3

1 URI /

HTTP

POST /examples/default.jsp HTTP/1.1 URI /

3
POST URI /examples/default.jsp / HTTP/1.1

HTTP 1.1 7 GET POST HEAD OPTIONS PUT


DELETE TRACE GET POST

URI /
URL URI http://www.ietf.org/rfc/rfc2396.txt

HTTP
header / CRLF

HTTP HTTP
CRLF HTTP 4

lastName=Blanks&firstName=Mike

HTTP

HTTP
HTTP HTTP 3

HTTP

4
HTTP HTTP HTTP 1.1
200

HTTP HTTP
HTTP HTML HTTP
CRLF

200 Web
Web 401
405 HTTP http://www.w3.
org/Protocols/rfc2616/rfc2616-sec10.html

Java Servlet Java Web 1996 Servlet JSP


SUN CGI Web CGI
CPU
CGI CGI Servlet Servlet

Servlet Web
Web
Servlet
JavaServer Pages JSP Servlet
Spring MVC Struct 2 JSF Servlet JSP
Servlet Servlet Java Servlet
Servlet Web
Servlet 3.1 JSR Java Specification Request 340
http://jcp.org/en/jsr/detail?id=340 Java 6 JSP 2.3 JSR
245 http://jcp.org/en/jsr/detail?id=245 Java
Java Java 7 A Beginner s Tutorial fourth Edition

Servlet Java Servlet Servlet JSP

5
Servlet

Servlet Servlet Servlet


Servlet Servlet Servlet
JSP Java Web Servlet/JSP

Web IE Chrome Web Servlet Web


Web 1 Servlet/JSP

1 Servlet/JSP

Web Web HTTP Web HTTP

Servlet/JSP Servlet Web HTTP


Servlet/JSP HTTP Apache HTTP
Servlet/JSP HTTP
Servlet/JSP Apache Tomcat Jetty
Servlet/JSP http://tomcat.apache.org
http://jetty.codehaus.org

Servlet JSP Java Java JMS EJB JSF


JPA Java 7 Http://www.oracle.com/technetwork/java/
javaee/tech/index.html

Java Java GlassFish JBoss


Oracle Weblogic IBM WebSphere Servlet/JSP Java

6
Servlet/JSP Tomcat Jetty Java
EJB JMS

Spring Maven Gradle Spring

Maven
Gradle
Java
Maven Gradle Spring
Maven Maven/Gradle

Maven Spring Spring Spring Tool Suites


STS Eclipse IDE Maven Maven
Eclipse Maven
STS STS Spring MVC
Servlet web.xml Maven
Maven
web.xml Servlet 3.0 web.xml
web.xml Spring MVC

Maven/Gradle

Gradle Maven Spring

4.2.5 zip

7
x.y.z Spring

zip Java
libs Spring jar

Maven Gradle Spring B

Spring
Spring Git Spring

Gradle Spring Git Gradle

8
1 Spring

2 2 MVC Spring MVC

3 Spring MVC Spring MVC

4 MVC
Spring MVC 2.5

5 Spring MVC

8 JSP 2.0
JSP JSP
EL Java Bean

9 JSTL JSP
map XML

10 Spring MVC

11

12

13 Junit Mockito Spring MVC Test

A Tomcat Tomcat

B Spring Tool Suite Maven Spring Tool Suite


Spring MVC
C Servlet Servlet API Servlet Servlet
API 4 javax.servlet javax.servlet.http

D JavaServer Pages JSP actions

E Spring MVC

2
2.6 ......................................31
...............................1
2.7 ..............................................38

1.1 XML ..............................3


..................39
1.2 Spring .........4
1.2.1 bean 3.1 Spring MVC ............39
.....................................4 3.2 Spring MVC
1.2.2 bean DispatcherServlet ..........................40
.....................................5 3.3 Controller .............................41
1.2.3 .................6 3.4 Spring MVC ............42

1.2.4 .............6 3.4.1 ...........................42

1.2.5 Setter ...........7 3.4.2 Spring


1.2.6 .......10 MVC .................43
1.3 ..............................................10 3.4.3 Controller ......................44
3.4.4 View ..............................46
............. 11
3.4.5 ...........................47

2.1 1 .................................. 11 3.5 ..................................47


2.2 2 .................................. 11 3.6 ..............................................49
2.3 2 Servlet .............13
................50
2.3.1 Product ..........................14

2.3.2 ProductForm .................15 4.1 Spring MVC .................50

2.3.3 ControllerServlet ...........16 4.1.1 Controller ..........50


2.3.4 Action ...........................20 4.1.2 RequestMapping
2.3.5 ...................................20 ...................................51
2.3.6 ...........................22 4.2 ......................54

2.4 2 Filter ................22 4.3 ..............56


2.5 ..........................................25 4.3.1 ...........................56

1
4.3.2 ...........................56 5.3.4 Service ..........................84

4.3.3 Controller ......................59 5.3.5 ...........................87


4.3.4 View ...................................60 5.3.6 ...................................88

4.3.5 ...........................61 5.3.7 ...........................91

4.4 @Autowired @Service 5.4 ..............................................92


..............................62
.....................93
4.5 Flash ....................66

4.6 ..................67 6.1 Converter ......................................93


4.7 @ModelAttribute ..........................69 6.2 Formatter ......................................98
4.8 ..............................................70 6.3 Registrar Formatter .......101
6.4 Converter
.......71
Formatter ....................................103
5.1 ..............................71 6.5 ............................................103

5.2 ..................................72
.....................................104
5.2.1 ...........................73

5.2.2 input ..........................74 7.1 ....................................104

5.2.3 password ...................74 7.2 Spring .............................105


5.2.4 hidden .......................75 7.3 ValidationUtils .......................106

5.2.5 textarea ......................75 7.4 Spring Validator ............107

5.2.6 checkbox ...................76 7.5 ........................................109

5.2.7 radiobutton ................76 7.6 Controller ...............................109

5.2.8 checkboxes ................77 7.7 ................................ 111


5.2.9 radiobuttons ..............78 7.8 JSR 303 .............................. 112

5.2.10 select .......................78 7.9 JSR 303 Validator .............. 113

5.2.11 option ......................79 7.10 .......................................... 116

5.2.12 options .....................80


............................ 117
5.2.13 errors .......................80

5.3 ..............................81 8.1 ........................ 117

5.3.1 ...........................81 8.2 .................... 118


5.3.2 Domain .........................81 8.2.1 ............................. 118

5.3.3 Controller ......................83 8.2.2 [] . ..................... 119

2
8.2.3 ......................... 119 8.9.7 count ................................131
8.3 JavaBean ............................120 8.9.8 min ...................................131
8.4 EL ..............................121 8.9.9 max ..................................131
8.4.1 pageContext .....................121 8.9.10 map ................................131
8.4.2 initParam ..........................123 8.9.11 filter ................................132
8.4.3 param ...............................123 8.9.12 forEach...........................132
8.4.4 paramValues .....................123 8.10 ..............................132
8.4.5 header...............................123 8.10.1 HTML ..........132
8.4.6 headerValues ....................124 8.10.2 String.join() ...........134
8.4.7 cookie...............................124 8.11 ..............................134
8.4.8 applicationScope 8.12 ..............................134

sessionScope requestScope 8.13 JSP 2.0


pageScope ...................124 EL ...................................135
8.5 EL ..................124 8.13.1 JSP
8.5.1 .....................125 ...............................135

8.5.2 .....................125 8.13.2 EL ................135

8.5.3 .....................126 8.14 ..........................................137


8.5.4 .....................126
........................................138
8.5.5 empty ..................126

8.5.6 .........126 9.1 JSTL...................................138


8.5.7 .....................127 9.2 JSTL .......................................138
8.6 ........127 9.3 ....................................140
8.7 Set List Map ...............128 9.3.1 out ...........................140

8.8 Map .......129 9.3.2 url ............................141

8.9 ....................................129 9.3.3 set ............................144


8.9.1 toList ................................129 9.3.4 remove ....................145
8.9.2 toArray .............................130 9.4 ....................................146
8.9.3 limit ..................................130 9.4.1 if ..............................146
8.9.4 sort ...................................130 9.4.2 choose when otherwise
8.9.5 average .............................130 .................................147
8.9.6 sum...................................131 9.5 ....................................148

3
9.5.1 forEach ....................148 10.2 Spring MVC ...173

9.5.2 forTokens ................157 10.2.1


9.6 ................................158 .......................174

9.6.1 formatNumber .........158 10.2.2


9.6.2 formatDate ..............160 .......................175
9.6.3 timeZone .................162 10.3 Spring MVC
9.6.4 setTimeZone ...........163 .................................176

9.6.5 parseNumber ...........163 10.4 message ...................177

9.6.6 parseDate ................165 10.5 ..........................................177

9.7 ............................................166 10.6 ..........................................181


9.7.1 contains ...................166
..............................182
9.7.2 containsIgnoreCase
.................................166 11.1 .............................. 182

9.7.3 endsWith .................167 11.2 MultipartFile .................... 183


9.7.4 escapeXml ...............167 11.3 Commons FileUpload
9.7.5 indexOf ...................167 ................................... 184

9.7.6 join ..........................167 11.4 Domain ................................. 185


9.7.7 length ......................168 11.5 ...................................... 185

9.7.8 replace .....................168 11.6 .................................. 187

9.7.9 split .........................168 11.7 JSP ................................... 188

9.7.10 startsWith ..............169 11.8 ...................... 190

9.7.11 substring ................169 11.9 Servlet 3


9.7.12 substringAfter .......169 ................................... 191

9.7.13 substringBefore .....169 11.10 ............................ 194

9.7.14 toLowerCase .........170 11.11 ......................................... 202

9.7.15 toUpperCase ..........170


..............................203
9.7.16 trim ........................170

9.8 ............................................170 12.1 .......................... 203

12.2 1 ................... 204


...................................171
12.3 2 ........... 207

10.1 ..................................172 12.4 .......................................... 210

4
.............................. 211 ....................................242

13.1 .................................. 211 A.1 Tomcat................... 242


13.2 .............. 213 A.2 Tomcat................... 243
13.3 JUnit................................. 213 A.3 ............................... 243
13.3.1 .......213 A.4 ................................... 244

13.3.2 .......215 A.5 TLS .......................... 245

13.3.3
.... 246
...........215

13.4 B.1 STS .................................... 246


Test Doubles ........................ 216 B.2 Spring MVC ..... 247
13.4.1 dummy ...........................217 B.3 Java ........................... 251
13.4.2 stub.................................219 B.4 index.html ................ 252
13.4.3 spy ..................................219 B.5 .................................... 253
13.4.4 fake ................................221 B.6 .................................... 253
13.4.5 mock ..............................224
.....................................256
13.5 Spring MVC Controller
................................... 226 C.1 Servlet API ........................ 256

13.5.1 MockHttpServletRequest C.2 Servlet ........................................ 257


MockHttpServlet C.3 Servlet .... 258
Response ........................226 C.3.1 Servlet ...259
13.5.2 ModelAndViewAssert....229 C.3.2 .........260
13.6 Spring MVC Test C.3.3 Servlet ....................261
................................... 232 C.4 ServletRequest ........................... 262
13.6.1 API .................................233 C.5 ServletResponse ......................... 262
13.6.2 Spring MVC C.6 ServletConfig ............................. 263
................................234 C.7 ServletContext............................ 266
13.6.3 ...............................236 C.8 GenericServlet ............................ 266
13.7 Web C.9 Http Servlets............................... 268
...................................... 239 C.9.1 HttpServlet ......................269
13.8 .......................................... 241 C.9.2 HttpServletResponse .......271

5
C.10 HTML .................... 271 E.1.1 .........................305

C.11 ...................... 277 E.1.2 context-param ..................305


C.12 .......................................... 280 E.1.3 distributable .....................306
E.1.4 error-page ........................306
..............281
E.1.5 filter .................................306
D.1 JSP .................................... 281 E.1.6 filter-mapping ..................307
D.2 ........................................... 286 E.1.7 listener .............................308
D.3 ................................... 287 E.1.8 locale-encoding-mapping-list
D.4 ........................................... 290 locale-encoding-
D.4.1 page ........................290 mapping ...........................308
D.4.2 include ....................292 E.1.9 login-config .....................308
D.5 ................................... 293 E.1.10 mime-mapping ..............309
D.5.1 ............................294 E.1.11 security-constraint .........309
D.5.2 ................................294 E.1.12 security-role ...................310
D.5.3 .................298 E.1.13 Servlet............................ 311
D.6 ........................................... 298 E.1.14 servlet-mapping .............313
D.6.1 useBean ...........................298 E.1.15 session-config ................313
D.6.2 setProperty E.1.16 welcome-file-list ............313
getProperty ......................299 E.1.17 JSP-Specific Elements ...314
D.6.3 include.............................300 E.1.18 taglib ..............................314
D.6.4 forward ............................301 E.1.19 jsp-property-group .........315
D.7 ................................... 301 E.2 ............................................ 316
D.8 ........................................... 302 E.3 Web fragment ............................. 317
E.4 ............................................ 319
.............................303

E.1 ............................................ 303

6
2.3 2 Servlet

import javax.servlet.http.HttpServletResponse;
import appdesign1.action.SaveProductAction;
import appdesign1.form.Product Form;
import appdesign1.model.Product;
import java.math.BigDecimal;

@WebServlet(name = "ControllerServlet", urlPatterns = {


"/input-product", "/save-product"})
public class ControllerServlet extends HttpServlet {

private static final long serialVersionUID = 1579L;

@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
process(request, response);
}

@Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
process(request, response);
}

private void process(HttpServletRequest request,


HttpServletResponse response)
throws IOException, ServletException {

String uri = request.getRequestURI();


/*
* uri is in this form: /contextName/resourceName,
* for example: /appdesign1/input-product.
* However, in the event of a default context, the
* context name is empty, and uri has this form
* /resourceName, e.g.: /input-product
*/
int lastIndex = uri.lastIndexOf("/");
String action = uri.substring(lastIndex + 1);
// execute an action
String dispatchUrl = null;
if ("input-product".eauals(action)) {
// no action class, just forward
dispatchUrl = "/jsp/ProductForm.jsp";
} else if ("save-product".eauals(action)) {
// create form

17
2 2 MVC

ProductForm productForm = new ProductForm();


// populate action properties
productForm.setName(request.getParameter("name"));
productForm.setDescription(
request.getParameter("description"));
productForm.setPrice(request.getParameter("price"));

// create model
Product product = new Product();
product.setName(productForm.getName());
product.setDescription(productForm.getDescription());
try {
product.setPrice(new Bigdecimal(productForm.getPrice()));
} catch (NumberFormatException e) {
}
// execute action method
SaveProductAction saveProductAction =
new SaveProductAction();
saveProductAction.save(product);

// store model in a scope variable for the view


request.setAttribute("product", product);
dispatchUrl = "/jsp/ProductDetails.jsp";
}

if (dispatchUrl != null) {
RequestDispatcher rd =
request.getRequestDispatcher(dispatchUrl);
rd.forward(request, response);
}
}
}

ControllerServlet process URI action


String uri = request.getRequestURI();
int lastIndex = uri.lastIndexOf("/");
String action = uri.substring(lastIndex + 1);

action input-product save-product

process

1 save-product 3 name
description price

18
2.3 2 Servlet

3 JSP

process action if
// execute an action
if ("input-product".eauals(action))) {
// no action class, just forward
dispatchUrl = "/jsp/ProductForm.jsp";
} else if ("save-product".eauals(action)) {
// instantiate action class

input-product save-product ProductForm


Product
2.5

process SaveProductAction save


// create form
ProductForm productForm = new ProductForm();
// populate action properties
productForm.setName(request.getParameter("name"));
productForm.setDescription(
request.getParameter("description"));
productForm.setPrice(request.getParameter("price"));

// create model
Product product = new Product();
product.setName(productForm.getName());
product.setDescription(productForm.getDescription());
try {
product.setPrice(new BigDecimal(productForm.getPrice()));
} catch (NumberFormatException e) {
}
// execute action method
SaveProductAction saveProductAction =
new SaveProductAction();
saveProductAction.save(product);

Product HttpServletRequest
// store action in a scope variable for the view
request.setAttribute("product", product);

process action product_input ProductForm.jsp

19
3.4 Spring MVC

3.4.2 Spring MVC


3.1 web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app 3 1.xsd">

<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>
<!-- map all requests to the DispatcherServlet -->
<url-pattern>/</url-pattern>
</servlet-mapping>

</web-app>

Servlet/ JSP Spring MVC Dispatcher Servlet


url-pattern / URL servlet servlet init-param
Spring MVC /WEB-INF

3.2 Spring MVC


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean name="/input-produrt"
class="controller.InputProductController"/>
<bean name="/save-product"
class="controller.SaveProductController"/>

</beans>

43
6

6.8 springmvc-config.xml Registrar


<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/springcontext.xsd">

<context:component-scan base-package="controller" />


<context:component-scan base-package="formatter" />

<mvc:annotation-driven conversion-service="conversionService" />

<mvc:resources mapping="/css/**" location="/css/" />


<mvc:resources mapping="/*.html" location="/" />

<bean id="viewResolver"
class="org.springframework.web.servlet.view.
InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>

<bean id="conversionService"
class="org.springframework.format.support.
FormattingConversionServiceFactoryBean">

<property name="formatterRegistrars">
<set>
<bean class="formatter.MyFormatterRegistrar">
<constructor-arg type="java.lang.String"
value="MM-dd-yyyy" />
</bean>
</set>
</property>
</bean>
</beans>

102

You might also like