67 279
Assignments Done
99,1%
Successfully Done
In November 2018

Answer to Question #5922 in Java | JSP | JSF for venki

Question #5922
Write a Servlet that lets a user vote for his favorite food from a combo box or radio buttons (the user must be able to make multiple food selections per request).
• Store the favorite foods and the number of votes for each food.
• Display all foods and their number of votes in alphabetical order back to the user.
• Use database to store the data.
Expert's answer
package com.ndrei;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
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 VoteServlet
& */
@WebServlet("/VoteServlet")
public class VoteServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
& * @see HttpServlet#HttpServlet()
& */
public VoteServlet() {
& super();
& // TODO Auto-generated constructor stub
}

protected void doPost(HttpServletRequest request,
& HttpServletResponse response) throws ServletException, IOException {

& String driver = "com.mysql.jdbc.Driver";
& String url = "jdbc:mysql://localhost/p26";
& String root = "root";
& String pass = "14011992";
& try {
& Class.forName(driver).newInstance();
& Connection c;
& String select[] = request.getParameterValues("id");

& c = DriverManager.getConnection(url, root, pass);
& Statement s = c.createStatement();

& if (select != null && select.length != 0) {
& for (int i = 0; i < select.length; i++) {
& s = c.createStatement();
& s.executeUpdate("UPDATE Foods SET NumOfVotes = NumOfVotes +1 WHERE Food = '"
& + select[i] + "';");
& }
& }
& s = c.createStatement();
& ResultSet rs = s.executeQuery("SELECT * FROM Foods");

& response.setContentType("text/html");
& PrintWriter out = response.getWriter();
& out.println("<html>");
& out.println("<body>");
& out.println("<tabe>");
& while (rs.next()) {
& out.println("<tr>");
& out.println("<td>");
& out.println(rs.getString("Food"));
& out.println("</td>");
& out.println("<td>");
& out.println(rs.getInt("NumOfVotes"));
& out.println("
");
& out.println("</td>");
& out.println("</tr>");
& }
& out.println("</tabe>");
& out.println("</body>");
& out.println("</html>");
& out.close();

& } catch (SQLException e) {
& e.printStackTrace();
& } catch (InstantiationException | IllegalAccessException
& | ClassNotFoundException e1) {
& e1.printStackTrace();
& }

}

}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions