doPost() is not seeing a Parameter - java

I am sure that a similar question has probably been asked already and I have been working on this for hours to the point where I'm like... this is getting ridiculous.
Seeing that I suddenly have plenty of time and I am assuming a lot of you do too, I figured let me ask StackOverflow to see if they could help. Also I apologize in advance for all the detail in this question, I just want to give you all the information that I have gathered from these frustrating few hours.
Okay so I am trying to build a very basic web forum using Java Servlets in eclipse. This was a homework assignment that was due about a week ago, I already submitted it not working at 100% but I revisited it now trying to figure out where I went wrong. I am sure you are thinking, "But Karla, there is a much easier way to do this". I am sure there is but this was a project on MVC before the introduction of JSP so it had to be done this way.
My problem: It seems that the problem lies in the servlet CreateTopic in the doPost(), it cannot pull the parameter 'id' so that it can redirect to Display Topics. I will post all servlets that I have at the moment. So the short answer of what it is supposed to do:
Shows all forums
If you click on a forum name, you get a list of topics under that forum
If you click create topic, you should be able to add to the topic list under that forum one you hit add, it all goes down hill.
This is what I know:
The parameter is a string and I have tried to pull it using Integer.valueOf(…) and Integer.parseInt(…) and it doesn't work.
The error I get is a null pointer, I have tested it by manually inserting an id number and it redirects just fine so I figured that there is an issue with doPost() where it cannot seem to pull the parameter ID..
I know that doGet() is able to pull this parameter as it can pull the name of the object and the counter of the amount of topics listed under the forum through the getter and setters of the class Forum.
I have also tried making the getForum() to take a string as an argument and I feel that the only issue that the program is having is through the parsing of integer but I realize now that it is mostly due to the pointer being null which is confusing because doGet() is able to access this parameter.
I am open to all suggestions and or solutions, thank you so very much!
Server: Tom Cat v8.5
IDE: Eclipse Version: 2019-12 (4.14.0)
Build id: 20191212-1212
Java Version: 13
DisplayForum:
package web.WebForum;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletConfig;
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 DisplayForum
*/
#WebServlet("/DisplayForum")
public class DisplayForum extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public DisplayForum() {
super();
// TODO Auto-generated constructor stub
}
public void init(ServletConfig config) throws ServletException {
super.init(config);
Topic topic = new Topic("Eclipse Problem","Karla Valencia");
List<Forum> forums = new ArrayList<Forum>();
forums.add(new Forum("General Discussion",topic));
forums.add(new Forum("CS3220 Web Programming"));
getServletContext().setAttribute("forums", forums);
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
#SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
List<Forum> forums = (List<Forum>) getServletContext().getAttribute("forums");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Forums</title></head><body>");
out.println("<table border = '1'>");
out.println("<tr><th>Forum</th><th>Topics</th></tr>");
for(Forum forum : forums) {
out.println("<tr><td><a href='DisplayTopics?id=" + forum.getForumId()+"'>" + forum.getForumName() + "</a></td><td style = 'text-align: center'>" + forum.getNumberOfTopics() + "</td><td>" + forum.getForumId() +"</td></tr>");
}
out.println("</table>");
out.println("</body></html>");
}
/**
* #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);
}
}
DisplayTopics:
package web.WebForum;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
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 DisplayTopics
*/
#WebServlet("/DisplayTopics")
public class DisplayTopics extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public DisplayTopics() {
super();
// TODO Auto-generated constructor stub
}
public Forum getForum (int id) {
#SuppressWarnings("unchecked")
List<Forum> forums = (List<Forum>) getServletContext().getAttribute("forums");
for(Forum forum: forums) {
if(forum.getForumId() == id) {
return forum;
}
}
return null;
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
int id = Integer.valueOf(request.getParameter("id"));
Forum forum = getForum(id);
List<Topic> topics = forum.getTopics();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Forums</title></head><body>");
out.println("<h2>"+ forum.forumName +"</h2><table border = '1' style = 'text-align: center'>");
out.println("<tr><th>Topic</th><th>Author</th><th>Replies</th><th>Last Post</th></tr>");
for(Topic topic : topics) {
out.println("<tr><td><a href='#'>" + topic.getTopicName() + "</a></td><td style = 'text-align: center'>" + topic.getAuthor() + "</td><td>" + topic.getNumComments() +"</td><td>"+ topic.getLastPost() +"</td></tr>");
}
out.println("</table>");
out.println("</br><a href='CreateTopic?id="+ forum.getForumId() +"' > Create Topic</a>");
out.println("</body></html>");
}
/**
* #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);
}
}
Create Topic Servlet: (where I think issue is stemming from)
package web.WebForum;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
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("/CreateTopic")
public class CreateTopic extends HttpServlet {
private static final long serialVersionUID = 1L;
public CreateTopic() {
super();
// TODO Auto-generated constructor stub
}
public Forum getForum (int id) {
#SuppressWarnings("unchecked")
List<Forum> forums = (List<Forum>) getServletContext().getAttribute("forums");
for(Forum forum: forums) {
if(forum.getForumId() == id) {
return forum;
}
}
return null;
}
public Forum getForum(String id) {
#SuppressWarnings("unchecked")
List<Forum> forums = (List<Forum>) getServletContext().getAttribute("forums");
for(Forum forum: forums) {
if(String.valueOf(forum.getForumId()) == id) {
return forum;
}
}
return null;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Integer id = Integer.valueOf(request.getParameter("id"));
Forum forum = getForum(id);
request.setAttribute("forumName", forum.getForumId());
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Create Topic</title></head><body>");
out.println("<h2><a href='DisplayTopics?id=" + forum.getForumId()+"'>" +forum.forumName +"</a> > Create Topic</h2>");
out.println("<form action='CreateTopic' method='post'>");
out.println("<table border = '1'><tr><th>Your Name: </th><td><input type ='text' name='author'></td></tr>");
out.println("<tr><th>Subject: </th><td><input type ='text' name='name'></td></tr>");
out.println("<tr><th>Content</th><td><textarea name='comment'cols='40' rows='4'></textarea></td></tr>");
out.println("<tr><td col='4' row ='1'><input type='submit' name='add' value='Add'/></td></tr>");
out.println("</table></form></body></html>");
out.println(id);
}
#SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String author = request.getParameter("author");
String name = request.getParameter("name");
String comment = request.getParameter("comment");
List<Forum> forums = (List<Forum>) getServletContext().getAttribute("forums");
Topic topic = new Topic(author,name,comment);
response.sendRedirect("DisplayTopics?id=#");
}
}
Forum Class:
package web.WebForum;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class Forum {
static AtomicInteger count = new AtomicInteger(0);
String forumName;
int numberOfTopics;
private final int forumId;
List<Topic> topics = new ArrayList<Topic>();
public Forum(String forumName) {
this.forumName = forumName;
this.numberOfTopics = 0;
this.forumId = count.incrementAndGet();
}
public Forum(String forumName, Topic topic) {
this.forumName = forumName;
this.numberOfTopics = 0;
this.forumId = count.incrementAndGet();
addTopic(topic);
}
public Forum(String forumName, int numberOfTopics) {
this.forumName = forumName;
this.numberOfTopics = numberOfTopics;
this.forumId = count.incrementAndGet();
}
public void addTopic(Topic topic){
this.topics.add(topic);
this.numberOfTopics++;
}
public String getForumName() {
return forumName;
}
public void setForumName(String forumName) {
this.forumName = forumName;
}
public int getNumberOfTopics() {
return numberOfTopics;
}
public void setNumberOfTopics(int numberOfTopics) {
this.numberOfTopics = numberOfTopics;
}
public int getForumId() {
return forumId;
}
public List<Topic> getTopics() {
return topics;
}
public void setTopics(List<Topic> topics) {
this.topics = topics;
}
}
Topic class:
package web.WebForum;
import java.util.ArrayList;
import java.util.List;
public class Topic {
String topicName;
String author;
int numComments;
String lastPost = "no posts";
String comment;
List<String> comments = new ArrayList<String>();
public Topic ( String topicName, String author,String comment) {
this.topicName = topicName;
this.author = author;
this.comment = comment;
}
public Topic ( String topicName, String author) {
this.topicName = topicName;
this.author = author;
}
public void addComment(String comment) {
comments.add(comment);
//this.lastPost = comment.postedOn;
this.numComments++;
}
public String getTopicName() {
return topicName;
}
public void setTopicName(String topicName) {
this.topicName = topicName;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getNumComments() {
return numComments;
}
public void setNumComments(int numComments) {
this.numComments = numComments;
}
public String getLastPost() {
return lastPost;
}
public void setLastPost(String lastPost) {
this.lastPost = lastPost;
}
public List<String> getComments() {
return (List<String>) comments;
}
public void setComments(List<String> comments) {
this.comments = (List<String>) comments;
}
}

Related

ClassNotFoundException even after including mysql-connector-bin.jar and mysql-jdbc.jar

While debugging this servlet code in a dynamic web project in Spring tool suite.It throws class not found exception at this line Class.forName("com.mysql.jdbc.Driver"); even after incuding mysql connector and mysql jdbc jars. Please help.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class dbclassview
*/
public class dbclassview extends HttpServlet {
private int name;
private int pcaNo;
private String ip;
//getter and setter methods
public void setName(int name)
{
this.name=name;
}
public void setPcaNo(int pcaNo)
{
this.pcaNo=pcaNo;
}
public void setIp(String ip)
{
this.ip=ip;
}
public int getName()
{
return name;
}
public int getPcaNo()
{
return pcaNo;
}
public String getip()
{
return ip;
}
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public dbclassview() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Using GET Method to Read Form Data";
String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
List<dbclassview> list=new ArrayList();
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/database_name?autoReconnect=true&useSSL=false","root","password");
Statement stmt=con.createStatement();
//String sql = "Create table students(Student_ID Integer,Student_Name Varchar(20),Student_Age Integer)";
//stmt.executeUpdate(sql);
//stmt.executeUpdate("Insert into students(Student_ID,Student_Name,Student_Age) values (1,'sid',22)");
ResultSet rs=stmt.executeQuery("Select * from products");
while (rs.next()) {
dbclassview type1=new dbclassview();
type1.setName(rs.getInt(1));
type1.setPcaNo(rs.getInt(2));
type1.setIp(rs.getString(3));
list.add(type1);
}
rs.close();
con.close();
}catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
for(int i=0;i<list.size();i++)
{
System.out.println(list.get(i));
}
}
out.println(docType + "<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ list + "\n" +
" <li><b>Last Name</b>: "
+ "\n" +
"</ul>\n" +
"</body></html>");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}

