Professional Documents
Culture Documents
Spring MVC Full Version Vienamese
Spring MVC Full Version Vienamese
3.2
DispatcherServlet ................................................................................................................................ 4
3.3
Controllers........................................................................................................................................... 10
3.3.1
3.3.2
3.3.3
MultiActionController ............................................................................................................ 12
3.3.4
3.4
3.5
Views. .................................................................................................................................................... 18
3.5.1
3.5.2
3.6
3.6.1
AcceptHeaderLocaleResolver ............................................................................................. 20
3.6.2
CookieLocaleResolver ............................................................................................................ 20
3.6.3
SessionLocaleResolver........................................................................................................... 21
3.6.4
LocaleChangeInterceptor ..................................................................................................... 21
3.7
3.7.1
3.7.2
3.7.3
3.8
3.8.1
Introduction ............................................................................................................................... 23
3.8.2
3.8.3
3.9
3.9.1
Configuration ............................................................................................................................. 27
3.9.2
3.9.3
3.9.4
3.9.5
3.9.6
3.9.7
3.9.8
Option tag.................................................................................................................................... 31
3.9.9
3.9.10
3.9.11
3.9.12
Page 3
3.2 DispatcherServlet
Spring's web MVC framework ging nh nhiu web MVC frameworks, request-driven, c
thit k xung quanh mt servlet trung tm, n gi cc request n cc controller v a ra
nhng chc nng d dng cho s pht trin ca ng dng web. Spring DispatcherServlet
bt c nh th no , lm nhiu hn l ch c vy. N hon ton c tch hp vi Spring IoC
container v nh vy cho php bn s dng bt c c tnh no m Spring c.
Lung x l request ca Spring Web MVC DispatcherServlet c minh ha trong lc
bn di. Ngi c c hiu bit v m hnh s nhn thy rng that the DispatcherServlet l
mt s din t ca mu thit k Front Controller (y l mt mu m Spring Web MVC
chia s vi nhiu web frameworks dn u khc ).
Page 4
Page 6
Vi v tr trong s cu hnh servlet trn, bn s cn c mt file gi l '/WEB-INF/golfingservlet.xml' trong ng dng ca bn; file ny s cha ng tt c cc m t ca cc
component(bean) ca Spring Web MVC. V tr chnh xc ca cc file cu hnh c th b thay
i qua mt tham s khi to ca servlet ( Xem bn di r hn).
WebApplicationContext l mt s m rng ca plain ApplicationContext, n c mt vi tnh
nng ph cn thit cho cc web. N khc vi mt ApplicationContext bnh thng, n
c kh nng gii quyt cc theme (xem Section 13.7, Using themes), v rng n bit serlet
no n c lin kt (bi c mt lin kt ti ServletContext). WebApplicationContext c
bao bn trong ServletContext, v s dng nhng phng thc tnh trn lp
RequestContextUtils, bn c th lun lun tm thy WebApplicationContext trong trng
hp bn cn truy cp n n.
Spring DispatcherServlet c mt s ghp ni vi cc bean c bit, n dng c th x l
cc request v to ra nhng view thch hp. Nhng bean c bao gm bn trong
Spring framework v c th c cu hnh trong WebApplicationContext, ch nh mt vi
bean khc cn c cu hnh. Mi ci bean ny c m t chi tit hn bn di. By gi,
chng ta s ch cp n chng, va bn bit chng tn ti v c th cho php chng ta
ni v DispatcherServlet. Hu ht cc bean, c th thy c mc nh c cung cp v th
bn khng (initially) phi lo lng v lm sao cu hnh chng.
Table 13.1. S c t bean trong the WebApplicationContext
Bean type
Explanation
Controllers
Handler
mappings
Handler mappings x l s thc thi ca mt danh sch cc pre- v postprocessors v cc controllers s c thc thi nu chng hp vi tiu
chun chc chn ( cho i tng mt s xng hp ca mt URL c bit
Page 7
Explanation
vi controller)
View resolvers
multipart file
resolver
Handler
exception
resolver(s)
Parameter
contextClass
Explanation
Lp thc thi ApplicationContext, n s c dng khi
to ng cnh c s dng bi servlet ny. Nu tham s ny
khng c c t, XmlWebApplicationContext s c s
dng.
Explanation
context, ca cc bean c nh ngha hai ln, ci sau cng
c u tin).
namespace
3.3 Controllers
S thng bo ca mt controller l mt phn trong thit k ca m hnh MVC (Chnh xc
hn n l 'C' trong MVC. Cc Controller cung cp ch truy cp vo ng dng m n c
nh ngha tiu biu bi mt service interface. Cc Controller gii thch user input v
chuyn i thnh dng input c th hiu c m n s c trnh din cho user bng
view. Spring thc thi s thng bo ca mt controller trong mt cch chung chung tru
tng, cho php mt lng ln cc loi controller c tao to ra. Spring cha ng c t
form (form-specific) ca cc controller, cc command-based controller, v cc controller
m n thc hin wizard-style logic, thnh tn nhng mt t.
C s ca Spring cho kin trc controller l interface
org.springframework.web.servlet.mvc.Controller, Source code cho n c lit k bn di.
public interface Controller {
/**
* Process the request and return a ModelAndView object which the
DispatcherServlet
* will render.
*/
ModelAndView handleRequest(
HttpServletRequest request,
HttpServletResponse response) throws Exception;
}
Nh bn c th thy, Controller interface nh ngha mt phng thc n c chu trch
nhim cho vic x l mt request v tr v mt model v view thch hp. Ba khi nim l
c s cho Spring MVC implementation - ModelAndView v Controller. Trong khi Controller
interface l kh tru tng, Spring a ra mt lng cc Controller implementation c th
s dng d dng v n cha ng mt lng cc chc nng m bn cn.Controller
Page 10
Explanation
requiresSession
synchronizeSession
cacheSeconds
useCacheHeader
Page 12
delegate
Explanation
C hai kch bn s dng vi MultiActionController. Hoc l bn to
ra mt subclass ca MultiActionController v c t nhng phng
thc s c gii quyt bi MethodNameResolver trn subclass (
trong trng hp ny bn khng cn t delegate), hoc bn nh
ngha mt i tng, trn phng thc ny s resolved by the
MethodNameResolver will be invoked. If you choose this scenario,
you will have to define the delegate using this configuration
parameter as a collaborator.
Xin ch rng kiu np chng phng thc l khng c cho php (overloading method)
khi n s lm cho MultiActionController nhm ln. Hn na, bn c th nh ngha
exception handlers c kh nng x l cc exception m c nm ra t phng thc m bn
c t.
Tham s Exception c th l mt vi exception, xa hn na n l mt subclass ca
java.lang.Exception or java.lang.RuntimeException. Tham s ca AnyObject c th l mt vi
class. Nhng thm s Request s c bao li bn trong i tng ny cho s s dng thch
hp.
Tm kim mt vi v d hp l v phng thc MultiActionController.
Kiu chun (phng thc interface ca Controller).
public ModelAndView doRequest(HttpServletRequest, HttpServletResponse)
Page 13
Kiu tr v kiu void (tm hiu thm ti Section 13.11, Convention over configuration ).
public void goHome(HttpServletRequest, HttpServletResponse)
MethodNameResolver l phng thc chu trch nhim x l tn da trn request vo. Xem
chi tit bn di v 3 kiu implement ca MethodNameResolver m Spring cung cp m
khng c rng buc.
Page 14
## together with
public class SampleDelegate {
public ModelAndView retrieveIndex(HttpServletRequest req, HttpServletResponse
resp) {
return new ModelAndView("index", "date", new
Long(System.currentTimeMillis()));
}
}
Page 16
interceptors: danh sch cc b chn dng. Xem thm Section 13.4.3, Intercepting
requests - the HandlerInterceptor interface.
defaultHandler: default handler dng, Khi handler mapping ny khng hp vi
handler no.
order: da trn gi tr ca thuc tnh order (xem org.springframework.core.Ordered
interface), Spring s sp xp tt c cc handler mappings ang c trong context v p
dng handler u tin.
Page 17
3.5 Views.
3.5.1 Chaining ViewResolvers
Spring h tr nhiu view resolver, v chng c sp xp mt cch th t theo mt chui
mc xch. Trong v d bn di, chui mc xch ca chng ta c hai view (
InternalResourceViewResolver):
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="excelViewResolver"
class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="order" value="1"/>
<property name="location" value="/WEB-INF/views.xml"/>
</bean>
<!-- in views.xml -->
<beans>
<bean name="report" class="org.springframework.example.ReportExcelView"/>
</beans>
Page 18
Default
classname +
LOCALE
Description
Tn ca cookie
cookiePath
Page 20
3.6.3 SessionLocaleResolver
SessionLocaleResolver cho php bn ly cc locale t session.
3.6.4 LocaleChangeInterceptor
Bn c th xy dng s thay i ca locale bng cch s dng LocaleChangeInterceptor. B
chn ny cn c thm vo handler mappings, trong request v thay i locale (n gi
setLocale() ca LocaleResolver, m n cng tn ti trong ng cnh ny).
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="siteLanguage"/>
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver"/>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref bean="localeChangeInterceptor"/>
</list>
</property>
<property name="mappings">
<value>/**/*.view=someController</value>
</property>
</bean>
Description
FixedThemeResolver
SessionThemeResolver
Page 23
After that, create the controller and the actual class to hold the file property.
public class FileUploadController extends SimpleFormController {
protected ModelAndView onSubmit(
HttpServletRequest request,
HttpServletResponse response,
Object command,
BindException errors) throws ServletException, IOException {
// cast the bean
FileUploadBean bean = (FileUploadBean) command;
let's see if there's content there
byte[] file = bean.getFile();
if (file == null) {
// hmm, that's strange, the user did not upload anything
}
Page 24
Page 25
Page 26
Page 27
Page 28
<form:form>
<table>
<tr>
<td>Subscribe to newsletter?:</td>
<%-- Approach 1: Property is of type java.lang.Boolean --%>
<td><form:checkbox path="preferences.receiveNewsletter"/></td>
<td> </td>
</tr>
<tr>
<td>Interests:</td>
<td>
<%-- Approach 2: Property is of an array or of type
java.util.Collection --%>
Page 29
<tr>
<td>Interests:</td>
<td>
Quidditch: <input name="preferences.interests" type="checkbox"
value="Quidditch"/>
<input type="hidden" value="1" name="_preferences.interests"/>
Herbology: <input name="preferences.interests" type="checkbox"
value="Herbology"/>
<input type="hidden" value="1" name="_preferences.interests"/>
Defence Against the Dark Arts: <input name="preferences.interests"
type="checkbox"
value="Defence Against the Dark Arts"/>
<input type="hidden" value="1" name="_preferences.interests"/>
</td>
<td> </td>
</tr>
Page 30
<tr>
<td>Password:</td>
<td>
<form:password path="password" value="^76525bvHGq" showPassword="true" />
</td>
</tr>
<tr>
<td>Skills:</td>
<td><select name="skills" multiple="true">
<option value="Potions">Potions</option>
<option value="Herbology" selected="true">Herbology</option>
<option value="Quidditch">Quidditch</option></select></td>
<td></td>
</tr>
Page 31
If the User lived in the UK, the HTML source of the 'Country' row would look like:
<tr>
<td>Country:</td>
<tr>
<td>Country:</td>
<td>
<select name="country">
<option value="-">--Please Select</option>
<option value="AT">Austria</option>
<option value="UK" selected="true">United Kingdom</option>
<option value="US">United States</option>
</select>
</td>
<td></td>
</tr>
<td></td>
</tr>
As the example shows, the combined usage of an option tag with the options tag generates
the same standard HTML, but allows you to explicitly specify a value in the JSP that is for
display only (where it belongs) such as the default string in the example: "-- Please Select".
3.9.10 The textarea tag
This tag renders an HTML 'textarea'.
<tr>
<td>Notes:</td>
<td><form:textarea path="notes" rows="3" cols="20" /></td>
<td><form:errors path="notes" /></td>
</tr>
Page 32
If we submit a form with empty values in the firstHame and lastName fields, this is what
the HTML would look like:
<form method="POST">
<table>
<tr>
Page 33
What if we want to display the entire list of errors for a given page? The example below
shows that the errors tag also supports some basic wildcarding functionality.
The example below will display a list of errors at the top of the page, followed by fieldspecific errors next to the fields:
<form:form>
<form:errors path="*" cssClass="errorBox" />
<table>
<tr>
<td>First Name:</td>
<td><form:input path="firstName" /></td>
<td><form:errors path="firstName" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><form:input path="lastName" /></td>
<td><form:errors path="lastName" /></td>
</tr>
<tr>
<td colspan="3">
<input type="submit" value="Save Changes" />
</td>
</tr>
</table>
</form:form>
Page 34
Page 35