In the last post, we talked about the difference between Model1 and Model2. 

To know more about Model2, we need to know Java Servlet, EL(Expression Language), and JSTL(JSP Standard Tag Library). First, let us discuss about Java Servlet Class.

 

Java Servlet Class
Java Servlet Class means all the web programs that is written in Java language. This class can include the HTML, and JavaScript codes and it can print out the codes on the web browser right away. 

 

To create the Java Servlet Class in Eclipse, Java EE has to be selected as a perspective. 

In the new dynamic web project, in the src folder, create a new Servlet. 

The class name and the file name will be the same. As you can see, its superclass is automatically designated as the HttpServlet class, so this class will be inherited as extends.

Since we don't need any constructors, we are ticking out the box, and we will leave others as they are. 

Then, you will see this codes with doGet method and doPost method, as we checked the box.

package send;

import java.io.IOException;
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 HelloWorld
 */
@WebServlet(description = "My first Java Servlet", urlPatterns = { "/HelloWorld" })
public class HelloWorld extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

When you fun the code, you will see this on the browser. 

Here, this is called Annotation.

Let us change the code a bit.

package send;

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 HelloWorld
 */
@WebServlet(description = "My first Java Servlet", urlPatterns = { "/HelloWorld" })
public class HelloWorld extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Hello World!</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Hi there!!</h1>");
        out.println("</body>");
        out.println("</html>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

 Before running the code, if there are other files with the same annotation, you need to close them to run this well. 

To encode, in the jsp files, we used the contentType and the charset, whereas, in this servlet class, we use setContentType.

response.setContentType("text/html;charset=utf-8");

 

 

For better understanding, this time, let us make another servlet class with HTML file. 

 

Example 1

 

Method.java

doPost class is connected to the Call with get method, and the doGet class is connected to the Call with post method.

package send;

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 Method
 */
@WebServlet("/Method")
public class Method extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<h1>Processed with a get method.</h1>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<h1>Processed with a post method.</h1>");
	}

}

Method.html

The action has to correspond to the annotation(@) in the servlet class.

<html lang="en">
<head>
	<meta charset="utf-8">
</head>
<body>
	<!-- action = "/Project name/Servlet file name"  
		No package name needed.
	-->
	<form method="get" action="/jsppro/Method">
		<input type="submit" value="Called with get method">
	</form>

	<form method="post" action="/jsppro/Method">
		<input type="submit" value="Called with post method">
	</form>
</body>
</html>

 

Example 2

 

Let us exercise more with a little bit more complicated example. 

QueryString.html

<html lang="en">
 <head>
  <meta charset="utf-8">
 </head>
 <body>

<form method="get" action="/jsppro/QueryString">
ID : <input type="text" name="id"  size="20"> <br>
Password : <input type="password" name="pw"  size="20"> <br>
Name : <input type="text" name="name"  size="20"> <br>
Group : <input type="radio" name="group"  value="member"> Member
           <input type="radio" name="group"  value="Manager"> Manager<br>
Phone : <select name="phone1">
                 <option value="010" selected> 010 </option>    
                 <option value="011"> 011 </option>    
                 <option value="016"> 016 </option> 
                 <option value="017"> 017 </option>    
                 <option value="018"> 018 </option>    
                 <option value="019"> 019 </option>
           </select>              
    -      <input type="text" name="phone2" size="4" maxlangth="4">
    -
			<input type="text" name="phone3" size="4" maxlangth="4"><br>
			<input type="submit" value="Sumbit">
		</form>
	</body>
</html>

QueryString.java

package send;

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 QueryString
 */
@WebServlet(description = "Exercise", urlPatterns = { "/QueryString" })
public class QueryString extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub

		response.setContentType("text/html;charset=utf-8");

		PrintWriter out = response.getWriter();
		String id = "", name = "", vclass = "", phone1 = "", phone2 = "", phone3 = "";
		id = request.getParameter("id");
		name = request.getParameter("name");
		vclass = request.getParameter("group");
		phone1 = request.getParameter("phone1");
		phone2 = request.getParameter("phone2");
		phone3 = request.getParameter("phone3");
		
		out.println("<html><head></head><body>");
		out.println("The data that you inserted is processed with [GET method].<br> ID : <b>");
		out.println(id);
		out.println("</b><br> Name : <b>");
		out.println(name);
		out.println("</b><br> Group : <b>");
		out.println(vclass);
		out.println("</b><br> Phone : <b>");
		out.println(phone1);
		out.println("-");
		out.println(phone2);
		out.println("-");
		out.println(phone3);
		out.println("</b><br><a href='javascript:history.go(-1)'>Go back</a>");
		out.println("</body></html>");
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		response.setContentType("text/html;charset=utf-8");

		request.setCharacterEncoding("utf-8");
		
		PrintWriter out = response.getWriter();
		String id = "", name = "", vclass = "", phone1 = "", phone2 = "", phone3 = "";
		id = request.getParameter("id");
		name = request.getParameter("name");
		vclass = request.getParameter("group");
		phone1 = request.getParameter("phone1");
		phone2 = request.getParameter("phone2");
		phone3 = request.getParameter("phone3");
		
		out.println("<html><head></head><body>");
		out.println("The data that you inserted is processed with [POST method].<br> ID : <b>");
		out.println(id);
		out.println("</b><br> Name : <b>");
		out.println(name);
		out.println("</b><br> Group : <b>");
		out.println(vclass);
		out.println("</b><br> Phone : <b>");
		out.println(phone1);
		out.println("-");
		out.println(phone2);
		out.println("-");
		out.println(phone3);
		out.println("</b><br><a href='javascript:history.go(-1)'>Go back</a>");
		out.println("</body></html>");
		out.close();
	}

}

