JSP 기본 코드(WEB-XML, JSFUNCTION, JDBConnect, CookieManager)

꿈꾸는하늘·2024년 3월 9일

JSP

목록 보기
2/25

* WEB-XML

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>golf</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    <welcome-file>default.htm</welcome-file>
  </welcome-file-list>
  
  <context-param>
  	<param-name>MySqlDriver</param-name>
  	<param-value>com.mysql.jdbc.Driver</param-value>
  </context-param>
  <context-param>
  	<param-name>MySqlURL</param-name>
  	<param-value>jdbc:mysql://localhost:3306/test</param-value>
  </context-param>
  <context-param>
  	<param-name>MySqlId</param-name>
  	<param-value>root</param-value>
  </context-param>
  <context-param>
  	<param-name>MySqlPw</param-name>
  	<param-value>0000</param-value>
  </context-param>
  
  <!-- 한글 깨짐 방지를 위한 필터 설정 -->
  <filter>
    <filter-name>SetCharEncoding</filter-name>
    <filter-class>org.apache.catalina.filters.SetCharacterEncodingFilter</filter-class>
      <init-param>
        <param-name>encoding</param-name>
        <param-value>utf-8</param-value>
      </init-param>
  </filter>
  <filter-mapping>
    <filter-name>SetCharEncoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
</web-app>

* JSFUNCTION

package util;

import java.io.PrintWriter; // 기본 객체( 자바에서는 Ctrl+shift+ㅐ

import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspWriter;

public class JSFunction {
    // 메시지 알림창을 띄운 후 명시한 URL로 이동합니다.
	// msg : 알림창에 띄울 메시지
	// url : 알림창을 닫은 후 이동할 페이지의 URL
	// out : 자바스크립트 코드를 삽입할 출력 스트림 ( JSP의 out 내장 객체)
    public static void alertLocation(String msg, String url, JspWriter out) {
        try {
            String script = ""  // 삽입할 자바스크립트 코드
                          + "<script>"
                          + "    alert('" + msg + "');"
                          + "    location.href='" + url + "';"
                          + "</script>";
            out.println(script);  // 자바스크립트 코드를 out 내장 객체로 출력(삽입)
        }
        catch (Exception e) {}
    }

    // 메시지 알림창을 띄운 후 이전 페이지로 돌아갑니다.
    public static void alertBack(String msg, JspWriter out) {
        try {
            String script = ""
                          + "<script>"
                          + "    alert('" + msg + "');"
                          + "    history.back();"
                          + "</script>";
            out.println(script);
        }
        catch (Exception e) {}
    }
}

* JDBConnect

코드를package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletContext;

public class JDBConnect {
	public Connection con;	//DB와 연결
	public Statement stmt;  //정적쿼리문 실행
	public PreparedStatement psmt;  //동적쿼리문 실행
	public ResultSet rs;  //select 결과 저장


	public JDBConnect() {
	    try {
	        // JDBC 드라이버 로드
	    	// 객체 생성
	        Class.forName("com.mysql.jdbc.Driver");
	
	        // DB에 연결
	        String url = "jdbc:mysql://localhost:3306/test";  //test : DB명
	        String id = "root";
	        String pwd = "0000"; //처음 mySQL 접속시 DB연결 비밀번호
	        con = DriverManager.getConnection(url, id, pwd); 
	
	        System.out.println("DB 연결 성공(기본 생성자)");
	    }
	    catch (Exception e) {     
	    	System.out.println("에러 발생");
	        e.printStackTrace();
	    }
	}
	
	public JDBConnect(String driver, String url, String id, String pw) {
		try {
			Class.forName(driver);
			con = DriverManager.getConnection(url, id, pw);
			System.out.println("DB 연결 성공( 인수 생성자 1 )");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public JDBConnect(ServletContext application) {
		try {
			String driver = application.getInitParameter("MySqlDriver");
			
			Class.forName(driver);
			
			String url = application.getInitParameter("MySqlURL");
			String id = application.getInitParameter("MySqlId");
			String pw = application.getInitParameter("MySqlPw");
			
			con=DriverManager.getConnection(url, id, pw);
			System.out.println("DB 연결 성공( 인수 생성자 2 )");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}
	
	public void close() {

		try {
			if(rs!=null)rs.close();
			if(stmt!= null) stmt.close();
			if(psmt !=null) psmt.close();
			if(con!= null) con.close();
			System.out.println("JDBC 자원해제");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
}
	

* CookieManager

package util;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieManager {
	
	public static void makeCookie(HttpServletResponse response, String cName,
			String cValue, int cTime) {
		Cookie cookie = new Cookie(cName, cValue);
		cookie.setPath("/");
		cookie.setMaxAge(cTime);
		response.addCookie(cookie);
	}
	
	public static String readCookie(HttpServletRequest request, String cName) {
		String cookieValue="";
		Cookie[] cookies = request.getCookies();
		if(cookies !=null) {
			for(Cookie c : cookies) {
				String cookieName = c.getName();
				if(cookieName.equals(cName)) {
					cookieValue=c.getValue();
				}
			}
		}
		return cookieValue;
	}
	
	public static void deleteCookie(HttpServletResponse response, String cName) {
		makeCookie(response, cName, "", 0);
	}

}

해당 네가지 코드는 항상 가지고 다니면서 사용하고자하는 코드로 수정하여 사용할 것

0개의 댓글