[Project]掲示板1-4の作成

121595 ワード

動的Webプロジェクトを使用した掲示板の作成


掲示板1-3の作成では、メンバーに関連するコンテンツをメンバーサーブレットで処理し、フォーラム記事に関連するコンテンツをNoticeBoardサーブレットで処理し、論理的に2つのサーブレットのみを処理する.これは初回実施時には便利ですが、メンテナンス時には一部を修復するコストも高いです.そこで,ここでは1−3作成の掲示板をMVC Patternに変更して実現する.すべてのページの移動はコントローラを通ります.

きほんプロジェクトこうぞう


既存のサーブレットは、コントローラ、サービス、データの3つのセクションに分かれています.論理の順序は次のとおりです.
要求ページ->コントローラ->サービス->データ->サービス->コントローラ->結果ページ

プライマリコード


すべてのコードを確認

Controller


MemberController

package com.company.noticeboard.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.company.noticeboard.dto.MemberDto;
import com.company.noticeboard.model.service.MemberService;
import com.company.noticeboard.model.service.MemberServiceImpl;

@WebServlet("/member")
public class MemberController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private MemberService memberService = new MemberServiceImpl();

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		process(request, response);
	}
	
	private void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String root = request.getContextPath();
		String path = "/index.jsp";
		String act = request.getParameter("act");
		
		if ("mvjoin".equals(act)) {
			path = "/user/join.jsp";
			response.sendRedirect(root + path);
		} else if ("mvlogin".equals(act)) {
			path = "/user/login.jsp";
			response.sendRedirect(root + path);
		} else if ("regist".equals(act)) {
			path = registMember(request, response);
			response.sendRedirect(root + path);
		} else if ("login".equals(act)) {
			path = login(request, response);
			response.sendRedirect(root + path);
		} else if ("logout".equals(act)) {
			path = logout(request, response);
			response.sendRedirect(root + path);
		} else if ("idcheck".equals(act)) {
			path = idCheck(request, response);
			request.getRequestDispatcher(path).forward(request, response);
		} else {
			response.sendRedirect(root + path);
		}
	}
	
	private String idCheck(HttpServletRequest request, HttpServletResponse response) {
		int idcount = 1;
		
		try {
			idcount = memberService.idCheck(request.getParameter("userid"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		request.setAttribute("idcount", idcount);
		
		return "/user/idcheck_result.jsp";
	}

	private String registMember(HttpServletRequest request, HttpServletResponse response) {
		String emailid = request.getParameter("emailid");
		String emaildomain = request.getParameter("emaildomain");
		String email = emailid + "@" + emaildomain;
		
		MemberDto memberDto = new MemberDto();
		memberDto.setUserName(request.getParameter("username"));
		memberDto.setUserId(request.getParameter("userid"));
		memberDto.setUserPwd(request.getParameter("userpwd"));
		memberDto.setEmail(email);
		
		try {
			memberService.registMember(memberDto);
		} catch (Exception e) {
			e.printStackTrace();
			return "/error/error.jsp";
		}
		
		return "/user/login.jsp";
	}
	
	private String login(HttpServletRequest request, HttpServletResponse response) {
		String root = request.getContextPath();
		String idsave = request.getParameter("idsave");
		String userid = request.getParameter("userid");
		String userpwd = request.getParameter("userpwd");
		
		MemberDto memberDto = null;
		try {
			memberDto = memberService.login(userid, userpwd);
		} catch (Exception e) {
			e.printStackTrace();
			return "/error/error.jsp";
		}
		
		if (memberDto != null) {
			HttpSession session = request.getSession();
			session.setAttribute("user", memberDto);
			
			if ("saveok".equals(idsave)) {
				Cookie cookie = new Cookie("savedId", userid);
				cookie.setPath(root);
				cookie.setMaxAge(60 * 60 * 24 * 365 * 40);
				response.addCookie(cookie);
			} else {
				Cookie[] cookies = request.getCookies();
				
				if (cookies != null) {
					for (Cookie cookie : cookies) {
						if ("savedId".equals(cookie.getName())) {
							cookie.setMaxAge(0);
							cookie.setPath(request.getContextPath());
							response.addCookie(cookie);
							break;
						}
					}
				}
			}
		}
		
		return "/index.jsp";
	}
	
	private String logout(HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession();
		session.invalidate();
		
		return "/index.jsp";
	}

}

NoticeBoardController

package com.company.noticeboard.controller;

import java.io.IOException;
import java.util.List;

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 com.company.noticeboard.dto.MemberDto;
import com.company.noticeboard.dto.NoticeBoardDto;
import com.company.noticeboard.model.service.NoticeBoardService;
import com.company.noticeboard.model.service.NoticeBoardServiceImpl;

@WebServlet("/article")
public class NoticeBoardController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private NoticeBoardService noticeBoardService = new NoticeBoardServiceImpl();

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		process(request, response);
	}

	private void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String root = request.getContextPath();
		String path = "/index.jsp";
		String act = request.getParameter("act");

		if ("mvwrite".equals(act)) {
			path = "/noticeboard/write.jsp";
			response.sendRedirect(root + path);
		} else if ("mvmodify".equals(act)) {
			path = getArticle(request, response);
			request.getRequestDispatcher(path).forward(request, response);
		} else if ("modify".equals(act)) {
			path = modifyArticle(request, response);
			response.sendRedirect(root + path);
		} else if ("regist".equals(act)) {
			path = registArticle(request, response);
			response.sendRedirect(root + path);
		} else if ("delete".equals(act)) {
			path = deleteArticle(request, response);
			response.sendRedirect(root + path);
		} else if ("list".equals(act)) {
			path = listArticle(request, response);
			request.getRequestDispatcher(path).forward(request, response);
		}
	}

	private String getArticle(HttpServletRequest request, HttpServletResponse response) {
		int articleno = Integer.parseInt(request.getParameter("articleno"));
		NoticeBoardDto article = null;
		
		try {
			article = noticeBoardService.getArticle(articleno);
			request.setAttribute("article", article);
		} catch (Exception e) {
			e.printStackTrace();
			return "/error/error.jsp";
		}
		
		return "/noticeboard/modify.jsp";
	}
	
	private String modifyArticle(HttpServletRequest request, HttpServletResponse response) {
		NoticeBoardDto noticeBoardDto = new NoticeBoardDto();
		
		noticeBoardDto.setArticleNo(Integer.parseInt(request.getParameter("articleno")));
		noticeBoardDto.setSubject(request.getParameter("subject"));
		noticeBoardDto.setContent(request.getParameter("content"));
		
		try {
			noticeBoardService.updateArticle(noticeBoardDto);
		} catch (Exception e) {
			e.printStackTrace();
			return "/error/error.jsp";
		}
		
		return "/article?act=list";
	}

	private String registArticle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		MemberDto user = (MemberDto) request.getSession().getAttribute("user");

		NoticeBoardDto noticeBoardDto = new NoticeBoardDto();
		noticeBoardDto.setSubject(request.getParameter("subject"));
		noticeBoardDto.setContent(request.getParameter("content"));
		noticeBoardDto.setUserId(user.getUserId());
		
		try {
			noticeBoardService.registArticle(noticeBoardDto);
		} catch (Exception e) {
			e.printStackTrace();
			return "/noticeboard/writefail.jsp";
		}

		return "/noticeboard/writesuccess.jsp";
	}
	
	private String deleteArticle(HttpServletRequest request, HttpServletResponse response) {
		int articleno = Integer.parseInt(request.getParameter("articleno"));
		
		try {
			noticeBoardService.deleteArticle(articleno);
		} catch (Exception e) {
			e.printStackTrace();
			return "/error/error.jsp";
		}
		
		return "/article?act=list";
	}

	private String listArticle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String key = request.getParameter("key");
		String word = request.getParameter("word");

		List<NoticeBoardDto> articles = null;

		try {
			articles = noticeBoardService.listArticle(key, word);
		} catch (Exception e) {
			e.printStackTrace();
			return "/error/error.jsp";
		}

		request.setAttribute("articles", articles);

		return "/noticeboard/list.jsp";
	}

}

