ajax를 써서 id를 입력할때마다 검사하게 했는데 302 리다이렉트가 뜨네요,,,

조회수 4031회

이미지

이미지

아래는 코드입니다.

----------------- join.jsp -----------------

<!-- 실시간 ID체크 -->
<script type="text/javascript">
    var xmlReq; // 전역변수로 지정.
    // Ajax 객체 생성 과정
    function createAjax() {
        xmlReq = new XMLHttpRequest();
    }

    // Ajax 객체를 이용한 데이터 전송 과정
    function RealTimeIDCheck() {
        createAjax();
        var m_id = document.getElementById("m_id").value;
        xmlReq.onreadystatechange = callBack; // 괄호 열고닫고가 틀리다.!
        xmlReq.open("POST", "id_check_receive.do?m_id=" + m_id, true);
        xmlReq.send(null);
        // send가 끝나고나면 비동기식이기 때문에 프로그램이 계속 진행된다.
    }

    // 콜백 함수 과정
    function callBack() {
        if (xmlReq.readyState == 4) {
            if (xmlReq.status == 200) {
                printData();
            }
        }
    }

    // 결과 출력 과정
    function printData() {
        var result = xmlReq.responseXML;

        var rootNode = result.documentElement;
        // <root>true</root> , <root>false</root>
        var rootValue = rootNode.firstChild.nodeValue;
        var rootTag = document.getElementById("result");

        var idNode = rootNode.getElementsByTagName("m_id");
        var idValue = idNode.item(0).firstChild.nodeValue;
        var idTag = document.getElementById("idTxt");

        if (rootValue == "true") {
            rootTag.innerHTML = "사용 가능한 아이디 : ";
            idTag.innerHTML = "<br>" + idValue;
        } else {
            rootTag.innerHTML = "중복된 아이디 : ";
            idTag.innerHTML = "<br>" + idValue;
        }
    }
</script>
<input type="text" id="m_id" name="m_id" onkeyup="RealTimeIDCheck()" autocomplete="off">
<span id="result" style="color: BLUE;"></span> 
<span id="idTxt" style="color: green;"></span> 

----------------- MemberController.java -----------------

@RequestMapping(value = "id_check_receive.do", method = RequestMethod.POST)
    public void id_check(@RequestParam("m_id") String m_id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("id가 있니 : " + m_id);

        StringBuffer str = new StringBuffer();
        str.append("<?xml version='1.0' encoding='utf-8'?>");
        str.append("<root>");

        int resultNum = Memberservice.idCheck(m_id);
        System.out.println("id가 있니 : " + resultNum);
        if (Memberservice.idCheck(m_id) != 0) {
            str.append("true");
        } else {
            str.append("false");
        }
        str.append("<id>" + m_id + "</id>");
        str.append("</root>");

        response.setContentType("text/xml;charset=utf-8");
        response.getWriter().write(str.toString());
    }

----------------- servlet-context.xml -----------------

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

    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />


    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <context:component-scan base-package="talent.seok" />



</beans:beans>

----------------- root-context.xml -----------------

<?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: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/context 
        http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <!-- Root Context: defines shared resources visible to all other web components -->

    <!-- database.properties 읽어오기 -->
    <bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="/WEB-INF/database.properties" />
    </bean>

    <!-- dataSource설정(database.properties에 설정된 값으로 넣기) -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${user}" />
        <property name="password" value="${password}" />
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation"
            value="classpath:talent/seok/mybatis/mybatis-config.xml" />
    </bean>
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory" />
    </bean>

    <!-- 어노테이션 기반으로 객체 자동 생성하기 -->
    <context:annotation-config />
    <context:component-scan base-package="talent.seok">
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
    </context:component-scan>


    <!-- Multipart Resolaver -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />


    <!-- gmail -->
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.gmail.com" />
        <property name="port" value="587" />
        <property name="defaultEncoding" value="utf-8" />
        <property name="username" value="syareun726@gmail.com" />
        <property name="password" value="rlawlals3" />

        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.starttls.enable">true</prop>
                <prop key="mail.smtp.auth">true</prop>
            </props>
        </property>

    </bean>
    <bean id="email" class="talent.seok.email.Email">
    </bean>
    <bean id="emailSender" class="talent.seok.email.EmailSender">
    </bean>



</beans>

며칠동안 해맨것이 부끄럽네요,,,,,ㅠㅜㅠㅜ 부탁드립니다!

  • (•́ ✖ •̀)
    알 수 없는 사용자

2 답변

  • 직접 테스트를 해보지는 못했습니다만, InternalResourceViewResolver 때문인 것 같습니다.

    다음을 순서대로 적용해보세요. (앞에 방법에 안되면 다음 방법으로...)

    첫 번째,

           response.getWriter().write(str.toString());
           response.getWriter().flush(); 
           // 강제로 버퍼에 있는 내용을 스트림에 쓰도록 합니다.
    }
    

    두 번째, HTTP Status를 200 OK로 응답하게 만듦.

     @RequestMapping(value = "id_check_receive.do", method = RequestMethod.POST) 
     @ResponseStatus(HttpStatus.OK)
     public void id_check(@RequestParam("m_id") String m_id, HttpServletRequest request, HttpServletResponse response) throws IOException {
    
  • 캐시가 원인일 가능성도 있어 보이네요.

    해당 브라우저에서 처음 입력하는 아이디 값(ex:testtesttest)을 전송했을때도 302 리턴인지 200 리턴인지 확인해주세요~

    캐시 원인이 맞다면 timestamp 등으로 요청하는 url을 매번 변경되도록 하는 방법이 있긴 합니다.

    xmlReq.open("POST", "id_check_receive.do?m_id=" + m_id + "&date=" new Date().getTime(), true);
    
    • (•́ ✖ •̀)
      알 수 없는 사용자

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)