If you change the method from "get" to "post" it will change like this below.

Now, we will add the DTO and DAO classes. We also have to edit a little bit of QueryString.java.

We add this(below) is in the doPost class,

String pw = "";

this(below) to connect to the DTO and DAO.

QueryDTO query = new QueryDTO();
query.setId(id);
query.setPw(pw);
query.setName(name);
query.setVclass(vclass);
query.setPhone(phone1+"-"+phone2+"-"+phone3);
		
QueryDAO dao = QueryDAO.getInstance();
dao.insert(query);		//Sign up

 

QueryDTO.java

package send;

public class QueryDTO {

	private String id;
	private String pw;
	private String name;
	private String vclass;
	private String phone;
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPw() {
		return pw;
	}
	public void setPw(String pw) {
		this.pw = pw;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getVclass() {
		return vclass;
	}
	public void setVclass(String vclass) {
		this.vclass = vclass;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	
}

QueryDAO.java

package send;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class QueryDAO {

	private static QueryDAO instance = new QueryDAO();
	
	public static QueryDAO getInstance(){
		return instance;
	}
	
	public void insert(QueryDTO dto){
		Connection conn = null;
		PreparedStatement pstmt = null;
		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String sql="";
		
		try{
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection(url,"totoro","totoro123");
			
			sql="insert into query values(?,?,?,?,?)";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, dto.getId());
			pstmt.setString(2, dto.getPw());
			pstmt.setString(3, dto.getName());
			pstmt.setString(4, dto.getVclass());
			pstmt.setString(5, dto.getPhone());
			pstmt.executeUpdate();		
			
		}catch(Exception e){
			
		}finally{
			if(pstmt != null){
				try{
					pstmt.close();
				}catch(Exception e){					
				}
			}
			if(conn != null){
				try{
					conn.close();
				}catch(Exception e){					
				}
			}			
		}
		
	}
	
}

Now, we will create a table on Oracle to connect the database and save the data. 

create table query(
		id varchar2(20),
		pw varchar2(20),
		name varchar2(20),
		vclass varchar2(20),
		phone varchar2(30));

 

Checkboxes

Here is an example of dealing with the checkboxes in the servlet.

multiPara.html

<html lang="en">
 <head>
  <meta charset="UTF-8">
</head>
<body>
<form method="post" action="/jsppro/multiPara">
<h2>Programming Languages</h2><br>
Which languages can you use for programming?<br>
<hr>
 <input type="checkbox" name="plang" value="C"> c
 <input type="checkbox" name="plang" value="Java"> Java
 <input type="checkbox" name="plang" value="JavaScript"> JavaScript<br>
 <input type="checkbox" name="plang" value="C++"> C++
 <input type="checkbox" name="plang" value="Python"> Python
 <input type="checkbox" name="plang" value="Assembly"> Assembly<br>  
 <input type="submit" value="Submit"> 
</form>
</body>
</html>

multiPara.java

Since the "post" method is requested, it will be processed in the doPost method.

package send;

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 multiPara
 */
@WebServlet(description = "Exercise", urlPatterns = { "/multiPara" })
public class multiPara extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		String[] item;

		item = request.getParameterValues("plang");
		out.println("Selected languages are");
		
		try {
			for (int i = 0; i < item.length; i++)
				out.println(" : " + item[i]);
//				out.println(" : " + HanConv.toKor(item[i]));
		} catch (Exception e) {
			out.println(" nothing.");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8");
		
		request.setCharacterEncoding("UTF-8");
		
		PrintWriter out = response.getWriter();
		String[] item;

		item = request.getParameterValues("plang");
		out.println("Selected languages are");
		
		try {
			for (int i = 0; i < item.length; i++)
				out.println(" : " + item[i]);
//				out.println(" : " + HanConv.toKor(item[i]));

		} catch (Exception e) {
			out.println(" nothing.");
		}
	}

}

 

 

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

JSP) JSTL (JSP Standard Tag Library) - Basic / Core tags  (0) 2022.09.17
JSP) EL(Expression Language)  (0) 2022.09.16
JSP) Model1 vs Model2  (0) 2022.09.15
JSP) JSP and Oracle  (0) 2022.08.31
JSP) JavaBean  (0) 2022.08.31

+ Recent posts