Storing data into ArrayList through through servlets - java

I am attempting to write an application that will make use of 3 different servlets.
One will display information, the other will allow users to enter data and display it, and the last servlet would allow users to edit existing data.
I am having trouble finding a way to store the data into an ArrayList from one servlet and displaying in a table on the servlet that displays the info.
Here is what I have so far:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
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;
#WebServlet("/DisplayItems")
public class DisplayItems extends HttpServlet {
private static final long serialVersionUID = 1L;
public static ArrayList list = new ArrayList();
public DisplayItems() {
super();
// TODO Auto-generated constructor stub
}
public void init(ServletConfig config) throws ServletException {
ServletContext context = config.getServletContext();
if (context.getAttribute("data_list") == null) {
context.setAttribute("data_list", new ArrayList<String>());
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<String> list = (List<String>) getServletContext().getAttribute("data_list");
list.add("1");
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<html>");
out.println("<head><title>Department Library</title>");
//out.println("<style>h1,h2,form,p{text-align:center;color:white}body{background-color:black;}</style></head>");
out.println("<body>");
out.println("<h1>Welcome to the Department Library</h1>");
out.println("<table border='1' cellpadding='2' cellspacing='2'>");
out.println("<thead><tr><th>ID</th><th>Type</th><th>Name</th><th>Addition Info</th><th>Available</th><th>Operation</th></tr><thead>");
out.println("<tr><td>"+list.get(1)+"</td><td>"+list.get(0)+"</td><td>"+list.get(0)+"</td><td>"+list.get(0)+"</td><td>"+list.get(0)+"</td><td><a href='./EditItem'>Edit</a></td></tr>");
out.println("<p><a href='./AddItem'>Add Item</a></p>");
out.println("<p><a href='./EditItem'>Edit Item</a></p>");
//out.println("<form method='post'><input id='inputtext' name='inputtext'></inputText><input type='submit' value='Translate' name='submit'></input></form>");
out.println("</body></html>");
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
public void row(String id, String type, String name, String info ){
}
}
AddItem
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Array;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/AddItem")
public class AddItem extends HttpServlet {
private static final long serialVersionUID = 1L;
public AddItem() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<html>");
out.println("<head><title>Add Items</title>");
out.println("<body>");
out.println("<h1>Add Items</h1>");
out.println("<form method='post'");
//name=type
//name=name
//name=info
//name=copies
out.println("<table><tbody><tr><td>Type:</td><td><select name='type'><option>Book</option><option>Tablet</option> </select></td><tr>");
out.println("<tr><td>Name:</td><td><input name='name' size='60'/></td></tr>");
out.println("<tr><td>Additional Info:</td><td><input name='info' size='60' /></td></tr>");
out.println("<tr><td># of Copies:</td><td><input name='copies' size='8' /></td></tr>");
out.println("<tr><td colspan='2' rowspan='1'><input name='add' type='submit' value='Add' /></td></tr></tbody></table>");
out.println("</form>");
out.println("<p><a href='./DisplayItems'>Display Items</a></p>");
//out.println("<p><a href='./EditItem'>Edit Item</a></p>");
//out.println("<form method='post'><input id='inputtext' name='inputtext'></inputText><input type='submit' value='Translate' name='submit'></input></form>");
out.println("</body></html>");
out.close(); }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
request.getParameter("type");
String name = request.getParameter("name");
String info = request.getParameter("info");
String copies = request.getParameter("copies");
//type.add(value);
out.println(name);
out.println(info);
out.println(copies);
}
}

Edit : add the cast from getAttribute() to List
You could use store your ArrayList in a servlet context attribute to share it between all your servlets. But you should considere using a class to store data if it is more complex than a single String.
You could try to put something like that in init method of your servlets :
public void init(ServletConfig config) throws ServletException {
ServletContext context = config.getServletContext();
if (context.getAttribute("data_list") == null) {
context.setAttribute("data_list", new ArrayList<String>());
}
}
and then in get or post methods, you simply access the shared list as :
List<String> list = (List<String>) getServletContext().getAttribute("data_list");
As suggested by Vighanesh Gursale you could also use a HashMap, if your data has a natural key.
Edit2 :
To be sure of what is happening, you should use the debugger to see what is null or add logs like following : one in each init method after creating the attribute
if (context.getAttribute("data_list") == null) {
context.setAttribute("data_list", new ArrayList<String>());
log("Creating attribute data_list");
}
else {
log("Attribute data_list already created");
}
then in doGet :
ServletContext context = getServletContext();
log ((context == null) ? "Context null!?" : "Context ok");
Object attribute = context.getAttribute("data_list");
log((attribute == null) ? "Attribute null", attribute.toString());

