How can i get my table values from html to servlet? - java

I need to get my html table values in my servlet
Hi,
Im doing a project during my acadamic courses about sudoku website.
During my project I have encounterd a problem that I can't slove - get my table html values into my servlet.
I have tried doing things like set hidden names and getParameterValues but none of them worked.
this is my html table
<table class="center">
<% int n =9;
for(int s = 0; s<n; s++){
%>
<tr>
<% for(int f=0; f<n; f++)
{
%>
<td><% int z = SF[s][f];
if(z==0) {%>
<input type="text">
<% } else { %>
<%=SF[s][f]%>
<%}%>
</td hidden name="z">
<% } %>
</tr hidden name="z">
<% } %>
</table>
and this is my empty servlet
package View;
import org.omg.CORBA.SystemException;
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 java.io.IOException;
import java.io.PrintWriter;
#WebServlet(name = "CheckSudokuServlet",urlPatterns = "/CheckSudokuServlet")
public class CheckSudokuServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
//tried - String td[]=request.getParameterValues("z");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}

How about using javascript to encode the values into a url
var z=3;
window.location.href = "/CheckSudokuServlet?z="+z;
Then in your servlet you can access as so:
String refBgcId= request.getParameter("refBgcId").toString();

Related

<c:out> tag is not showing up in JSP nor does it work

