2017년 10월 27일 금요일

[jQuery] How to add and remove 'disabled' attribute.


$('#btn').attr('disabled', '');
$('#btn').attr('disabled', 'true');
$('#btn').attr('disabled', 'false');
$('#btn').attr('disabled', 'disabled');

Those are the same.

$('#btn').removeAttr('disabled');

This is how you remove the attribute.

[jsp]How to include 'header.jsp' and 'footer.jsp' in all the jsp files in easy way using web.xml

It might be wrong... But It is like this way.
Go to WebContent > WEB-INF and source like this.

<?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_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>NeverIn</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>

  <jsp-config>
  <jsp-property-group>
  <url-pattern>/board/*</url-pattern>
  <include-prelude>/board/header.jsp</include-prelude>
  <include-coda></include-coda>
  </jsp-property-group>
  </jsp-config>
</web-app>

2017년 10월 19일 목요일

[Servlet] How servlet looks like, what it contains its inside.

Servlet has Context Path(ex. @WebServlet("/file.do")) above class name and it consists of two parts - doGet(), doPost()

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    if( ){
    } else if( ){
    } else if( ){
    } else ...
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    if( ){
    } else if( ){
    } else if( ){
    } else ...
}

2017년 10월 17일 화요일

Servlet - > Ajax 한글 깨짐 해결 방법

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

Ajax에
dataType: 'Text'

추가

2017년 10월 15일 일요일

[JSTL] JSTL Basic

[MySQL] How to write DB Dao

public class ADao {
private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_URL = 
"jdbc:mysql://ip:portNumber/jsp";
private static final String DB_ID = "id";
private static final String DB_PW = "password";

private Connection connection;
private PreparedStatement preparedStatement;
private ResultSet resultSet;

// singleton
private static ADao instance;
public static MemberDao getInstance() {
if(instance == null) {
instance = new ADao();
}
return instance;
}

private ADao() {
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println("ADao Create Error");
e.printStackTrace();
}
}

private void createConnection() {
try {
connection = DriverManager.getConnection
(DB_URL, DB_ID, DB_PW);
} catch (SQLException e) {
System.out.println("Connection Error);
e.printStackTrace();
}
}

private void closeConnection() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

private void closePreparedStatement() {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

private void closeResultSet() {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

public int insert(Member member) {
createConnection();
String sql = "INSERT INTO MEMBER(ID,PW,PHONE,NAME)"
+ "VALUES(?,?,?,?)";
int result = 0;

try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, member.getId());
preparedStatement.setString(2, member.getPw());
preparedStatement.setString(3, member.getPhone());
preparedStatement.setString(4, member.getName());

resultpreparedStatement.executeUpdate();
} catch (SQLException e) {
System.out.println("ADao insert error");
e.printStackTrace();
} finally {
closePreparedStatement();
closeConnection();
}
return result;

}
}


[JSTL] Duplicate Log In Check with JSTL

<c:if test = '${empty sessionScope.loginId}">
<form action = "${myContextPath}/member" method = "post">
ID:<input type="text name="id" size="20"><br>
PW:<input type="password" name="pw" size="20"><br>
<input type="submit" value="Sign up">
<input type="hidden" name="task" value="login">
</form>
</c:if>
<c:if test = '${not empty sessionScope.loginId}">
<script type = "text/javascript">
alert("This account is already logged in.");
</script>
<%
response.sendRedirect(request.getContextPath()+"/");
%>

2017년 10월 12일 목요일

[JSTL] Introduction to JSTL

  • What is JSTL?

JSTL stands for 'JSP Standard Tag Library'. It is a way to simplify JSP source code. As you may know, JSP's readibility is not good. JSTL increases its readibility and write code much simply.

  • How to download .jar file of JSTL.

Goto: http://www.mvnrepository.com
Search: jstl
Chose any jstl link and download .jar file.

  • How to apply JSTL in Eclipse

  1. Create a project: File > New > Dynamic Web Project ( keep pressing 'next' and check 'Generate web.xml deployment descripter' )
  2. Copy & Paste into lib folder: WebContent > WEB-INF > lib
  3. Now, you are ready to use JSTL

  • How to use JSTL in JSP

Add a directive: <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

MUST JSP JSTL
<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
int n1 = 100, n2=200;
%>
<c:set var="n1" value="<%=n1%>"/>
<c:set var="n2" value="<%=n2%>"/>

n1 : ${n1} <br>
n2 : ${n2} <br>
n1 + n2 : ${n1+n2}<br>
n1 > n2 : ${n1>n2}<br>
n1 == n2 : ${n1 == n2}<br>
n1>0 && n2>0 : ${n1>0 && n2>0}<br>
n1>0 and n2>0 : ${n1>0 and n2>0}<br>
------------------------------------<hr>
<%List<String> words = new ArrayList<>();%>
<c:set var="words" value="<%=words%>"/>

is word empty? >> ${empty words}<br>
<% words.add("apple"); %>
add a word into 'words' List> ${words.get(0)}<br>
</body>
</html>


[Java] When 'sc.nextLine()' doesn't work after 'sc.nextInt()'

[Solution]
int n = sc.nextInt();
sc.skip("[\\r\\n]+");
for(int i = 0 ; i < n ; i++){
   String str = sc.nextLine();
   System.out.println(str);
}

2017년 10월 11일 수요일

[Servlet] doGet and doPost Defference

Basically, doGet and doPost are used in Servlet. It communicates with jsp. Servlet receives Parameters(request.getParameter("name")), all in String type. However, JSP gets Attributes(request.getAttributes("name")), all in Object type(So, you can simply cast using barces'( )'(int num = (Integer) request.getAttribute; ).

       Servlet                                        HTML
Get  request.getParameter("name")       request.getAttribute("name)
Set  request.setAttribute("name", value) <form>, <a>, <input> (it sends in doGet or doPost)
  • doGet
1. html(or jsp) -> servlet

# Send to Servlet

- Using <a> tag
<a href="<%=request.getContextPath()%>/board?type=deleteForm&articleNum=<%=article.getAritlcleNum()%>"></a>

- Using <form> tag
<form action="<%=request.getContextPath()%>/board">
(method="get" is omitted)
# Get from HTML

- request.getParameter("name") 
(Object(VO) example: Article)

Article article = new Article();
article.setTitle(request.getParameter("title"));
article.setWriter(request.getParameter("writer"));
article.setPassword(request.getParameter("password"));
article.setContents(request.getParameter("contents"));

2. servlet -> html(or jsp)

# Send to HTML
request.setAttribute("name", value)

# Get from Servlet
- request.getAttribute("name")
<%
int articleNum = (Integer) request.getAttribute("articleNum");
%>
<form action="..." method="post">
<input type="hidden" name ="acticleNum" value="<%=articleNum%>">
</form>
(type="hidden" for "doPost" later in <form> & submit)
  • doPost
1. html(or jsp) -> servlet

- Using <a> tag
No

- Using <form> tag & <input> tag
<form action="<%=request.getContextPath()%>/board" method="post">
<input type="hidden" name ="acticleNum" value="<%=articleNum%>
</form>
2. servlet -> html(or jsp)
- The same with doGet method

How to write DB Dao ( with Simple Board Example )

package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import vo.Article;

public class BoardDao {
private static final String DB_DRIVER =
"com.mysql.jdbc.Driver";
private static final String DB_URL =
"jdbc:mysql://ip address:port number/db name";
private static final String DB_ID =
"id";
private static final String DB_PW =
"pw";
////////////////////////////////////////////////////////////
// singleton
private static BoardDao instance = new BoardDao();
public static BoardDao getInstance() {
return instance;
}
private BoardDao() {
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println("mysql connection error");
e.printStackTrace();
}
}
////////////////////////////////////////////////////////////
private Connection con;
private PreparedStatement pstmt;
private ResultSet rs;

private void makeConnection() {
try {
con = DriverManager.getConnection
(DB_URL, DB_ID, DB_PW);
} catch (SQLException e) {
System.out.println("DB connection error");
e.printStackTrace();
}
}
private void closeCon() {
if(con!=null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private void closePstmt() {
if(pstmt!=null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private void closeRs() {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
////////////////////////////////////////////////////////////
public int selectArticleCount() {
makeConnection();
String sql = "SELECT COUNT(*) FROM BOARD";
int result = 0;
try {
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();

rs.next();
result = rs.getInt(1);
} catch (SQLException e) {
System.out.println("dao count error");
e.printStackTrace();
} finally {
closeRs();
closePstmt();
closeCon();
}
return result;
}

public List<Article> selectArticleList
(int startRow, int count){
makeConnection();
String sql = "SELECT ARTICLE_NUM, TITLE,"
+ "WRITER, CONTENTS, READ_COUNT,"
+ "WRITE_DATE, PASSWORD FROM BOARD "
+ "ORDER BY ARTICLE_NUM DESC LIMIT ?,?";
List<Article> articleList = new ArrayList<>();

try {
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, startRow);
pstmt.setInt(2, count);
rs = pstmt.executeQuery();

while(rs.next()) {
Article article = new Article();
article.setAritlcleNum(rs.getInt(1));
article.setTitle(rs.getString(2));
article.setWriter(rs.getString(3));
article.setContents(rs.getString(4));
article.setReadCount(rs.getInt(5));
article.setWriteDate(rs.getTimestamp(6));
article.setPassword(rs.getString(7));

articleList.add(article);
}
} catch (SQLException e) {
System.out.println("dao selectArticleList error");
e.printStackTrace();
} finally {
closeRs();
closePstmt();
closeCon();
}
return articleList;
}

//////////////////////////////////////////////////////////
public int insert(Article article) {
makeConnection();
String sql = "INSERT INTO BOARD"
+ "(TITLE,WRITER,PASSWORD,CONTENTS,READ_COUNT,"
+ "WRITE_DATE) VALUES(?,?,?,?,?,?)";
int result = 0;

try {
pstmt = con.prepareStatement(sql);
pstmt.setString(1, article.getTitle());
pstmt.setString(2, article.getWriter());
pstmt.setString(3, article.getPassword());
pstmt.setString(4, article.getContents());
pstmt.setInt(5, article.getReadCount());
pstmt.setTimestamp(6,
new Timestamp(article.getWriteDate().getTime()));

result = pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println("dao insert error");
e.printStackTrace();
} finally {
closePstmt();
closeCon();
}
return result;
}
//////////////////////////////////////////////////////////
public int updateReadCount(int articleNum) {
makeConnection();
String sql =
"UPDATE BOARD SET READ_COUNT=READ_COUNT+1 "
+ "WHERE ARTICLE_NUM=?";
int result = 0;
try {
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, articleNum);

result = pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println("dao update error");
e.printStackTrace();
} finally {
closePstmt();
closeCon();
}
return result;
}
public Article select(int articleNum) {
makeConnection();
String sql =
"SELECT ARTICLE_NUM,TITLE,WRITER,"
+ "CONTENTS,WRITE_DATE,READ_COUNT FROM BOARD "
+ "WHERE ARTICLE_NUM=?";
Article article = null;

try {
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, articleNum);
rs = pstmt.executeQuery();

if(rs.next()) {
article = new Article();
article.setAritlcleNum(rs.getInt(1));
article.setTitle(rs.getString(2));
article.setWriter(rs.getString(3));
article.setContents(rs.getString(4));
article.setWriteDate(rs.getTimestamp(5));
article.setReadCount(rs.getInt(6));
}
} catch (SQLException e) {
System.out.println("dao select error");
e.printStackTrace();
} finally {
closeRs();
closePstmt();
closeCon();
}
return article;
}
public int update(Article article) {
makeConnection();
int result = 0;
String sql = "update board set title=?, contents=?,"
+"write_date = ? where article_num=? and password=?";
try {
pstmt = con.prepareStatement(sql);

pstmt.setString(1, article.getTitle());
pstmt.setString(2, article.getContents());
pstmt.setString(2, article.getContents());
pstmt.setTimestamp(3, new Timestamp(article.getWriteDate().getTime()));
pstmt.setInt(4,  article.getAritlcleNum());
pstmt.setString(5,  article.getPassword());

result = pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println("dao update error");
e.printStackTrace();
} finally {
closePstmt();
closeCon();
}
return result;
}
}