I have a page that takes student attendance. It prints out a student list with a checkbox next to each student. Then the person clicks submit and send the selected student's ids and the lab ids to the database.
The problem I'm having is its sending the last ticked box to the database and none of the rest. I'm assuming its overwriting the ones previous to it but I am unsure how I can fix this problem.
Here is my doPost method:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int user_id = Integer.parseInt((String)request.getParameter("user_id"));
int lab_id = Integer.parseInt((String)request.getParameter("lab_id"));
System.out.println("I got a blow job");
String message = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
System.out.println("got connection");
Statement s = con.createStatement();
String sql = "INSERT INTO user_lab" +
" (user_id, lab_id)" +
" VALUES" +
" ('" + user_id + "'," +
" '" + lab_id + "')";
System.out.println(sql);
int i = s.executeUpdate(sql);
if (i==1) {
message = "Successful attendance.";
response.sendRedirect("Tutor_labs");
}
s.close();
con.close();
}
catch (SQLException e) {
message = "Error." + e.toString();
boolean error = true;
}
catch (Exception e) {
message = "Error." + e.toString();
boolean error = true;
}
if (message!=null) {
PrintWriter out = response.getWriter();
out.println("<B>" + message + "</B><BR>");
out.println("<HR><BR>");
}
}
}
and here is my JSP page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Mars University Lab System</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen">
</head>
<body>
<jsp:include page="headerTutor.jsp"/>
<div id = "centrecontent">
<h3>Students In Tutorial</h3>
<h2>Attendance List</h2>
<%
String[] list1 = (String[])request.getAttribute("res1");
String[] list2 = (String[])request.getAttribute("res2");
String[] list3 = (String[])request.getAttribute("res3");
String[] list4 = (String[])request.getAttribute("res4");
if(null == list1){%>
<th>Uni Id</th><th>Name</th><th>Email</th>
<%
}else{ %>
<form name="ViewStudentsTutor" ACTION="http://www.crackman.net.au/ICE/test.php\" method="post">
<% for(int i=0; i<list1.length; i++)
{
%> <input type="hidden" name="lab_id" value=<%=request.getParameter("labid")%>>
<%out.println(list2[i]);%>
<%out.println(list3[i]);%>
<%out.println(list4[i]); %>
<input type="checkbox" name="user_id" value=<%out.println(list1[i]);%>><br>
<% }}
%>
<input type="submit" value="Submit" name="Submit"/>
</form>
</div>
<jsp:include page="footer.jsp"/>
</body>
</html>
You are taking only one user_id using request.getParameter("user_id")
Instead you should use request.getParameterValues("user_id") that will return an array of String of all user_ids which you want and not a single user_id which currenlty you are getting
Similar is for lab_id
Related
Here is the Servlet
public class displayServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
Connection con = dbConnection.getConnection();
String query = "SELECT theaterNames, FROM thtrname where id in(11,12)";
try{
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
String str = null;
while(rs.next()){
str = rs.getString(1);
}
out.print(str);
HttpSession session = request.getSession();
session.setAttribute("thtr", str);
RequestDispatcher rd = request.getRequestDispatcher("success.jsp");
rd.forward(request, response);
rs.close();
ps.close();
con.close();
}catch(Exception ex){
}
}
}
Here is the success.jsp
<%#page contentType="text/html" pageEncoding="UTF-8" session="true"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<font color="green">
<%= request.getAttribute("thtr") %>
<h1><c:out value="${sessionScope.thtr}" /></h1>
</font>
</body>
</html>
I just don't get it where I am going wrong. I am using both JSTL and Scriptlet but all I am getting on the success.jsp page is null.
You need to set the value to request instead of session
from
session.setAttribute("thtr", str);
to
request.setAttribute("thtr", str);
a then to show just use ${thtr} in jsp
I am unable to get a piece of code in the following JSP code ( commented as d1, d2, d3, d4):
<%#page import="java.sql.*" errorPage="/MyError.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LoginProcess</title>
</head>
<body>
<%
Connection conn = null;
String uname = request.getParameter("uname");
String pass = request.getParameter("pass");
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e)
{
out.println("Error(class):"+e);
}
try
{
conn = DriverManager.getConnection("jdbc:mysql://localhost/studentdb","root","mysql");
PreparedStatement stmt = conn.prepareStatement("select * from studentdb.userdetails where uname=? and pass=?");
stmt.setString(1, uname);
stmt.setString(2, pass);
ResultSet rs = stmt.executeQuery();
if(!rs.next())
{
out.println("username or password is incorrect");
%> <%--d1--%>
Try Again:<%#include file="Login.html" %> <%--d2--%>
</body> <%--d3--%>
</html> <%--d4--%>
<%
return;
} //if
} //try-sql
catch(SQLException e)
{
out.println("Error(SQL):" + e);
}
finally
{
conn.close();
}
%>
This is Home Page<br>
Welcome,<b> <%= uname%></b>
</body>
the following are appearing in an if block which I am not getting why and how do they work , I know the meaning of <%#include file="Login.jsp"> and selective tags but not I am getting how are they workign here.
%> <%--d1--%>
Try Again:<%#include file="Login.html" %> <%--d2--%>
</body> <%--d3--%>
</html> <%--d4--%>
<%
(the body and html tags are not appearing in the above piece of code).
Instead of if(!rs.next()), try using if(rs.isBeforeFirst()). If rs.isBeforeFirst() is false, then you have no records.
i've to build a dynamic web project in Eclipse(Moon) with Tomcat 7.0 and mysql database (5.1). I've created a java class for users, a connector java class between jsp and mysql and the jsp pages with a login/registration forms.
This is the user.java class:
package cop;
public class Company {
public String name = "";
public String username = "";
public String password = "";
public String email = "";
public String country = "";
public String address = "";
public Company(String username, String password){
this.username = username;
this.password= password;
}
}
This is the connector .java class:
public static Company DB_login1(String user, String pass){
Company co = null;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/Mysql?user=root&password=root");
PreparedStatement pst = con.prepareStatement("SELECT username "
+ "FROM Companies "
+ "WHERE username = '"+user+"' AND password = '"+pass+"'");
pst.setString(1, user);
pst.setString(2, pass);
ResultSet rs = pst.executeQuery();
while (rs.next()){
String username = rs.getString("username");
String password = rs.getString("password");
co = new Company(username, password);
}
con.close();
}
catch (Exception e) {
System.out.println("Unable to connect to DB");
e.printStackTrace();
}
return co;
}
And at last this is the login.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="cop.*" import="java.util.*"%>
<!DOCTYPE html>
<html lang="en-US">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<div id="head">
<title>The Music Shop</title>
</div>
<div id="titles">
<text id="t1"> The Music Shop </text> <br>
<text id="t2"> The new way of buying is here </text>
</div>
<div id="login">
<form id="login_form" action="company-login.jsp" method="POST" accept-charset="utf-8">
<ul>
<li> <label for="user"> Username </label>
<input type="text" name="user" required></input></li>
<li> <label for="pass"> Password </label>
<input type="text" name="pass" required></input></li>
<li>
<input type="submit" value="Submit"> </li>
</ul>
</form>
</div>
<% String user = request.getParameter("user");
String pass = request.getParameter("pass");
Company co = Dbcon.DB_login1(user , pass);
if (co == null){
response.sendRedirect("home.jsp?err=1");
}
else{
response.sendRedirect("home.jsp");
}
%>
When i run the jsp page on Tomcat, immediately it redirects me to the "home.jsp?err=1" page, and it doesn't display the html page. Has anyone any suggestions to fix it?
Thanks in regard.
String user = request.getParameter("user");
String pass = request.getParameter("pass");
Company co = Dbcon.DB_login1(user , pass);
if (co == null){
response.sendRedirect("home.jsp?err=1");
}
else{
response.sendRedirect("home.jsp");
}
if you run your jsp page without passing any parameters(user,pass) , Dbcon.DB_login1(user , pass); will get null as both arguments . Your query will not return any results and co will remain assigned to null and so Dbcon.DB_login1(user , pass); returns null to your jsp. which then satisfies your if condition and the page gets redirected.
change
PreparedStatement pst = con.prepareStatement("SELECT username "
+ "FROM Companies "
+ "WHERE username = '"+user+"' AND password = '"+pass+"'");
to
PreparedStatement pst = con.prepareStatement("SELECT username "
+ "FROM Companies "
+ "WHERE username = '"+?+"' AND password = '"+?+"'");
Check your console, there must be some error trace.
Add System.out.println(e) as well so that if trace is disabled you can able to see the error in console
catch (Exception e) {
System.out.println("Unable to connect to DB");
System.out.println(e);
e.printStackTrace();
}
I know it is a simple task but don't able to find out what is the problem.
I made one login.jsp which is starting page.
LoginAction.jsp which will validate the user
I think there is some problem with ReqestDispatcher.
I am trying to find out solution from past 2 days and I am exhausted please help me.
All the table names and their field names are correct.
This is LoginAction.jsp
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="DataBase.DBCONNEction"%>
<%#page import="java.sql.PreparedStatement"%>
<%#page import="java.sql.Connection"%>
<%#page import="javax.servlet.RequestDispatcher"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String uname = request.getParameter("name");
String pass = request.getParameter("pass");
String unam, upass;
Connection con = null;
PreparedStatement prst = null;
Statement stm = null;
DBCONNEction DBC = null;
con = DBC.getConnection();
stm = con.createStatement();
RequestDispatcher rd = request.getRequestDispatcher("/welcome.jsp");
ResultSet rs = stm.executeQuery("select password from details where username = '" + uname + "'");
if (rs.next()) {
if (rs.getString("password").equals(pass)) { //If valid password
session.setAttribute("User", uname);
}else {
request.setAttribute("Error", "Invalid password.");
rd = request.getRequestDispatcher("/login.jsp");
}
}
else {
request.setAttribute("Error", "Invalid user name.");
rd = request.getRequestDispatcher("/login.jsp");
}
rd.forward(request, response);
%>
</body>
</html>
This is login.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Knowledge Repository System</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<div class="header">
<h1>Knowledge Repository System JSP</h1>
<form id="search" action="loginAction.jsp" method="POST">
<label>Username <input type="text" name="name" id="s-user" style="width:90%;" required></label>
<label>Password<input type="password" name="pass" id="s-pass" style="width:90%;" required></label>
<input type="submit" class="submit" value="Submit">
</form>
</div>
Admin Panel
<div class="nav">
<h2 style="font-size: 36px"><strong>Sign Up</strong></h2>
<form action="details" method="POST">
<signup>
<p><input type="text" name="name" required placeholder="Username"></p>
<p><input type="password" name="pass" required placeholder="password"></p>
<p><input type="text" name="email" required placeholder="xyz#abc.com"></p>
<p><input type="submit" value="Sign Up" align="center"></p>
</signup>
</form>
</div>
</body>
</html>
This is DBCONNEction.java
package DataBase;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBCONNEction {
private static String URL = "jdbc:mysql://localhost:3306/repository";
private static String DRIVER = "com.mysql.jdbc.Driver";
private static String pass = "myserver";
private static String user = "root";
static Connection con = null;
static {
try {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL, user, pass);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
return con;
}
}
I have a stateless Session Bean in which I get the values from the database and write them down in Arraylist, who returns to the servlet. In a servlet I send ArrayList on JSP page and try to show the value, but displays only the line "dataList", what is my mistake?
Here is my code:
ViewBean.java
//imports
#Stateless
#LocalBean
public class ViewBean {
public List getData() {
ResultSet rs = null;
List list = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/c_store", "root", "root");
Statement stmt = con.createStatement();
String query = "SELECT product.name_prod, product.price_prod, buy.number_buy, client.name_client, client.date_client FROM product, buy, client WHERE product.id_prod = buy.id_buy = client.id_client;";
stmt.executeQuery(query);
rs = stmt.getResultSet();
list = new ArrayList();
while(rs.next()){
list.add(rs.getString(1));
list.add(rs.getInt(2));
list.add(rs.getInt(3));
list.add(rs.getString(4));
list.add(rs.getString(5));
}
rs.close();
stmt.close();
con.close();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
}
ViewServlet.java
//imports
#WebServlet("/ViewServlet")
public class ViewServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#EJB
ViewBean viewBean;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
List data = new ArrayList();
data = viewBean.getData();
request.setAttribute("dataList", data);
for(int i = 0; i<data.size(); i++){
out.println(data.get(i));
}
}
}
view.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# page import="java.util.*" %>
<!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=ISO-8859-1">
<title>View Records</title>
</head>
<body>
<c:forEach var="item" items="dataList">
<b><c:out value="${item}" /></b>
</c:forEach>
</body>
</html>
You forgot to declare dataList as a variable, look at the items attribute in the loop:
<c:forEach var="item" items="${dataList}">
^ here is the bug, add the dollar sign and the curly braces
<b><c:out value="${item}" /></b>
</c:forEach>