Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*; // needed for I/O processing
- import java.sql.*; // needed for SQL query
- import javax.servlet.*; // Generic Servlet
- import javax.servlet.http.*; // HttpServlet
- public class MainServlet extends HttpServlet {
- private Connection connection;
- // init() runs when servlet is loaded into the server
- public void init() throws ServletException {
- try {
- connection = DriverManager.getConnection(
- "jdbc:mysql://localhost:3306/estoredb", "root", "");
- } catch (SQLException exception) {
- exception.printStackTrace();
- }
- }
- // doGet() run once per HTTP GET request to the server
- public void doGet(HttpServletRequest request,
- HttpServletResponse response)
- throws ServletException, IOException {
- // Set the MIME type for the response message
- response.setContentType("text/html");
- PrintWriter out = response.getWriter();
- Statement statement = null;
- try {
- statement = connection.createStatement();
- String sqlStr = "select * from categories";
- ResultSet categorySet = statement.executeQuery(sqlStr);
- int categorySum = categorySet.getFetchSize();
- int categoryIds[] = new int[categorySum];
- String categoryNames[] = new String[categorySum];
- int i = 0;
- while (categorySet.next()) {
- categoryIds[i] = categorySet.getInt("id");
- categoryNames[i] = categorySet.getString("name");
- i++;
- }
- request.setAttribute ("categoryIds", categoryIds);
- request.setAttribute ("categoryNames", categoryNames);
- String apple="appleshop";
- request.setAttribute("fruit", apple);
- getServletConfig().getServletContext().getRequestDispatcher(
- "/jsp/main.jsp").forward(request, response);
- } catch (SQLException exception) {
- exception.printStackTrace();
- } finally {
- try {
- if (statement != null) statement.close();
- } catch (SQLException exception) {
- exception.printStackTrace();
- }
- }
- }
- // destroy() runs when the servlet is unloaded from the server
- public void destroy() {
- try {
- connection.close();
- } catch (SQLException exception) {
- exception.printStackTrace();
- }
- }
- }
Add Comment
Please, Sign In to add comment