String getParameter(String name)

: name이름으로 전송되어 온 파라미터값을 반환해 주는 메소드

: HttpServletRequest에서 제공.

: 하나만 받음.





String[] getParameterValues(String paramName)

: 여러개 파라미터 값 처리

: checkbox같은 값 처리




ex>checkbox 처리.

- test01.html

<!DOCTYPE html>

<html>

<head>

<meta charset="EUC-KR">

<title>Insert title here</title>

</head>

<body>

<h1>강아지선택</h1>

<form action="dog" method="post">

<input type="checkbox" name="dog" value="진돗개">진돗개

<input type="checkbox" name="dog" value="푸들">푸들

<input type="checkbox" name="dog" value="삽살개">삽살개

<input type="submit" value="send">

</form>

</body>

</html>








MultiRequest.java


package test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


/**

 * Servlet implementation class MultiRequest

 */

@WebServlet("/dog")

public class MultiRequest extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {

// TODO Auto-generated method stub


   //한글처리

request.setCharacterEncoding("euc-kr");

response.setContentType("text/html;charset=euc-kr");

PrintWriter out = response.getWriter();

String[] dog = request.getParameterValues("dog");

out.println("<html>");

out.println("<head>");

out.println("</head>");

out.println("<body>");

out.println("<table>");

out.println("<tr>");

for(int i=0;i<dog.length;i++){

out.println("<td>");

out.println(dog[i]);

out.println("</td>");

}

out.println("</tr>");

out.println("</table>");

out.println("</body>");

out.println("</html>");

}

}








'WEB > JSP' 카테고리의 다른 글

11. JSP 예제1  (0) 2013.04.19
10. JSP - 특정페이지로 이동방법(forward/redirect)  (0) 2013.04.19
8. 한글 처리  (0) 2013.04.18
7. Servlet 컨텍스트 영역에 값넣기  (0) 2013.04.18
6. Servlet - connection pool  (0) 2013.04.18


- 클라이언트 즉, 브라우저에서 문자를 처리하는 방식과 서버에서 문자를 처리하는 방식이 같아야 한다.

브라우저에서 euc-kr로 했으면 서버에서도 euc-kr로 해야 인식됨.



GET방식


- 이클립스 server폴더 / server.xml 


...

<Connector connectionTimeout="20000" port="8081" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="euc-kr"/>

..


추가.

서버 재시작.




POST방식

request.setCharacterEncoding("euc-kr")


ex>

protected void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

req.setCharacterEncoding("euc-kr");

...













서블릿 컨텍스트 영역에 값 넣기 예제

 << 서블릿의 영역(scope) ** >>

  1. ServletContext영역

  - 모든 서블릿이 공유하는 영역

  - 하나의 웹어플리케이션당 하나가 만들어짐.


  2. ServletConfig영역

  - 서블릿 하나당 할당되는 영역



1. web.xml

2. main.html

3. MyServlet.java

4. ServletScope.java

5. ServletScope1.java

6. TestServlet.java




 web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

  <display-name>day02_servlet01</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  <servlet>

  <servlet-name>myservlet</servlet-name>

  <servlet-class>test.servlet.MyServlet</servlet-class>

  </servlet>

  <servlet-mapping>

  <servlet-name>myservlet</servlet-name>

  <url-pattern>/my.do</url-pattern>

  </servlet-mapping>

  <!-- 서블릿 컨텍스트 영역에 값 넣기 -->

  <context-param>

  <param-name>user</param-name>

  <param-value>scott</param-value>

  </context-param>

  

  <servlet>

  <servlet-name>scope1</servlet-name>

  <servlet-class>test.servlet.ServletScope1</servlet-class>

  <!-- 초기화 파라미터 설정하기(서블릿컨피그를 통해 사용가능함.!!) -->

  <init-param>

  <param-name>id</param-name>

  <param-value>song</param-value>

  </init-param>

  </servlet>

  <servlet-mapping>

  <servlet-name>scope1</servlet-name>

  <url-pattern>/scope1.do</url-pattern>

  </servlet-mapping>

</web-app>



2. main.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Insert title here</title>

</head>

<body>

<a href="my.do">myservlet</a><br/>

<a href="scope.do">scope</a><br/>

<a href="test.do">test</a><br/>

</body>

</html>








3. MyServlet.java

; myservlet 클릭하면

package test.servlet;