Somehow, the <c:out> tag is not working at all. It doesn't show any alerts and it's just blank. It's like I never added the tag into the file. Here's my code:
Connector.java:
package connect;
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 java.util.ArrayList;
import javax.servlet.ServletContext;
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 javax.servlet.http.HttpSession;
import products.Product;
/**
* Servlet implementation class Connector
*/
#WebServlet("/Connector")
public class Connector extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Connector() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
#SuppressWarnings({ "unchecked", "null", "unused" })
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://\\\\.\\pipe\\MSSQL$SQLEXPRESS\\sql\\query:8888;databaseName=ShoppingDB";
Connection con = DriverManager.getConnection(url,"sa","33887899");
Statement stmt = con.createStatement();
ArrayList<Product> pro=new ArrayList<Product>();
ResultSet rs=stmt.executeQuery("select * from Products");
Product p = new Product();
while(rs.next()) {
p.setId(rs.getInt("product_id"));
p.setName(rs.getString("product_name"));
p.setDes(rs.getString("product_des"));
p.setPrice(rs.getInt("product_price"));
p.setSrc(rs.getString("product_img_source"));
p.setType(rs.getString("product_type"));
p.setBrand(rs.getString("product_brand"));
p.setAmount(1000);
pro.add(p);
}
Product re;
String name=request.getParameter("search");
for(int i =0;i<pro.size();i++) {
if(pro.get(i).getName()==name) {
re=pro.get(i);
break;
}
}
p=pro.get(0);
ServletContext context=getServletContext();
context.setAttribute("p", p);
}catch(Exception e) {
out.println(e);
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
Home.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" href="Style.css">
</head>
<body style="background-color:#f5f5f5;">
<h1 style="text-align:center">PRJ321X_202x</h1>
<div id="nav">
<button class="navbtn">Home</button>
<button class="navbtn">Products</button>
<button class="navbtn">About Us</button>
<button class="navbtn" style="float:right;" onclick="location.href='Login.jsp'">Log in</button>
<form style="float:right;" method="Post" action="Connector">
<input name="search" id="search" type="text" placeholder="Search..">
<input type="submit" style="display:none">
</form>
</div>
<script src="Script.js"></script>
<div style="float:left;width:75%;margin-right:5px;" id="products">
<div>
<c:out value="${p.id}"/>
</div>
</div>
<div style="float:left;width:24%">
<div style="background-color:white;width:100%">
<h3>Shopping cart</h3>
<div style="height:2.5cm;background-color:#8f8d8d;width:100%">Your cart is currently empty</div>
</div>
<div style="background-color:white;width:100%">
<h4>Popular products or banner</h4>
<p>Iphone 11 Pro Max</p>
<img src="11PM.jpg" style="width:50%">
<p>Iphone 12 Pro Max</p>
<img src="12PM.jpg" style="width:50%">
<p>Samsung Galaxy S20</p>
<img src="S20.jpg" style="width:50%">
</div>
</div>
</body>
</html>
In your servlet you are doing
context.setAttribute("p", p);
But in your JSP you are doing:
<c:out value="${s.id}"/>
Obviously, your names must match and the tag should be:
<c:out value="${p.id}"/>
One other thing I notice is that you are not dispatching to the JSP. You need to do a requestDispatcher.forward() to your JSP
Here is the minimum example to make everything work:
Servlet:
package connect;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
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 products.Product;
#WebServlet("/Connector")
public class Connector extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Product p = new Product();
p.setId(1234);
ServletContext context = getServletContext();
context.setAttribute("p", p);
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/Home.jsp"); // <--- your path here
requestDispatcher.forward(request, response);
}
}
If your Home.jsp file is on some other path, change above accordingly.
Home.jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:out value="${p.id}" />
With that being said, a few comments on your controller code.
First of all, don't use #SuppressWarnings unless you know what you are doing. Based on your code, you are at a beginner level, so this annotation can hide a lot of issues that you should pay attention to.
You use an output stream PrintWriter out = response.getWriter(); in your code, but only to write a exception message into it when your code fails. If your code works, not only that you don't use your JSP, but you also don't use this out object to write a response to send to the client. So in regards with generating a response, your servlet did nothing, that's why nothing was displayed.
If you are doing a search for a product, you can write a WHERE clause and retrieve only what you are searching for instead of getting all the products in the database and then looping through them. Make sure you use prepared statement parameters when building your query. DO NOT CONCATENATE STRING TO BUILD YOUR SQL QUERY. That can cause SQL injection vulnerabilities.
You are looping through a list of product results but you are declaring your product object outside of the while loop. The result of this is that your array will only be filled with this reference object, that will point to objects that have the last retrieved value from the database. You need to move the product creation inside the while loop, like this:
while (rs.next()) {
Product p = new Product();
p.setId(rs.getInt("product_id"));
// all the other props
pro.add(p);
}
You are using the Product re; reference to search for your product, but then you never use it because you do a p=pro.get(0); to get the first product from your list and you use p to place in context for the JSP. I'me assuming you mean to use re instead.
Don't compare strings with ==. This code:
if (pro.get(i).getName() == name) {
should probably be something like:
if (pro.get(i).getName().equalsIgnoreCase(name)) {
Even more, you need to make sure you protect yourself from NullPointerExceptions in case getName() can also return null. If you used a WHERE SQL clause, you wouldn't need to loop again and search for products.
Finally, you should read some books or documentation on the concepts and code you are using. You might be able to put something together eventually, without fully understanding what's going on, but it might not necessarily be what you expect.

Receive checkbox values in Java EE

I have this simple html form code:
<html>
<form method="post" action="http://localhost:7001/checkuser">
<input type="checkbox" name="name" value="1">John</input>
<input type="checkbox" name="name" value="2">Matt</input>
<input type="checkbox" name="name" value="3">Chris</input>
<input type="submit" name="sprawdz" value="Submit" />
</form>
</html>
And when i receive this post request in a node.js app with express I see that the posted object has a "name" array with the checked values in it.
When I try this in a Java EE servlet:
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
import java.sql.*;
public class NewServlet extends HttpServlet {
private static final long serialVersionUID =1L;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
}
The name variable only contains the first element checked, and I know how to get the whole array. I tried
String[] name = request.getParameter("name");
but this tells me that the left and right side are incompatible.
You can use getParameterValues() method..
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
import java.sql.*;
public class NewServlet extends HttpServlet {
private static final long serialVersionUID =1L;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String[] myarr = request.getParameterValues("name");
for(String s:myarr) {
out.println("Name : " + s);
}
}

passing parameters between jsp pages and servlets

I am new to web services jsps and servlets and i have this very simple example just to understand how things work.
At first, i have this simple web service :
package com.sav.calculator;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
#WebService(serviceName = "CalculatorWS")
public class CalculatorWS {
#WebMethod(operationName = "add")
public int add(#WebParam(name = "i") int i, #WebParam(name = "j") int j) {
int k = i + j;
return k;
}
}
Then i use this web service in my client application. Im trying to work the right way so i send data from a jsp to servlet, do the calculations in the servlet and send the data in another jsp for the presentation.. but the question is why im not getting it right?
here is the first jsp(just an html form):
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form method="POST" action="ClientServlet">
<input type="text" name="j"/>
<input type="text" name="i"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
here is the servlet where i use my add webmethod:
package com.sav.calculator.client;
import com.sav.calculator.CalculatorWS_Service;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
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 javax.xml.ws.WebServiceRef;
#WebServlet(name = "ClientServlet", urlPatterns = {"/ClientServlet"})
public class ClientServlet extends HttpServlet {
#WebServiceRef(wsdlLocation = "WEB-INF/wsdl/localhost_8080/CalculatorWSApplication/CalculatorWS.wsdl")
private CalculatorWS_Service service;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
doPost(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
int i = (int) request.getAttribute("i");
int j = (int) request.getAttribute("j");
int k = add(i, j);
request.setAttribute("k",k);
RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("newjsp2.jsp");
dispatcher.forward(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}
private int add(int i, int j) {
com.sav.calculator.CalculatorWS port = service.getCalculatorWSPort();
return port.add(i, j);
}
}
And the newjsp2 is just a hello world page, im just trying to get there first but what i get is :
that.
After starting web-service server, in web browser type address:
http://localhost:8080/CalculatorWSApplication/CalculatorWS.wsdl
if this address contains an wsdl (xml format) then use it as your wsdlLocation.
Try also some tool, like SoapUI, or some other.
From Servlet to JSP
You could set values into the response object before forwarding request to jsp. Or you can put your values into a session bean and access it in the jsp.
From JSP to Servlet
You need to submit a form and pass parameter as an input. An example ...
<form method="Post" action="path/to/servlet">
<input type="text" name="x" />
<input type="password" name="xx" />
<input type="hidden" name="xxx" value="zzz" />
<input type='submit' />
</form>

unknown Servlet exception throw error of HTTP Status 500

I have tried adding all libraries that are needed for Servlet to run but still I am getting an exception that threw HTTP Status 500 error.
I also have tried all previously asked questions in stack overflow.
LoginServlet.java
package com.testlogin;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String username = request.getParameter("username");
String password = request.getParameter("password");
PrintWriter pw = response.getWriter();
pw.print("Hello");
if (username.equals(password)) {
pw.println("<h1>Hello </h1>" + username);
}
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
login.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="LoginServlet" method="post">
<div style="color: red">
User Name
<input type="text" name="username">
<br /> Password
<input type="password" name="password">
<br>
<input type="submit" value="Sign In">
</div>
</form>
</body>
</html>
well, don't complicate your code. I think your code will work fine too and problem should be on your server.
please make sure if you are using servlet version >3.0 and tomcat 7 as it will not run in the previous versions of tomcat
try this..
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String username = request.getParameter("username");
String password = request.getParameter("password");
PrintWriter pw = response.getWriter();
pw.print("Hello");
if (username.equals(password)) {
pw.println("<h1>Hello </h1>" + username);
}
}
}

Out.Print method not working?

Here is my code
LoginController.java
package mvc.demo.control;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mvc.demo.model.Authenticate;
public class LoginController extends HttpServlet {
private static final long SerialVersionUID=1L;
public LoginController()
{
super();
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String s1=req.getParameter("username");
String s2=req.getParameter("password");
RequestDispatcher rd=null;
Authenticate au=new Authenticate();
String result=au.authorise(s1, s2);
if(result.equals("success"))
{
rd=req.getRequestDispatcher("/success.jsp");
}
else
{
//This is the point where i try to print error message on jsp.
PrintWriter out = resp.getWriter( );
out.print("Sorry UserName or Password Error!");
rd=req.getRequestDispatcher("/login.jsp");
rd.include(req, resp);
}
rd.forward(req, resp);
}
}
login.jsp
<%# 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>
<title>Login Page</title>
</head>
<body>
<form method="post" action="LoginController" >
UserName: <input type="text" name="username"><BR><BR>
PassWord: <input type="password" name="password"><BR><BR>
<input type="submit" />
</form>
</body>
</html>
Please check the else block of loginController class where i am trying to print error message on my jsp file currently the "out.print" method is unable to reflect on my login.jsp file.
Kindly help me to sort this issue Thanks in advance.
You can set the error message in request attribute and can fetch it in JSP
String errorMsg = "UserName or Password is invalid !";
req.setAttribute("errorMsg", errorMsg);
req.getRequestDispatcher("/login.jsp").forward(req, res);
Now on your JSP
<h2>${errorMsg}</h2> // Print wherever you need it
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mvc.demo.model.Authenticate;
public class LoginController extends HttpServlet {
private static final long SerialVersionUID=1L;
public LoginController()
{
super();
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String s1=req.getParameter("username");
String s2=req.getParameter("password");
RequestDispatcher rd=null;
Authenticate au=new Authenticate();
String result=au.authorise(s1, s2);
if(result.equals("success"))
{
rd=req.getRequestDispatcher("/success.jsp");
//The error was with this line
rd.forward(req, resp);
}
else
{
PrintWriter out = resp.getWriter( );
out.print("Sorry UserName or Password Error!");
rd=req.getRequestDispatcher("/login.html");
rd.include(req, resp);
}
}
}
I can't see out.close() in your code. You must close the PrintWriter object in the end.
If u want to print the error message in Jsp and first Set the Error msg in request
req.setAttribute("msg","error msg configure here");
and now you can get the same in jsp by using EL Expression.
${msg}
or You can get it by using scripting language.
<%Object obj=request.getAttribute("msg");%>
Typecast the Obj into String and print by using this
<%=str%>
Note:- Recommended to use El expression.

Categories