#05:メモを表示する - Servlet
ここでは、選択したメモを個別に表示するプログラムを作成します。まずは、「/show」でアクセスした時、指定されたメモの詳細情報を呼び出すServletを作成しましょう。
(tomcat/webapps/mymemo/ShowServlet.java)import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.sql.*;
public class ShowServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int postId = Integer.parseInt(request.getParameter("id"));
if (request.getAttribute("message") == null) {
request.setAttribute("message", "This is your post " + postId);
}
String url = "jdbc:mysql://localhost/memo";
String user = "root";
String password = "";
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
}
String sql = "SELECT * FROM posts WHERE id = ?";
try (Connection connection = DriverManager.getConnection(url, user, password);
PreparedStatement statment = connection.prepareStatement(sql)) {
statment.setInt(1, postId);
ResultSet results = statment.executeQuery();
while (results.next()) {
String id = results.getString("id");
request.setAttribute("id", id);
String title = results.getString("title");
request.setAttribute("title", title);
String content = results.getString("content").replaceAll("\n", "<br>");
request.setAttribute("content", content);
}
} catch (Exception e) {
request.setAttribute("message", "Exception:" + e.getMessage());
}
String view = "/WEB-INF/views/post.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(view);
dispatcher.forward(request, response);
}
}
- Javaの道>Servlet・JSP
https://www.javaroad.jp/servletjsp/index.html
- Servletアプリ開発:目次 - Web系開発メモ
http://web-dev.hatenablog.com/entry/java/servlet/dev-restful-app/table-of-contents