import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class MyServlet extends HttpServlet{

//서블릿이 최초로 요청될때 딱한번만 호출됨.(초기화작업)

@Override

public void init() throws ServletException {

System.out.println("init메소드가 호출됨!!");

}

//서블릿이 종료될때 ( 메모리에서 제거될때 ) 호출됨.(자원해제등, .. )

//일정시간 동안 서블릿이 호출되지 않거나 웹서버가 종료되면 서블릿은 제거됨.

@Override

public void destroy() {

System.out.println("destroy");

}

// 서블릿을 요청할때마다 호출됨.

@Override

protected void service(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

resp.setContentType("text/html;charset=euc-kr");

PrintWriter pw = resp.getWriter();

pw.println("<h2>service메소드 호출!</h2>");

pw.close();

}

}



4. ServletScope.java

package test.servlet;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletContext;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


@WebServlet("/scope.do")

public class ServletScope extends HttpServlet{

@Override

protected void service(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {


//서블릿컨텍스트 객체 얻어오기

ServletContext sc = getServletContext();


//서블릿컨텍스트 영역에 값넣기

sc.setAttribute("url", "localhost");


//서블릿컨텍스트 영역에서 값 꺼내오기

String url=(String)sc.getAttribute("url");


//web.xml에 설정된 초기화파라미터 읽어오기.

String user = sc.getInitParameter("user");

resp.setContentType("text/html;charset=euc-kr");

PrintWriter pw = resp.getWriter();

pw.println("url:" + url);

pw.println("user:" + user);

pw.println("<a href='test.do'>testservlet</a><br/>");

pw.close();

}

}



; user에 scott를 보여준다.(xml에서 읽기)



5. ServletScope1.java

package test.servlet;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletConfig;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class ServletScope1 extends HttpServlet{

@Override

protected void service(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {


//서블릿컨피그 객체 얻어오기.

ServletConfig sc = getServletConfig();

String id = sc.getInitParameter("id");


resp.setContentType("text/html;charset=euc-kr");

PrintWriter pw = resp.getWriter();

pw.println("id:" + id);

pw.close();

}

}







6. TestServlet.java

package test.servlet;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletContext;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


@WebServlet("/test.do")

public class TestServlet extends HttpServlet {

@Override

protected void service(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {


ServletContext sc=getServletContext();

String url=(String)sc.getAttribute("url");


resp.setContentType("text/html;charset=euc-kr");

PrintWriter pw = resp.getWriter();

pw.println("서블릿컨텍스트에 담긴 url:" + url);

pw.close();

}

}






'WEB > JSP' 카테고리의 다른 글

9. JSP - Servlet 파라미터 받기  (0) 2013.04.18
8. 한글 처리  (0) 2013.04.18
6. Servlet - connection pool  (0) 2013.04.18
5. Servlet예제 - doGet, doSet  (0) 2013.04.18
4. JSP - Servlet 예제  (0) 2013.04.18

[[ 컨넥션 풀 ]]


- DBMS와 접속된 컨넥션들을 여러개 만들어 놓고(컨넥션풀) DB와 접속할때 사용중이지 않은  컨넥션 객체를 얻어와 사용하고 작업이 끝나면 컨넥션객체를 다시 반환한다.


 - 성능향상을 위해 사용한다.


 - 아파치 dbcp 설정으로 사용하지만 아래는 connection pool을 작성해본 소스임.




[ ConnectionPoolBean.java ]


package test.db;

import java.sql.*;
import java.util.*;


public class ConnectionPoolBean{
    String url, usr, pwd;
    HashMap<Connection,Boolean> h; //pool장
    int increment = 3;
   
    public ConnectionPoolBean() throws ClassNotFoundException, SQLException{
        Connection con = null;
        try{
            Class.forName("oracle.jdbc.OracleDriver");
        }catch(ClassNotFoundException cnfe){
           System.out.println(cnfe.getMessage());
        }
        url = "jdbc:oracle:thin:@localhost:1521:XE";
        usr = "scott";
        pwd = "tiger";
        h = new HashMap<Connection,Boolean>();
        for(int i=0; i<5; i++)
        {
            //컨넥션 객체 얻어오기
            con = DriverManager.getConnection(url, usr, pwd);
            //컨넥션객체를 Map에 담기(사용중이 아닌 상태라는 표시로 false저장)
            h.put(con,false);
        }
        System.out.println("ConnectionPoolBean created ...");
    }
    //사용중인 아닌 컨넥션 반환
    public synchronized Connection getConnection()
        throws SQLException{
        Connection con = null;
        Boolean b = null;
        Set<Connection> e = h.keySet();
        Iterator<Connection> it=e.iterator();
        while(it.hasNext()){
            //Map에서 컨넥션 얻어오기
            con = it.next();
            //상태 얻어오기(사용중:true,사용중이 아님:false)
            b = h.get(con);
            if(!b){//사용중이지 않으면
                //사용중인 상태(true)로 바꾸고
                h.put(con,true);
                //컨넥션 리턴
                return con;
            }
        }
        //컨넥션이 모두 사용중일때 새로운 컨넥션을 3개 얻어와 Map에 저장
        for(int i=0; i<increment; i++){
            h.put(DriverManager.getConnection(url,usr,pwd), false);
        }
        return getConnection();
    }
    public void returnConnection(Connection returnCon)
        throws SQLException {
        Connection con = null;
        Set<Connection> e = h.keySet();
        Iterator<Connection> it=e.iterator();
        while(it.hasNext()){
            con = it.next();
            if(con == returnCon){
                h.put(con, Boolean.FALSE);
                break;
            }
        }
        keepConSu(5);
    }
    //사용중이지 않은 컨넥션 객체를 su만큼 유지하는 메소드
    public void keepConSu(int su) throws SQLException{
        Connection con = null;
        Boolean b = null;
        int count = 0;
        Set<Connection> e = h.keySet();
        Iterator<Connection> it=e.iterator();
        while(it.hasNext()){
            con = it.next();
            b = h.get(con);
            if(!b){//컨넥션이 사용중이 아니면
                count++;//사용중이지 않은 컨넥션 갯수 세기
                if(count >su){//사용중이지 않은 컨넥션이 5보다 크면
                    h.remove(con);//Map에서 제거하기
                    con.close();//db접속 해제하기
                }
            }
        }
    }
    public void closeAll() throws SQLException{
        Connection con = null;
        Set<Connection> e = h.keySet();
        Iterator<Connection> it=e.iterator();
        while(it.hasNext()){
            con = it.next();
            h.remove(con);
            con.close();
        }
    }
}





커넥션풀 사용 예제>

Connection pool을 사용하여 con객체로 db접속 후 insert, select 처리 하는 예제 (db는 oracle xe11g )


[[ web.xml ]]

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>day03_ConnectionPool</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>insert</servlet-name>
    <servlet-class>test.servlet.InsertServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>insert</servlet-name>
    <url-pattern>/insert.do</url-pattern>
  </servlet-mapping>
</web-app>



[[ main.html ]]

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<a href="insert.html">회원추가</a><br/>
<a href="list.do">회원목록</a><br/>
</body>
</html>



[[ ListServlet.java ]]

package test.servlet;


import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import javax.servlet.ServletContext;

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 test.db.ConnectionPoolBean;


/**

 * Servlet implementation class ListServlet

 */

@WebServlet("/list.do")

public class ListServlet extends HttpServlet {

private static final long serialVersionUID = 1L;


ConnectionPoolBean cp;

public void init() throws ServletException {

ServletContext sc=getServletContext();

cp=(ConnectionPoolBean)sc.getAttribute("cp");

if(cp==null){

try{

cp=new ConnectionPoolBean();

sc.setAttribute("cp", cp);

}catch(SQLException se){

System.out.println(se.getMessage());

}catch(ClassNotFoundException ce){

System.out.println(ce.getMessage());

}

}

}


protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html;charset=euc-kr");

PrintWriter pw = response.getWriter();

Connection con = null;

PreparedStatement pstmt= null;

ResultSet rs = null;

try{

con=cp.getConnection();

String sql="select * from members";

pstmt=con.prepareStatement(sql);

rs = pstmt.executeQuery();

while(rs.next()){

pw.println(rs.getString(1) + ",");

pw.println(rs.getString(2) + ",");

pw.println(rs.getString(3) + ",");

pw.println(rs.getString(4) + ",");

pw.println(rs.getString(5) + "<br/>");

}

pw.close();

}catch(SQLException se){

System.out.println(se.getMessage());

}finally{

try{

if(rs!=null) rs.close();

if(pstmt!=null) pstmt.close();

if(con!=null) cp.returnConnection(con);

}catch(SQLException se){

System.out.println(se.getMessage());

}

}

}

}



[[ insert.html ]]

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<style type="text/css">
    #regbox{
        width:300px;
    }
    #regbox label{
        width:100px;
        display: block;
        float:left;
    }
