MVC 게시판

로그인-5

beejaem 2022. 1. 3. 21:29

앱과 연동과정에서 서버도 손을 보아야 했다.

MVC패턴을 적용하기 위해 요청데이터를 loginvo 클래스를 만들어 매핑을 시켰다.

public class LoginVO {
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    String id ;
    String pwd;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    String msg;
}

이를 위해 @RequestBody를 사용했더니 앱 연동에는 문제가 없었지만 웹과 통신하려하자 415error가 발생했다.

@RequestMapping (value="/login",method = RequestMethod.POST)
@ResponseBody
public LoginVO Login(@RequestBody LoginVO loginvo){
    String driver = "org.mariadb.jdbc.Driver";
    Connection con = null;
    PreparedStatement pstmt;
    Statement stmt = null;
    ResultSet rs = null;
    String user_num = null;
    try {
        Class.forName(driver);
        con = DriverManager.getConnection(
                "jdbc:mariadb://127.0.0.1:3306/logindb",
                "root",
                "1995sus");

        if( con != null ) {
            System.out.println("DB 접속 성공");
        }
        String id = loginvo.id;
        String pwd = loginvo.pwd;
        stmt = con.createStatement();
        String sql = "SELECT user_num FROM USER WHERE id = '"+id+"' AND pwd = '"+pwd+"';";
        System.out.println(sql);
        rs = stmt.executeQuery(sql);
        rs.next();
        user_num = rs.getString("user_num");
        System.out.println(user_num);
        loginvo.setMsg(user_num);
    } catch (ClassNotFoundException e) {
        System.out.println("드라이버 로드 실패");
    } catch (SQLException e) {
        System.out.println("DB 접속 실패");
        e.printStackTrace();
    }

    return loginvo;
}

요청할 때 데이터 형태와 서버에서 읽으려는 데이터의 형태가 맞지 않아 문제가 발생했던 것 같다.

그래서 아래처럼 ajax에 요청 시 데이터형태를 설정해주었다.

$.ajax({
    type: 'post',
    url : 'http://localhost:3001/login',
    data : JSON.stringify(obj),
    dataType:'text',
    contentType: "application/json",
    success: function(data){
        alert(data);
    },
    error:function(request,status,error){
        console.log("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
    }
})

contentType을 json으로, data를 보낼때도 json으로 변환해서 요청하자 앱,웹이 정상적으로 서버와 연동이 가능했다.

 

'MVC 게시판' 카테고리의 다른 글

회원가입-2  (0) 2022.01.06
회원가입-1  (0) 2022.01.06
로그인-4  (0) 2022.01.03
로그인-3  (0) 2022.01.01
로그인-2  (0) 2021.12.28