BestMeのブログ -5ページ目

BestMeのブログ

ブログの説明を入力します。

Web.xmlの配置設定をきっかけ

DispatcherServlet
web.xmlの設定例
<servlet>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring/*.xml
        </param-value>
    </init-param>
        <load-on-startup>1</load-on-startup>
</servlet>     
<servlet-mapping>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <url-pattern>/app/*</url-pattern>
</servlet-mapping>

●servlet(サーブレット)とは
定義は多分、調べたらすぐ出ると思いますが、自分はちょっと忘れがちのところ書いときます。
 ◯CGI(昔のやつ)と違って、リクエストのたびに、プログラムが読み込まれることではなく、一度だけ実行されたら、Webサーバー上で待機状態になり、複数のクライアントからの要求に対して並行に動作できます。

●役割
すべてのリクエストを受け取る ー> URLにマッピングされるcontroller委譲する ー> controllerがビジネスロジックを実行 ー>View名をもらって、レスポンス生成して返却

●ソース
(DispatcherServletの親クラス)
public abstract class HttpServletBean extends HttpServlet implements EnvironmentCapable, EnvironmentAware {

//Servletの初期化メソッド
public final void init() throws ServletException {
if (logger.isDebugEnabled()) {
logger.debug("Initializing servlet '" + getServletName() + "'");
}

// Set bean properties from init parameters.
try {
//web.xmlの<servlet>の<init-param>に定義したものをPropertyValuesとして読み込む
//requiredPropertiesはaddRequiredProperty()によって、必ずweb.xmlで指定しなければいけないプロパティを設定することが可能、DispatcherServletには必須のプロパティがない
PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
//SpringFrameworkに使わせるため、このservlet(DispatcherServlet)をBeanWrapperに変換する
//BeanWrapperはSpringのlow-levelのJavaBeans infrastructureであり、Beanのあるpropertyをgetまたはsetする能力を持っている
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
//Resource種別プロパティの解析ツールを登録、ようするに、このservletの中でResource.classのプロパティに出会ったら、Spring自定義のResourceEditorオブジェクトで解析する
bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
//子供クラスに継承させるため、残ったメソッド
initBeanWrapper(bw);
//<init-param>から読み込んでいたプロパティをservletに注入
bw.setPropertyValues(pvs, true);
}
catch (BeansException ex) {
logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
throw ex;
}

// Let subclasses do whatever initialization they like.
//DispatcherServletの場合、この子の親クラスであるFrameworkServletの中で実行している
initServletBean();

if (logger.isDebugEnabled()) {
logger.debug("Servlet '" + getServletName() + "' configured successfully");
}
}
}

public abstract class FrameworkServlet extends HttpServletBean implements ApplicationContextAware {
protected final void initServletBean() throws ServletException {
...
try {
this.webApplicationContext = initWebApplicationContext();
initFrameworkServlet();
}
...
}

protected WebApplicationContext initWebApplicationContext() {
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;

//まず、ここのwebApplicationContextはContextLoaderで生成したwebApplicationContextと違うものです。
//子供かな(WebApplicationContext for namespace 'spring-servlet-servlet': startup date [Thu Mar 19 17:54:40 JST 2015]; parent: Root WebApplicationContext)
//nullチェックの理由は、FrameworkServletのコンストラクターによって、既に指定ずみの可能性がある
if (this.webApplicationContext != null) {
// A context instance was injected at construction time -> use it
wac = this.webApplicationContext;
if (wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
if (!cwac.isActive()) {
// The context has not yet been refreshed -> provide services such as
// setting the parent context, setting the application context id, etc
if (cwac.getParent() == null) {
// The context instance was injected without an explicit parent -> set
// the root application context (if any; may be null) as the parent
cwac.setParent(rootContext);
}
configureAndRefreshWebApplicationContext(cwac);
}
}
}
if (wac == null) {
//web.xmlのcontextAttributeを使って、servletContext中の該当プロパティを検索する
//defaultはWebApplicatioContext.class.getName() + ".ROOT"となる
// No context instance was injected at construction time -> see if one
// has been registered in the servlet context. If one exists, it is assumed
// that the parent context (if any) has already been set and that the
// user has performed any initialization such as setting the context id
wac = findWebApplicationContext();
}
if (wac == null) {
//ローカルで作成
// No context instance is defined for this servlet -> create a local one
wac = createWebApplicationContext(rootContext);
}

if (!this.refreshEventReceived) {
// Either the context is not a ConfigurableApplicationContext with refresh
// support or the context injected at construction time had already been
// refreshed -> trigger initial onRefresh manually here.
onRefresh(wac);
}

if (this.publishContext) {
// Publish the context as a servlet context attribute.
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
"' as ServletContext attribute with name [" + attrName + "]");
}
}

return wac;
}
}