2023. 1. 23. 10:39

출처: MVC基础框架项目的实现_孤狼灬笑的博客-CSDN博客

 

MVC基础框架项目的实现_孤狼灬笑的博客-CSDN博客

项目实现思路: 过滤器1(设置编码)--->过滤器2(事务管理)-->DispacherServlet-中央控制器(用于参数处理  invoke 视图处理)-->控制器:*Controller(*业务名字)-->IOC <beans>配置变量-->FruitServic-->FruitDAO调用BaseDAO-->B

blog.csdn.net

약간 수정했음.

 

ioc 부분

 

구현 클래스

 

applicationContext.xml

 

기본 HelloController.java

 

응용 CountriesController.java

 

java 8 이상에서 되는 -parameters 컴파일러 옵션 필수 (이렇게 하지 않으면, 메소드 파라미터의 이름을 가져올 수 없음)

참조: 

Maven, Gradle이면 소스코드에 삽입가능

 

intellij 에선

확인 후 빌드 -> 프로젝트 다시 빌드 

package com.sora.webapptest.controllers;

import com.sora.webapptest.dao.CountryDao;
import com.sora.webapptest.dto.Country;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

public class CountriesController {

    private String index(HttpServletRequest request) {
        CountryDao countryDao = new CountryDao();
        request.setAttribute("countryList", countryDao.getCountryList());
        return "country/index";
    }

    private String add() {
        return "country/add";
    }

    private String add_ok(String country_id, String country_name, Integer region_id) {
        Country country = new Country();
        country.setCountry_id(country_id);
        country.setCountry_name(country_name);
        country.setRegion_id(new BigDecimal(region_id));
        CountryDao countryDao = new CountryDao();

        countryDao.addCountry(country);

        return "redirect:countries.do";
    }

    private String edit(String cid, HttpServletRequest request) {
        if (cid != null) {
            CountryDao countryDao = new CountryDao();
            Country country = countryDao.getCountryByCid(cid);
            request.setAttribute("country", country);
            return "country/edit";
        }

        return "error";
    }

    private String update(String country_id, String country_name, Integer region_id) {
        Country country = new Country();
        country.setCountry_id(country_id);
        country.setCountry_name(country_name);
        country.setRegion_id(new BigDecimal(region_id));
        CountryDao countryDao = new CountryDao();
        countryDao.updateCountry(country);

        return "redirect:countries.do";

    }

    private String del(String cid) {
        if (cid != null) {
            CountryDao countryDao = new CountryDao();
            int result = countryDao.deleteCountry(cid);
            if (result == 1) {
                return "redirect:countries.do";
            }
        }
        return "error";
    }
}

 

package com.sora.webapptest.controllers;

public class HelloController {

    private String index() {
        return "index";
    }
}
<?xml version="1.0" encoding="UTF-8" ?>

<beans>
    <bean id="hello" class="com.sora.webapptest.controllers.HelloController" />
    <bean id="countries" class="com.sora.webapptest.controllers.CountriesController" />
</beans>
package com.sora.webapptest.ioc;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class ClassPathXmlApplicationContext implements BeanFactory {

    private Map<String, Object> beanMap = new HashMap<>();
    private String path = "applicationContext.xml";

    public ClassPathXmlApplicationContext() {
        this("applicationContext.xml");
    }

    public ClassPathXmlApplicationContext(String path) {
        if (path == null || path.equals("")) {
            throw new RuntimeException("path가 비어있습니다.");
        }
        try {
            InputStream inputStream = getClass().getClassLoader().getResourceAsStream(path);
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.parse(inputStream);


            NodeList beanNodeList = document.getElementsByTagName("bean");
            for (int i=0; i<beanNodeList.getLength(); i++) {
                Node beanNode = beanNodeList.item(i);
                if (beanNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element beanElement = (Element) beanNode;
                    String beanId = beanElement.getAttribute("id");
                    String className = beanElement.getAttribute("class");
                    Class beanClass = Class.forName(className);
                    Object beanObj = beanClass.newInstance();
                    beanMap.put(beanId, beanObj);


                }
            }


        } catch (ParserConfigurationException | IOException | SAXException | ClassNotFoundException |
                 InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Object getBean(String id) {
        return beanMap.get(id);
    }
}

 

package com.sora.webapptest.ioc;

public interface BeanFactory {
    Object getBean(String id);
}
package com.sora.webapptest;



import com.sora.webapptest.ioc.BeanFactory;
import com.sora.webapptest.ioc.ClassPathXmlApplicationContext;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

@WebServlet("*.do")
public class DispatcherServlet extends HttpServlet {

    private BeanFactory beanFactory;

    @Override
    public void init() throws ServletException {
        super.init();
        beanFactory = new ClassPathXmlApplicationContext();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        //http://localhost:8080/WebTestApp/hello.do
        //servlet path : /hello.do
        // /hello.do -> hello
        // hello -> HelloController
        String servletPath = req.getServletPath();
        servletPath = servletPath.substring(1);
        int lastDotIndex = servletPath.lastIndexOf(".do");
        servletPath = servletPath.substring(0, lastDotIndex);
        Object controllerBeanObj = beanFactory.getBean(servletPath);
        String operate = req.getParameter("operate");
        if (operate == null || operate.equals("")) {
            operate = "index";
        }
        try {
            Method[] methods = controllerBeanObj.getClass().getDeclaredMethods();
            for (Method method : methods) {
                if (operate.equals(method.getName())) {
                    Parameter[] parameters = method.getParameters();
                    Object[] parameterValues = new Object[parameters.length];
                    for (int i=0; i<parameters.length; i++) {
                        Parameter parameter = parameters[i];
                        String parameterName = parameter.getName();
                        if ("request".equals(parameterName)) {
                            parameterValues[i] = req;
                        } else if ("response".equals(parameterName)) {
                            parameterValues[i] = resp;
                        } else if ("session".equals(parameterName)) {
                            parameterValues[i] = req.getSession();
                        } else {
                            String parameterValue = req.getParameter(parameterName);
                            Object parameterObj = parameterValue;
                            String typeName = parameter.getType().getName();
                            if (parameterObj != null) {
                                if ("java.lang.Integer".equals(typeName)) {
                                    parameterObj = Integer.parseInt(parameterValue);
                                }
                            }
                            parameterValues[i] = parameterObj;
                        }
                    }
                    method.setAccessible(true);
                    Object returnObj = method.invoke(controllerBeanObj, parameterValues);
                    String methodReturnStr = (String) returnObj;
                    if (methodReturnStr.startsWith("redirect:")) {
                        String redirectStr = methodReturnStr.substring("redirect:".length());
                        resp.sendRedirect(redirectStr);
                    } else {
                        RequestDispatcher requestDispatcher = req.getRequestDispatcher("/WEB-INF/views/" + methodReturnStr + ".jsp");
                        requestDispatcher.forward(req, resp);
                    }
                }
            }
        } catch (InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }


    }


}

'JAVA' 카테고리의 다른 글

파일업로드 구현  (1) 2023.01.30
Dao JDBC #3  (0) 2023.01.18
DAO JDBC #2  (0) 2023.01.18
DAO jdbc  (0) 2023.01.18
Servletでいまの時間を表示する  (0) 2023.01.01
Posted by 다만사