Service


MemberServiceImpl

package com.company.noticeboard.model.service;

import com.company.noticeboard.dto.MemberDto;
import com.company.noticeboard.model.dao.MemberDao;
import com.company.noticeboard.model.dao.MemberDaoImpl;

public class MemberServiceImpl implements MemberService {
	
	private MemberDao memberDao = new MemberDaoImpl();

	@Override
	public int idCheck(String id) throws Exception {
		return memberDao.idCheck(id);
	}

	@Override
	public void registMember(MemberDto memberDto) throws Exception {
		memberDao.registMember(memberDto);
	}

	@Override
	public MemberDto login(String id, String pwd) throws Exception {
		return memberDao.login(id, pwd);
	}

}

NoticeBoardServiceImpl

package com.company.noticeboard.model.service;

import java.util.List;

import com.company.noticeboard.dto.NoticeBoardDto;
import com.company.noticeboard.model.dao.NoticeBoardDao;
import com.company.noticeboard.model.dao.NoticeBoardDaoImpl;

public class NoticeBoardServiceImpl implements NoticeBoardService {
	
	private NoticeBoardDao noticeBoardDao = new NoticeBoardDaoImpl();

	@Override
	public void registArticle(NoticeBoardDto noticeBoardDto) throws Exception {
		noticeBoardDao.registArticle(noticeBoardDto);
	}

