Setting up servlet to add a new customer - java

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");
}
}
}

Related

doPost() is not seeing a Parameter

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;
}
}

Why am I getting "Duplicate local variable error" here?

I have this code where I am trying to send an email using JAVA Mail API. When running this code in eclipse, I am getting error as "Multiple annotations found at this line:Duplicate local variable session". I have declared session variable only once then why I am getting this error?
try{
String host="smtp.gmail.com";
String to="abc#gmail.com";
final String user="xyz#gmail.com";
final String password="*********";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host",host );
properties.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,password);
}
});
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("Thank you subscriber");
message.setContent("<table><tr><td>Name</td><td>+name+</td></tr><tr><td>Address</td><td>+Addr+</td></tr><tr><td>Age</td><td>+age+</td></tr><tr><td>Qualification</td><td>+Qual+</td></tr><tr><td>Percentage</td><td>+Persent+</td></tr><tr><td>Passout</td><td>+Year+</td></tr></table>","text/html");
Transport.send(message);
System.out.println("message sent....");
}
catch (MessagingException ex) {ex.printStackTrace();}
finally {}
This is my servlet which I am using.
package com.registration;
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;
/**
* Servlet implementation class RegistrationController
*/
public class RegistrationController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public RegistrationController() {
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
}
/**
* #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 out = response.getWriter();
String name = request.getParameter("fullname");
String Addr = request.getParameter("address");
String age = request.getParameter("age");
String Qual = request.getParameter("qual");
String Persent = request.getParameter("percent");
String Year = request.getParameter("yop");
if(name.isEmpty()||Addr.isEmpty()||age.isEmpty()||Qual.isEmpty()||Persent.isEmpty()||Year.isEmpty())
{
RequestDispatcher rd = request.getRequestDispatcher("registration.jsp");
out.println("<font color=red>OOPS!! YOU MISSED OUT SOME FIELDS. FILL THEM AGAIN</font>");
rd.include(request, response);
}
else
{
RequestDispatcher rd = request.getRequestDispatcher("home.jsp");
rd.forward(request, response);
}
}
}
jsp has an inbuilt session variable that you can actually use. So since you are reusing it you are getting the duplicate error.
This is the equivalent of doing Session session=request.getSession() in a servlet;

the specified http method is not allowed for the requested resource in servlet

I write controller with annotations to mapping the controller.
In the page jsp i have ajax request to the controller but i get error
"
type: Status report
message: HTTP method GET is not supported by this URL
description: The specified HTTP method is not allowed for the requested resource.
"
why it's happend?
the controller class:
package controllers;
import java.io.IOException;
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;
import javax.servlet.http.HttpSession;
import model.AntiXss;
import model.HibernateToDoListDAO;
import model.Items;
import model.ToDoListDAOException;
import model.User;
#WebServlet("/DeleteMessage/*")
public class DeleteMessageController extends HttpServlet{
private static final long serialVersionUID = 1L;
HttpSession session = null;
User user = null;
Items item = null;
List<Items> items = null;
String message;
HibernateToDoListDAO actions = HibernateToDoListDAO.getInstance();
public DeleteMessageController()
{
super();
}
#Override
#SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
session = request.getSession(false);
if(session == null)
{
response.sendRedirect("error.jsp");
}
try{
message = request.getParameter("item");
if(AntiXss.isUsername(message) == false )
{
if(session != null){
session.invalidate();
}
response.sendRedirect("error.jsp");
}
else
{
items = (List<Items>)session.getAttribute("listItems");
user = (User)session.getAttribute("user");
for(Items newItem : items)
{
if(newItem.getMessage() == message && newItem.getUsername() == user.getUsername())
{
item = newItem;
}
}
actions.deleteItems(item);
items = actions.getItems(user.getUsername());
session.setAttribute("listItems", items);
request.getRequestDispatcher("Index.jsp").forward(request, response);
}
}catch(ToDoListDAOException e){
e.printStackTrace();
}
}
}
and the jsp page:(i put here just the ajax request);
var xmlhttp = new XMLHttpRequest();
var item = "test";
if((txtSearch(item, item.length)) == 1)
{
var url = "DeleteMessage";
try
{
xmlhttp.open("post",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("item=" + item);
}catch(e){
alert("unable to connect to server");
}
}

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.

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