displaying sys properties using servlets

I am working with servlets as a newbie i have been trying to get desktop application and trying to see how they could come out when i use servlets,with the system.getproperty method if i hit my submit button i'm getting a blank message.
this is my jsp code.
<form action="checkservlet" method="get">
<input type="submit" value="submit"/><br/>
</form>
this is my servlet code
package com.check.pack;
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;
/**
* Servlet implementation class checkservlet
*/
#WebServlet("/checkservlet")
public class checkservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public checkservlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter write = response.getWriter();
Mulizwa Mcheck = new Mulizwa();
}
}
this is my class code
package com.check.pack;
import java.util.*;
public class Mulizwa {
public static void main(String[] args) {
Properties prop = System.getProperties();
Set<Object> keySet = prop.keySet();
for(Object obj : keySet){
System.out.println("System Property: {"+obj.toString()+","+System.getProperty(obj.toString())+"}");
}
}
}
i'm no expert but i'm here to learn,what i'm expecting from the code above if i hit the submit button i need to see the response in the browser about the system properties like os name java version etc.
First you need to write a function in your Mulizwa class that might return a String of your system properties instead of its main method that prints the properties on Standard out, some thing like this
public String getPropertyString (){
Properties prop = System.getProperties();
StringBuilder propertyString = new StringBuilder();
Set<Object> keySet = prop.keySet();
for(Object obj : keySet){
propertyString.append("System Property: {"+obj.toString()+","+System.getProperty(obj.toString())+"}");
}
return propertyString.toString();
}
Then in your servlet's doPost method,
PrintWriter write = response.getWriter();
Mulizwa mCheck = new Mulizwa();
write.write(mCheck.getPropertyString());
change
package com.check.pack;
import java.util.*;
public class Mulizwa {
public String getDetails(){
ResourceBundle rb = ResourceBundle.getBundle("System", Locale.getDefault());
StringBuilder str = new StringBuilder(" ");
Enumeration<String> en = rb.getKeys();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String value = rb.getString(key);
str.append(key+":"+value +"\n");
}
return sb.toString();
}
}
and in servelet class change doPost like the following
PrintWriter out = response.getWriter();
out.println(new Mulizwa().getDetails());
Instead of writing this code in main,keep it in a method in Mcheck class like this
public void writeSystemPropertiesInResponse(HttpServletResponse response)) {
Properties prop = System.getProperties();
Set<Object> keySet = prop.keySet();
PrintWriter writer = response.getWriter();
for(Object obj : keySet){
writer.write("System Property: {"+obj.toString()+","+System.getProperty(obj.toString())+"}");
}
}
And call this method in your servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
//PrintWriter write = response.getWriter();no need of this
Mulizwa Mcheck = new Mulizwa();
Mcheck.writeSystemPropertiesInResponse(resonse);
}
UPDATE
If you don't wanna pass response as argument,you can use StringBuilder to build a string and write using PrintWriter as suggested in other answers.

Java Servlet Async Support

Recently i have started working on Java Servlet Async functionality. I have written sample code shown below to check aysnc Functionality. I am running it on single core processor. I am submitting 100 requests (image requests) from jsp. I have added "Request Submmited:::" SOP in code. It is displaying SOP for first 0 to 6 requests then after some time it is displaying SOP for 6 to 11.... why it is not displaying SOP for all 100 requests.
package com.test;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.AsyncContext;
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(urlPatterns={"/Test"}, asyncSupported = true)
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
public Test() {
super();
}
int counter = 0;
#Override
protected void doGet(final HttpServletRequest request,
final HttpServletResponse response) throws ServletException,
IOException {
System.out.println("Request Submmited:::" + counter++);
final AsyncContext ctx = request.startAsync();
ctx.start(new Runnable() {
public void run() {
try {
String count = request.getParameter("test");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileInputStream fin = new FileInputStream(
"D:/TESTImages/8_0_0_NUCLEI" + count + ".jpg");
byte[] data = new byte[fin.available()];
fin.read(data);
response.getWriter().print(new String(data));
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
}
ctx.complete();
}
});
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Seems that the default thread pool size is 5, for the pool that procesess async requests in your servlet container. Try providing init params as below:
#javax.servlet.annotation.WebServlet(urlPatterns={"/Test"}, asyncSupported = true,
initParams = { #WebInitParam(name = "threadpoolsize", value = "100") })

Setting up servlet to add a new customer

What I am trying to accomplish is trying to make a new customer in the my servlet when the user clicks submit on a form. The form is in the form of a jsp file. So when the user clicks submit it will go to the doPost method in the servlet. I want to add one to the customer id when I click submit also. No database is involved yet. Still learning concepts.
Errors are thrown everytime I click submit. Both the errors I have in the doPost are thrown.
How can I fix this
Servlet
package edu.witc.Assignment03.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//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 edu.witc.Assignment03.model.Customer;
import edu.witc.Assignment03.model.Phone;
import edu.witc.Assignment03.model.States;
#WebServlet(description = "servlet to get act as controller between form and models", urlPatterns = { "/customerServlet","/addCustomer","/addPet", "/customerManagement" })
public class CustomerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public CustomerServlet() {
super();
}
private List<edu.witc.Assignment03.model.Customer> customers = new ArrayList<Customer>();
private void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = request.getSession();
Phone phone = new Phone();
States state = new States();
Collection<Phone> phones = phone.getPhoneCollection();
Collection<States> states = state.getStateCollection();
session.setAttribute("phones", phones);
session.setAttribute("states", states);
}
private void addCustomer(HttpServletResponse response, HttpServletRequest request)//redirect to form
throws IOException, ServletException {
String url = "/customerManagement.jsp";
processRequest(request, response);
Customer customer = new Customer();
HttpSession session = request.getSession();
session.setAttribute("customer", customer);
request.getRequestDispatcher(url).forward(request,response);
}
private void addPet(HttpServletResponse response, HttpServletRequest request)//redirect to pet page
throws IOException, ServletException {
String url = "/pets.jsp";
request.getRequestDispatcher(url).forward(request,response);
}
private Customer getCustomer(int customerId) {
for (Customer customer : customers) {
if (customer.getCustomerId() == customerId) {
return customer;
}
}
return null;
}
private void makeCustomerReceipt(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
String url = "/receipt.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
if("addCustomer".equals(action)) {
System.out.println("doGet add customer");
addCustomer(response, request);
}
else if("addPet".equals(action)) {
System.out.println("doGet pet");
addPet(response, request);
}
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// update customer
int customerId = 0;
Customer testCustomer = new Customer();
testCustomer.setCustomerId(1);
testCustomer.setFirstName("Test");
customers.add(testCustomer);
try {
customerId =
Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
response.getWriter().write("Error: Customer ID could not be parsed to a number");
}
Customer customer = getCustomer(customerId);
if (customer != null) {
customer.setFirstName(request.getParameter("firstName"));
customer.setLastName(request.getParameter("lastName"));
customer.setEmail(request.getParameter("email"));
customer.setPhone(request.getParameter("phone"));
customer.setAddress(request.getParameter("address"));
customer.setCity(request.getParameter("city"));
customer.setZip(request.getParameter("zip"));
makeCustomerReceipt(request, response);
}
else
{
response.getWriter().write("Error: customer is null");
}
}
}

