「Spring MVC開発」DispatcherServletの使い方

Javaコード:
public interface HandlerAdapter {
public boolean supports(Object handler);
public void handle(Object handler);
}

public interface Controller {

}

public class HttpController implements Controller{
public void doHttpHandler(){
System.out.println(“http…");
}
}

public class SimpleController implements Controller{
public void doSimplerHandler(){
System.out.println(“simple…");
}
}

public class AnnotationController implements Controller{
public void doAnnotationHandler(){
System.out.println(“annotation…");
}
}

public class SimpleHandlerAdapter implements HandlerAdapter {
public void handle(Object handler) {
((SimpleController)handler).doSimplerHandler();
}

public boolean supports(Object handler) {
return (handler instanceof SimpleController);
}

}
public class HttpHandlerAdapter implements HandlerAdapter {

public void handle(Object handler) {
((HttpController)handler).doHttpHandler();
}

public boolean supports(Object handler) {
return (handler instanceof HttpController);
}

}
public class AnnotationHandlerAdapter implements HandlerAdapter {

public void handle(Object handler) {
((AnnotationController)handler).doAnnotationHandler();
}

public boolean supports(Object handler) {

return (handler instanceof AnnotationController);
}

}
//DispatcherServlet
import java.util.ArrayList;
import java.util.List;
public class DispatchServlet {

public static List<HandlerAdapter> handlerAdapters = new ArrayList<HandlerAdapter>();

public DispatchServlet(){
handlerAdapters.add(new AnnotationHandlerAdapter());
handlerAdapters.add(new HttpHandlerAdapter());
handlerAdapters.add(new SimpleHandlerAdapter());
}
public void doDispatch(){

SimpleController controller = new SimpleController();
HandlerAdapter adapter = getHandler(controller);
adapter.handle(controller);

}

public HandlerAdapter getHandler(Controller controller){
for(HandlerAdapter adapter: this.handlerAdapters){
if(adapter.supports(controller)){
return adapter;
}
}
return null;
}

public static void main(String[] args){
new DispatchServlet().doDispatch();
}

}

Java

Posted by arkgame