</style>
</head>
<body>
<form method="post" action="insert.do">
    <fieldset id="regbox">
        <legend>회원가입</legend>
        <label for="id">아이디</label>
        <input type="text" name="id"/><br/>
        <label for="pwd">비밀번호</label>
        <input type="password" name="pwd"/><br/>
        <label for="email">이메일</label>
        <input type="text" name="email"/><br/>
        <label for="phone">전화번호</label>
        <input type="text" name="phone"/><br/>
        <input type="submit" value="가입"/>
        <input type="reset" value="취소"/>
    </fieldset>
</form>
</body>
</html>



[[ InsertServlet.java ]]

package test.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import test.db.ConnectionPoolBean;

public class InsertServlet extends HttpServlet{

    ConnectionPoolBean cp;
    //서블릿이 처음으로 요청될때 호출
    //서블릿컨텍스트에서 컨넥션 풀 얻어오기
    @Override
    public void init() throws ServletException {
        //서블릿컨텍스트 참조객체 얻어오기
        ServletContext sc=getServletContext();
        try{
            //서블릿컨텍스트 영역에서 컨넥션풀 얻어오기
            cp=(ConnectionPoolBean)sc.getAttribute("cp");
            //서블릿컨텍스트 영역에 컨넥션풀이 존재하지 않으면
            if(cp==null){
                //컨넥션풀 객체 생성
                cp=new ConnectionPoolBean();
                //서블릿컨텍스트 영역에 컨넥션풀 객체를 저장하기
                sc.setAttribute("cp",cp);
            }
        }catch(ClassNotFoundException ce){
            System.out.println(ce.getMessage());
        }catch(SQLException se){
            System.out.println(se.getMessage());
        }
    }
   
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //전송된 파라미터 얻어오기
        req.setCharacterEncoding("euc-kr");
        String id=req.getParameter("id");
        String pwd=req.getParameter("pwd");
        String email=req.getParameter("email");
        String phone=req.getParameter("phone");
        //파라미터를 db에 저장하기
        Connection con=null;
        PreparedStatement pstmt=null;
        try{
            //컨넥션풀에서 컨넥션객체 얻어오기
            con=cp.getConnection();
            String sql="insert into members values(?,?,?,?,sysdate)";
            pstmt=con.prepareStatement(sql);
            pstmt.setString(1,id);
            pstmt.setString(2,pwd);
            pstmt.setString(3,email);
            pstmt.setString(4,phone);
            pstmt.executeUpdate();
        }catch(SQLException se){
            System.out.println(se.getMessage());
        }finally{
            try{
                if(pstmt!=null) pstmt.close();
                //컨넥션풀에 컨넥션객체 반환하기
                if(con!=null) cp.returnConnection(con);
            }catch(SQLException se){}
        }
        //결과 응답하기
        resp.setContentType("text/html;charset=euc-kr");
        PrintWriter pw=resp.getWriter();
        pw.println("회원가입성공!");
        pw.close();
    }
}