I have a trouble with my Login Authentication Servlet

i have a problem with my login authentication login.jsp
I have a class UsuarioLogin:
package br.com.cad.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import br.com.cad.basica.Contato;
public class UsuarioLogin {
private Contato usuario;
public UsuarioLogin(Contato usr)
{
usuario=usr;
}
public boolean verificaLogin(){
if(usuario.getEmail()!=null && usuario.getSenha()!=null)
{
try
{
ConnectDb con = new ConnectDb();
String strsql="SELECT PF_EMAIL, PF_SENHA FROM DADOS_CADASTRO WHERE PF_EMAIL = ? and PF_SENHA = ?;";
PreparedStatement stmt = con.getConnection().prepareStatement(strsql);
stmt.setString(1, usuario.getEmail());
stmt.setString(2, usuario.getSenha());
boolean logado = false;
ResultSet rs=stmt.executeQuery();
rs.close();
stmt.close();
return logado;
}
catch (SQLException e)
{
e.printStackTrace();
return false;
}
}
return false;
}}
and my Servlet LoginAuthentication:
package br.com.cad.servlet;
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 javax.servlet.http.HttpSession;
import br.com.cad.basica.Contato;
import br.com.cad.dao.UsuarioLogin;
public class LoginAuthentication extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
} finally {
out.close();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String email=request.getParameter("email");
String senha=request.getParameter("password");
RequestDispatcher rd = null;
Contato user = new Contato();
user.setEmail(email);
user.setSenha(senha);
UsuarioLogin ul = new UsuarioLogin(user);
if(ul.verificaLogin())
{
HttpSession sessao = request.getSession();
sessao.setAttribute("USER",email);
rd=request.getRequestDispatcher("logado.jsp");
rd.forward(request,response);
}
else
{
request.setAttribute("msg", "Usuário ou senha inválidos");
rd=request.getRequestDispatcher("login.jsp");
rd.forward(request,response);
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
But i don't know how i got a user or password invalid if i entered a valid e-mail and pass!!! please somone can help me?
I guess the loganto is the boolean flag indicating that a user is logged in or not.
The problem in your code is that you execute the Select query but you never check if a record was found. You can do it like this:
ResultSet rs=stmt.executeQuery();
while(rs.next()){
loganto=true; //a valid record was found so return true
}
rs.close();
return loganto;

Categories