	@Override
	public List<NoticeBoardDto> listArticle(String key, String word) throws Exception {
		return noticeBoardDao.listArticle(key, word);
	}

	@Override
	public NoticeBoardDto getArticle(int articleNo) throws Exception {
		return noticeBoardDao.getArticle(articleNo);
	}

	@Override
	public void updateArticle(NoticeBoardDto noticeBoardDto) throws Exception {
		noticeBoardDao.updateArticle(noticeBoardDto);
	}

	@Override
	public void deleteArticle(int articleNo) throws Exception {
		noticeBoardDao.deleteArticle(articleNo);
	}

}

DAO


MemberDaoImpl

package com.company.noticeboard.model.dao;

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

import com.company.noticeboard.dto.MemberDto;
import com.company.util.DBUtil;

public class MemberDaoImpl implements MemberDao {
	
	private DBUtil dbUtil = DBUtil.getInstance();

	@Override
	public int idCheck(String id) throws Exception {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		int idcount = 1;
		
		try {
			conn = dbUtil.getConnection();
			
			String sql = "";
			sql += "select count(userid) ";
			sql += "from member ";
			sql += "where userid = ? ";
			
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, id);
			
			rs = pstmt.executeQuery();
			if (rs.next()) {
				idcount = rs.getInt(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbUtil.close(rs, pstmt, conn);
		}
		
		return idcount;
	}

	@Override
	public void registMember(MemberDto memberDto) throws Exception {
		Connection conn = null;
		PreparedStatement pstmt = null;
		
		try {
			conn = dbUtil.getConnection();
			
			String sql = "";
			sql += "insert into member (userid, username, userpwd, email) ";
			sql += "values (?, ?, ?, ?) ";
			
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, memberDto.getUserId());
			pstmt.setString(2, memberDto.getUserName());
			pstmt.setString(3, memberDto.getUserPwd());
			pstmt.setString(4, memberDto.getEmail());
			pstmt.executeUpdate();
		} finally {
			dbUtil.close(pstmt, conn);
		}
	}