'WEB > JSP' 카테고리의 다른 글

8. 한글 처리  (0) 2013.04.18
7. Servlet 컨텍스트 영역에 값넣기  (0) 2013.04.18
5. Servlet예제 - doGet, doSet  (0) 2013.04.18
4. JSP - Servlet 예제  (0) 2013.04.18
3. Servlet 작성 방법  (0) 2013.04.18

- 서블릿 사용 시 service메서드가 아닌  doGet, doSet 메소드 사용 예


- GET방식으로 요청이 전송되어 올 경우    doGet(HttpServletRequest req, HttpServletResponse resp)


- POST방식으로 요청이 전송되어 올 경우   doPost(HttpServletRequest req, HttpServletResponse resp)


- doGet, doPost를 따로 호출하여 사용해야 할때 사용한다.
단, service메소드가 오버라이딩되면 doGet,doPost메소드는 자동호출되지 않음


- 어노테이션 ( annotation )

java 5.0부터 지원되는 기술로, 기존 설정파일(web.xml)에서 제공하는 설정내용들을 설정파일에서 설정하지 않아도 해당 소스내에 설정방법을 제공하여 처리하는 기능

@WebServlet("/")



0. web.xml

1. main.html --> MyLoginServlet.java  ( <a>태그 Get방식으로 서블릿 전송 )