Related

NetBeans/Java - breakpoint can't catch exception

In NetBeans / Java - exception breakpoint (for Throwable) does not catch exceptions (RuntimeException in code of library for servlet). If you search tediously, you can find a purple stop line but without looking into the state of variables, etc. VS.NET does not have such ailments - it stops where you need it and everything is clear.
Is this a NetBeans problem or Java? How to get rid of breakpoint problems?
In here example would give you basic understanding of Exception Handling in Servlet
Actually putting a break point you can not catch a servlet exception because of it is happening before reaching the end point then you have to do something like this
When a servlet generates an error developers can handle those exceptions in various ways
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/SampleExceptionHandler")
public class SampleExceptionHandler extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
exceptionProcessor(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
exceptionProcessor(request, response);
}
private void exceptionProcessor(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// Analyze the servlet exception
Throwable throwable = (Throwable) request
.getAttribute("javax.servlet.error.exception");
Integer statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code");
String servletName = (String) request
.getAttribute("javax.servlet.error.servlet_name");
if (servletName == null) {
servletName = "Unknown";
}
String requestUri = (String) request
.getAttribute("javax.servlet.error.request_uri");
if (requestUri == null) {
requestUri = "Unknown";
}
}
}

ValidateLogin Internal Error 500

I'm attempting to create a login process using JSPs and linking them to my MySQL database. The issue I have encountered is an internal error (500) in my browser after I click "login".
I have setup my web.xml for the servlet ValidateLogin.java and I know that is not the issue. Can someone please help me here? I'll place down my code below that involves my HtmlServlet Request and Response.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ValidateLogin extends HttpServlet {
Connection connect;
ResultSet result;
String username, password, query;
DatabaseConnection database_connection;
protected void processRequest(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UF-8");
PrintWriter out = response.getWriter();
try {
// Code Here...
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}
}
Nevermind, I worked out the issue...
Change code from to...
//FROM
response.setContentType("text/html;charset=UF-8");
//TO
response.setContentType("text/html");

unable to redirect from servlet to jsp page

