displaying sys properties using servlets - java

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.

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;

How to change incoming URL in java Servlet filter and redirect request to the new URL [duplicate]

This question already has answers here:
How to use a servlet filter in Java to change an incoming servlet request url?
(4 answers)
Closed 5 years ago.
I have created a webapp and I am modifying the parameters from the url to decrypt one of the parameters. After decrypting I want to append the parameters to a new URL so that I can get expected response. I have created a HTML which collects input and the landing page is a Java page inbetween I am intercepting the request. I do not want the request to go to the landing page instead I want to send it to a new url.
below is my filter code.
package com.test.secondServlet;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* Servlet Filter implementation class SecondFilter
*/
#WebFilter("/SecondFilter")
public class SecondFilter implements Filter {
public String decryptedString;
private static final String characterEncoding = "UTF-8";
Properties prop = new Properties();
InputStream input = null;
public String globalKey;
public String RedirectURL;
public String DN;
public String TYPE;
public String NAME;
public String NUMBER;
/**
* #see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
//chain.doFilter(req, res);
HttpServletRequest request = (HttpServletRequest) req;
//String requestURI = request.getRequestURI();
//System.out.println(requestURI);
String url = ((HttpServletRequest)request).getRequestURL().toString() +"?"+request.getQueryString();
System.out.println(url);
String queryString = ((HttpServletRequest)request).getQueryString();
DN = ((HttpServletRequest) request).getParameter("DN");
TYPE = ((HttpServletRequest) request).getParameter("TYPE");
NAME = ((HttpServletRequest) request).getParameter("NAME");
NUMBER = ((HttpServletRequest) request).getParameter("encryptedssn");
// String key = ((HttpServletRequest) request).getParameter("aeskey");
//Code to load key from property file
try {
String filename = "Secretkey.properties";
input = SecondFilter.class.getClassLoader().getResourceAsStream(filename);
if(input==null){
System.out.println("Sorry, unable to find " + filename);
return;
}
//load a properties file from class path, inside static method
prop.load(input);
//get the property value and print it out
globalKey=prop.getProperty("Secretkey");
System.out.println("Global Key : "+globalKey);
} catch (IOException ex) {
ex.printStackTrace();
}
//code ends
if (queryString!=null) {
//decryptingssnhere
byte[] clearText;
try {
clearText = AesEncryption.decryptBase64EncodedWithManagedIV(NUMBER, globalKey);
decryptedString = new String(clearText,characterEncoding);
System.out.println("ClearText:" +decryptedString);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println("ClearText:" + new String(clearText,characterEncoding));
//if(url.startsWith("/SSNdecrypt/SSNdecrypt")){
System.out.println("queryString :"+queryString);
System.out.println("DN : "+DN);
System.out.println("TYPE : "+TYPE);
System.out.println("NAME : "+NAME);
System.out.println("S1/ NUMBER : "+NUMBER);
//System.out.println("key : "+key);
System.out.println("decrypted S1/ Number : "+decryptedString);
//String toReplace = url.substring(38);
System.out.println("input : "+input);
//String Redirect = "SSNdecrypt?"+queryString.substring(0,13)+decryptedString;
//System.out.println("redirect : "+Redirect);
//String newURI = url.replace(queryString, Redirect);
//System.out.println("new URL"+newURI);
//String newURI = url.concat("?"+newquerystring);
RedirectURL = "http://differentservername.com/contentexplorer/servlet/VipDms?";
String Redirect =RedirectURL+"DN="+DN+"&TYPE="+TYPE+"&NAME="+NAME+"&-NUMBER="+decryptedString;
System.out.println("redircting new URL for DOCVIEW : "+Redirect);
final HttpServletRequestWrapper wrapped = new HttpServletRequestWrapper(request) {
#Override
public StringBuffer getRequestURL() {
final StringBuffer originalUrl = ((HttpServletRequest) getRequest()).getRequestURL();
return new StringBuffer(Redirect);
}
};
//chain.doFilter(wrapped, res);
wrapped.getRequestDispatcher(Redirect).forward(wrapped, res);
} else {
chain.doFilter(req, res);
}
//SSNdecrypt/SSNdecrypt?encryptedssn=1234
//res.getWriter().println(requestURI.toString());
/**if (request instanceof HttpServletRequest) {
String url = ((HttpServletRequest)request).getRequestURL().toString();
String queryString = ((HttpServletRequest)request).getQueryString();
}**/
}
/**
* #see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
/**
* #see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
}
I do not want to use the urlrewriter and would like to do it in the same filter. how do I change the requested URL?
I am using HttpServletResponse resp = (HttpServletResponse) res; resp.sendRedirect(Redirect); instead of forwarding the request which is wrapped.getRequestDispatcher(Redirect).forward(wrapped, res);. Instead of using the request qrapper I am using the HTTP response wrapper and I was able to modify the complete URL from the request url.

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

Trying to build a Gateway using Tomcat, but request from chrome gets redirected to end point

I'm trying to build a simple gateway in Tomcat, which would do authorization checks and redirect the request to different endpoint, which gets the response and sends it back to the browser.
In Tomcat I have have a simple Servlet, which uses HttpURLConnection to connect to the endpoint, which gets the response and send it back to browser.
However in Chrome my URL always gets redirected to the endpoint domain. I don't see this behavior in IE or Firefox.
For example, this is deployed to hostname test.gateway.com.
If I make a http request test.gateway.com:9500/test/index.html from browser, Servlet should make a http request to test.endpoint.com/test/index.html and return the response. Client browser should remain on test.gateway.com:9500/test/index.html
However on Chrome my URL changes to http://test.endpoint.com/test/index.html
In my web.xml I have URL Mapping which calls this servlet.
Here is the Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class AppProxyServlet
*/
#WebServlet("/AppProxyServlet")
public class AppProxyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String proxy = "http://test.endpoint.com";
/**
* #see HttpServlet#HttpServlet()
*/
public AppProxyServlet() {
super();
// TODO Auto-generated constructor stub
}
private String callEndpoint(HttpServletRequest request, String plexURL)
throws Exception {
// make
String queryString = request.getQueryString();
if (queryString != null && queryString.length() > 0) {
plexURL += "?" + queryString;
}
URL obj = new URL(plexURL);
Cookie[] cookies = request.getCookies();
StringBuffer allCookies = new StringBuffer();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
// if( cookies[ i ].getName() == "SSO")
{
allCookies.append(cookies[i].getName());
allCookies.append("=");
if ("SSO".equals(cookies[i].getName())) {
String ssostr = cookies[i].getValue();
allCookies.append(ssostr);
} else {
allCookies.append(cookies[i].getValue());
}
if (i < cookies.length)
allCookies.append(";");
// con.setRequestProperty("Cookie", cookies[ i
// ].getName()+"="+cookies[i].getValue());
}
}
}
System.out.println("All Cookies:" + allCookies.toString());
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setInstanceFollowRedirects(false);
con.setRequestProperty("Accept-Charset", "ISO-8859-1");
con.setRequestProperty("Cookie", allCookies.toString());
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("\nSending Get request to URL:" + plexURL);
System.out.println("Response code:" + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream(), "ISO-8859-1")); // iso-8859-1
int value;
StringBuffer response = new StringBuffer();
while ((value = in.read()) != -1) {
char c = (char) value;
response.append(c);
}
con.disconnect();
return (response.toString());
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// ServletContext sc = getServletContext();
StringBuilder URL = new StringBuilder("");
String URI = request.getRequestURI();
System.out.println("Full URL:" + URI);
// Form the URL
URL.append(proxy);
URL.append(URI);
String sspResponse = "";
if (URI.endsWith("css")) {
response.setContentType("text/css");
} else {
response.setContentType("text/html;charset=ISO-8859-1");
}
PrintWriter printWriter = response.getWriter();
try {
sspResponse = callEndPoint(request, URL.toString());
} catch (Exception e) {
System.out.println(e.getStackTrace());
System.out.println("Some exception occured...");
}
printWriter.println(sspResponse);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}

Categories