2. MyLoginServlet.java

3. Login.html --> LoginServlet.java ( submit 으로 Post방식으로 서블릿 전송 )

4. LoginServlet.java




[ web.xml ]


<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

id="WebApp_ID" version="3.0">

<display-name>day02_servlet01</display-name>

<welcome-file-list>

<welcome-file>index.html</welcome-file>

<welcome-file>index.htm</welcome-file>

<welcome-file>index.jsp</welcome-file>

<welcome-file>default.html</welcome-file>

<welcome-file>default.htm</welcome-file>

<welcome-file>default.jsp</welcome-file>

</welcome-file-list>

<servlet>

<servlet-name>login</servlet-name>

<servlet-class>test.servlet.LoginServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>login</servlet-name>

<url-pattern>/login.do</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>mylogin</servlet-name>

<servlet-class>test.servlet.MyLoginServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>mylogin</servlet-name>

<url-pattern>/mylogin.do</url-pattern>

</servlet-mapping>

</web-app>


[main.html]

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<a href="mylogin.do">로그인하기</a>
</body>
</html>




[ MyLoginServlet.java ]


package test.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class MyLoginServlet extends HttpServlet{


    //GET방식으로 요청시 호출->로그인페이지로 이동하기
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //페이지이동하기
        resp.sendRedirect("login.html");
    }


    //POST방식으로 요청시 호출->로그인처리
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("euc-kr");
        String id=req.getParameter("id");
        String pwd=req.getParameter("pwd");
        resp.setContentType("text/html;charset=euc-kr");
        //응답하기위한 출력스트림 얻어오기
        PrintWriter pw=resp.getWriter();
        pw.println("<html>");
        pw.println("<head></head>");
        pw.println("<body>");
        if(id.equals("song") && pwd.equals("1234")){
            pw.println(id+"님 로그인 되셨습니다.");
        }else{
            pw.println("아이디 또는 비밀번호가 맞지 않습니다.");
        }
        pw.println("</body>");
        pw.println("</html>");
        pw.close();   
       
    }
}




[log.html]


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="mylogin.do">
아이디 <input type="text" name="id"/><br/>
비밀번호 <input type="text" name="pwd"/><br/>
<input type="submit" value="로그인"/>
</form>
</body>
</html>





Ex 2> 

[ LoginServlet.java ]


- service메소드는 get이든 post방식이든 무조건 호출됨.

- service메소드가 override되면 doGet, doPost는 호출되지 않는다.



package test.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class LoginServlet extends HttpServlet{
    //GET방식이든 POST방식이든 무조건 호출됨
    //service메소드가 오버라이딩되면 doGet,doPost메소드는 자동호출되지 않음
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("text/html;charset=euc-kr");
        //응답하기위한 출력스트림 얻어오기
        PrintWriter pw=resp.getWriter();
        pw.println("<html>");
        pw.println("<head></head>");
        pw.println("<body>");
        pw.println("<h2>Service메소드 호출!</h2>");
        pw.println("</body>");
        pw.println("</html>");
        pw.close();   
    }
    //get방식으로 요청되었을때 호출됨
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("text/html;charset=euc-kr");
        //응답하기위한 출력스트림 얻어오기
        PrintWriter pw=resp.getWriter();
        pw.println("<html>");
        pw.println("<head></head>");
        pw.println("<body>");
        pw.println("<h2>GET방식으로 요청되었어요!</h2>");
        pw.println("</body>");
        pw.println("</html>");
        pw.close();   
    }
    //post방식으로 요청되었을때 호출됨
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("text/html;charset=euc-kr");
        //응답하기위한 출력스트림 얻어오기
        PrintWriter pw=resp.getWriter();
        pw.println("<html>");
        pw.println("<head></head>");
        pw.println("<body>");
        pw.println("<h2>POST방식으로 요청되었어요!</h2>");
        pw.println("</body>");
        pw.println("</html>");
        pw.close();   
    }
}




'WEB > JSP' 카테고리의 다른 글

7. Servlet 컨텍스트 영역에 값넣기  (0) 2013.04.18
6. Servlet - connection pool  (0) 2013.04.18
4. JSP - Servlet 예제  (0) 2013.04.18
3. Servlet 작성 방법  (0) 2013.04.18
2. 웹응용프로그램 디렉토리구조  (0) 2013.04.18

+ Recent posts