	@Override
	public MemberDto login(String id, String pwd) throws Exception {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		MemberDto memberDto = null;
		
		try {
			conn = dbUtil.getConnection();
			
			String sql = "";
			sql += "select userid, username, email ";
			sql += "from member ";
			sql += "where userid = ? and userpwd = ? ";
			
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, id);
			pstmt.setString(2, pwd);
			
			rs = pstmt.executeQuery();
			if (rs.next()) {
				memberDto = new MemberDto();
				memberDto.setUserId(id);
				memberDto.setUserName(rs.getString("username"));
				memberDto.setEmail(rs.getString("email"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbUtil.close(rs, pstmt, conn);
		}
		
		return memberDto;
	}

}

NoticeBoardDaoImpl

package com.company.noticeboard.model.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import com.company.noticeboard.dto.NoticeBoardDto;
import com.company.util.DBUtil;

public class NoticeBoardDaoImpl implements NoticeBoardDao {
	
	private DBUtil dbUtil = DBUtil.getInstance();

	@Override
	public void registArticle(NoticeBoardDto noticeBoardDto) throws Exception {
		Connection conn = null;
		PreparedStatement pstmt = null;

		try {
			conn = dbUtil.getConnection();

			String sql = "";
			sql += "insert into noticeboard (userid, subject, content) ";
			sql += "values (?, ?, ?) ";

			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, noticeBoardDto.getUserId());
			pstmt.setString(2, noticeBoardDto.getSubject());
			pstmt.setString(3, noticeBoardDto.getContent());

			pstmt.executeUpdate();
		} finally {
			dbUtil.close(pstmt, conn);
		}
	}

	@Override
	public List<NoticeBoardDto> listArticle(String key, String word) throws Exception {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		List<NoticeBoardDto> articles = new LinkedList<NoticeBoardDto>();
		
		try {
			conn = dbUtil.getConnection();
			
			String sql = "";
			sql += "select userid, articleno, subject, content, regtime ";
			sql += "from noticeboard ";
			sql += "order by articleno desc ";
			
			pstmt = conn.prepareStatement(sql);
			
			rs = pstmt.executeQuery();
			
			while (rs.next()) {
				NoticeBoardDto article = new NoticeBoardDto();
				
				article.setUserId(rs.getString("userid"));
				article.setArticleNo(rs.getInt("articleno"));
				article.setSubject(rs.getString("subject"));
				article.setContent(rs.getString("content"));
				article.setRegTime(rs.getString("regtime"));
				
				articles.add(article);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbUtil.close(rs, pstmt, conn);
		}
		
		return articles;
	}

	@Override
	public NoticeBoardDto getArticle(int articleNo) throws Exception {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		NoticeBoardDto article = null;
		
		try {
			conn = dbUtil.getConnection();
			
			String sql = "";
			sql += "select userid, articleno, subject, content ";
			sql += "from noticeboard ";
			sql += "where articleno = ? ";
			
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, articleNo);
			
			rs = pstmt.executeQuery();
			
			if (rs.next()) {
				article = new NoticeBoardDto();
				
				article.setUserId(rs.getString("userid"));
				article.setArticleNo(rs.getInt("articleno"));
				article.setSubject(rs.getString("subject"));
				article.setContent(rs.getString("content"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbUtil.close(rs, pstmt, conn);
		}
		
		return article;
	}

	@Override
	public void updateArticle(NoticeBoardDto noticeBoardDto) throws Exception {
		Connection conn = null;
		PreparedStatement pstmt = null;

		try {
			conn = dbUtil.getConnection();

			String sql = "";
			sql += "update noticeboard ";
			sql += "set subject = ?, content = ?";
			sql += "where articleno = ? ";

			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, noticeBoardDto.getSubject());
			pstmt.setString(2, noticeBoardDto.getContent());
			pstmt.setInt(3, noticeBoardDto.getArticleNo());

			pstmt.executeUpdate();
		} finally {
			dbUtil.close(pstmt, conn);
		}
	}

	@Override
	public void deleteArticle(int articleNo) throws Exception {
		Connection conn = null;
		PreparedStatement pstmt = null;

		try {
			conn = dbUtil.getConnection();

			String sql = "";
			sql += "delete from noticeboard ";
			sql += "where articleno = ? ";

			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, articleNo);

			pstmt.executeUpdate();
		} finally {
			dbUtil.close(pstmt, conn);
		}
	}

}

結果画面


メイン




会員収入



会員登録の確認





会員登録パスワードチェック




ログイン



文章を書く



記事リスト



文章を直す



記事の削除