I am trying to create a small registeration form using jsp and servlet.
The concept goes like this:
The data being enterd in the jsp form will be checked for duplication by a servlet program.
If duplication exists , then the control must return back to the registeration (jsp) page from where the servlet was called.
I am doing this in eclipse helios.
Servlet program is under the default package under java resources ,
and jsp file is under the web content folder.
My problem is that
I am able to redirect from jsp to servlet;
but when I try to return back to the jsp page from the servlet ,
tomcat server is showing error like:
HTTP Status 404 - /RservletEs/registeration.jsp
type Status report
message /RservletEs/reg.jsp
description The requested resource is not available.
I tried both request.dispatcher() and response.sendRedirect() both are showing same error.
The file path is:
RservletEs/src/ServletCheck
Rservlets/Web Content/registeration.jsp
I have attached the source code below
somebody pls help me out of this
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.collect.ImmutableMap;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHitField;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import java.util.Map;
import com.google.gson.Gson;
/**
* Servlet implementation class ServletCheck
*/
#WebServlet("/ServletCheck")
public class ServletCheck extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
* /
public ServletCheck() {
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
String clusterName="asdf";
String hostName="localcost";
String index="testdb";
String type="emp_type";
String field="emailId";
response.setContentType("text/html");
PrintWriter out = response.getWriter();
int portNumber=26101;
final TransportClient client = new TransportClient(ImmutableSettings.settingsBuilder().put("cluster.name", clusterName)
.put("client.transport.sniff", true).build());
Settings settings = client.settings();
out.println("**settings:"+ settings);
ImmutableMap<String, String> map = settings.getAsMap();
out.println("**map::"+ map);
((TransportClient) client).addTransportAddress(new InetSocketTransportAddress(hostName, portNumber));
out.println("ES client:" + client);
String firstName=request.getParameter("firstName");
String lastName=request.getParameter("lastName");
String emailId=request.getParameter("emailId");
String age=request.getParameter("age");
String dob=request.getParameter("dob");
String eId=request.getParameter("employeeId");
String value=emailId;
SearchResponse response2 = client.prepareSearch(index)
.setTypes(type)
.setSearchType(SearchType.QUERY_AND_FETCH)
.setQuery(QueryBuilders.termQuery(field, value))
.setFrom(0).setSize(60).setExplain(true).setRouting("1")
.execute()
.actionGet();
SearchHit[] results = response2.getHits().getHits();
int length=results.length;
int i=0;
if (length>0){
response.sendRedirect(request.getContextPath()+"/registeration.jsp");
//request.getRequestDispatcher("/registeration.jsp").forward(request, response);
}
else{
out.println("setting the values");
hr_employee tweet = new hr_employee();
out.println("setting the id");
tweet.setEmployeeId(eId);
tweet.setFirstName(firstName);
out.println("setting the last name");
tweet.setLastName(lastName);
tweet.setEmailId(emailId);
tweet.setDob(dob);
String str=tweet.getEmployeeId();
/* System.out.println("the id is...."+str);
System.out.println("the firstname .... "+tweet.getFirstName());
System.out.println("teh last name....."+tweet.getLastName());
*/
out.println("initiallizing req builder");
final IndexRequestBuilder builder = client.prepareIndex(index, type,str);
out.println("setting source");
builder.setSource(new Gson().toJson(tweet));
out.println("getting response");
final IndexResponse response3 = builder.setRouting("1").execute().actionGet();
out.println("geting connected...");
out.println("ElasticSearchEJBBean:indexDocument:" + index+ ":" + type+ ":" + str + ":index results:" + response3);
response.sendRedirect(request.getContextPath()+"/ServletInsert");
}
}
/**
* #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);
}
}
sounds like there must be some problem with the way u name it.
Try like this:
right click on ur jsp file and select copy qualified name .
then use that name to redirect or dispatch like this:
request.getRequestDispatcher("/registeration .jsp").forward(request,response);
Since jsp is under the web-content folder do this
response.sendRedirect("/registeration.jsp");
or try something like this
response.sendRedirect(request.getSession().getServletContext().getRealPath("/registeration.jsp"));

Java servlet and a entity manager factory method for communicating mysql

I have a Java servlet and entity manager factory
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
this.setLevels(request);
if i use the line, then servlet does not work
//this.emf = Persistence.createEntityManagerFactory("projectPU");
servlet method continue...
out.println("this is a html content ....");
}
}
how to use Persistence.createEntityManagerFactory("projectPU") in servlet? Thanks.
Hej,
if you do not want to use any frameworks, as suggested above, you can do it for example like that:
I created a class called DataBroker, this is the class which contains the EntityManager and can persist entities or send queries againt the database.
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
public class DataBroker<T> {
private EntityManager em;
public DataBroker() {
if(em == null) {
em = Persistence.createEntityManagerFactory("ProjectPU").createEntityManager();
}
}
public void saveInput(T t) {
em.merge(t);
}
}
And now, for example a PersonServlet:
import java.io.IOException;
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 de.professional_webworkx.database.DataBroker;
import de.professional_webworkx.model.Person;
#WebServlet(urlPatterns = {"/personServlet"})
public class PersonServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 318982491390578805L;
private DataBroker<Person> dataBroker = new DataBroker<>();
public PersonServlet() {
super();
}
protected void processRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// do something with the user input from the jsp file
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
processRequest(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
processRequest(req, resp);
}
}
But it's right, these frameworks handle all this for you and you can be focused on your business logic or what else ;)
Patrick

Java ee annotations wont work

I'm trying to write annotations for the first time in my servlet. The #WebServlet is working fine. It is when I add #webInitParam that I get the red line. Also,
when I try to use the #POST annotation it gives me "POST cannot be resolved to a type".
Here's my code:
package servlets;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* Servlet implementation class Calc
*/
#WebServlet (loadOnStartup = 1 , urlPatterns = { "/CoolPage" } ,
initParams = {
#WebInitParam(name="text" , value="hello" , description="simple text"),
#WebInitParam(name="times", value="10" , description="times to print")
}
)
public class Calc extends HttpServlet {
private static final long serialVersionUID = 1L;
public Calc() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
#POST
protected void doThePost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Inside the POST method");
String username = request.getParameter("userName");
String password = request.getParameter("password");
request.setAttribute("userName", username);
request.setAttribute("password", password);
RequestDispatcher rd = request.getRequestDispatcher("jspGetting.jsp");
rd.forward(request, response);
}
}
Imports do not include sub-packages. Import the class from the javax.servlet.annotation package
import javax.servlet.annotation.WebInitParam;
It's hard to see how the servlet could compile without WebServlet being imported either(?).
import javax.servlet.annotation.WebServlet;
The POST annotation is located within the JAX-RS library
import javax.ws.rs.POST;

Categories

Resources