상세 컨텐츠

본문 제목

jsp filter 한글 필터, 캐릭터 인코딩 필터

JSP

by kwanghyup 2020. 7. 6. 20:04

본문

테스트 JSP페이지

 - /view/encodingTest.jsp,

 - /view/to.jsp 

 

encodingTest.jsp 

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/view/to.jsp" method="post">
    <input type="text" name="id">
    <input type="submit" value="전송">
</form>
</body>
</html>

to.jsp

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<%
    String id = request.getParameter("id");
%>
출력 : <%= id %>
</body>
</html>

 

필터 설정 전 테스트를 하면 한글이 깨진다. 

 

필터 클래스 : CharacterEncodingFilter

package filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;

@WebFilter(urlPatterns = "/*",
        initParams = {@WebInitParam(name = "encoding", value = "utf-8")}
)
public class CharacterEncodingFilter implements Filter {

    private String encoding;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        encoding = filterConfig.getInitParameter("encoding");
        if(encoding==null){
            encoding = "UTF-8";
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding(encoding);
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}

 

관련글 더보기

댓글 영역