taking servlet information with submit button [duplicate] - java

This question already has answers here:
How to call servlet class from HTML form
(2 answers)
Closed 7 years ago.
Im trying to create a Servlet application. When I hit the submit button I want to clear the forms and add the information to a unordered list and store the data. The issue is that I do not know how to evaluate when the button is pushed.
package org.gephi.demos;
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
// Extend HttpServlet class
#WebServlet(name = "HelloWorld", urlPatterns = {"/test"}, loadOnStartup=1)
public class HelloWorld extends HttpServlet {
private String message;
private File f;
private GephiBuilder gb;
//private Main m;
public void init() throws ServletException
{
gb = new GephiBuilder();
System.out.println("Initialized");
// Do required initialization
message = "Hello World for sure";
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");
//m = new Main(gb);
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println(HTMLUserInput("do you want a Nodes(n) or auto(a)", "directory", "d"));
String directory = request.getParameter("d");
// do some processing here...
// build HTML code
if(request.getParameter("button")!=null)
{
System.out.println("Hello");
//response.getParameter("d").valu;
String htmlRespone = "<html>";
htmlRespone += "<h2>Your directory is: " + directory + "<br/>";
htmlRespone += "</html>";
// return response
out.println(htmlRespone);
}
//out.println(addJSCode());
}
public String HTMLUserInput(String question, String id, String name){
String htmlOutput = "<form action=\"HelloWorld\"><label>"+question+"</label>"
+"<input name = \""+name+"\" id=\""+id+"\" type=\"text\"/>"
+"<input id=\"button\" type=\"button\">Submit</form>";
return htmlOutput;
}
public void destroy()
{
// do nothing.
}
}
If I press the button nothing changes, I imagine because this code is only evaluated on startup, how do I get it evaluated anytime I press my submit button.

1.You have to use URL for your servlet(wich was specified in servlet mapping) in action attribute . For example: <form action='/test'>
2.There is several way how to submit the form to the server. You can use <input type="submit">Submit</input> inside form tag .
Or if you want to use tag button you have to set id attribute for the form (<form id='myform' .../>) and connect button with the form specifying this id in form attribute:
<button type="submit" form="myform">Submit</button>
And button tag does not have to be located within form tag.
3.After that you can get the content of your form using request.getParameter("input name") and handle these data.

Use <input type="submit" /> instead of <button>
Your urlPatterns = {"/xxxxx"}, should match form action="xxxxx"

Related

Print output in TextArea(append-way) from different class in JSP/Servlet

I have below Dynamic web project setup
Index.jsp
<form action="submitClick" method ="post"
<textarea> id="textarea" name="textarea" rows="25" cols="100">${result}</textarea>
<input type="submit">
SubmitClick.java //servlet class
public class SubmitClick extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response){
MainLogicClass mainLogic = new MainLogicClass(username,password); //let's suppose hardcoded
request.setAttribute("result", "Hello");// Hello is getting printed on textarea, but I want to print output text on textarea from MainLogicClass.
getServletContext().getRequestDispatcher("/index.jsp").forward(request,response);
}
}
MainLogicClass//different class, present in same package
public class MainLogicClass{
public MainLogicClass(String username, String password){
//DB Connection logic
System.out.println("Database Connection successful");
/* I want to print "Database Connection successful" on textarea which presents on index.jsp
And after that, I need to print few more output so that the text gets appended to textarea like-
"Database Connection successful
DB query executed
DB connection closed"
*/
}
}
How can I print text from MainLogicClass to Servlet using request.setAttribute method or any other workaround.
Constructor doesn't have any return type so instead of constructor you can create a method and put your logic code there and return some value from there . So , your method inside MainLogicClass will look like somewhat below :
public String Something(String username, String password){
String msg = "" ;
msg +="Something to return";
msg +="soemthing more";
//your logic code
return msg;//return back
}
And then in your servlets doPost method do like below :
MainLogicClass mainLogic = new MainLogicClass();
String message = mainLogic.Something(String username, String password);//call that function
request.setAttribute("result", message );

How to create simple web service that takes input as JSONObject in java

Hello I am new to web services.
I am able to create simple web service which accept input string and return another string using eclipse.
But when it comes to JSONObject i am facing problems,while invoking web service
public class HelloWorld {
private int rowNumber;
public byte[] readJSON(JSONObject jsonObject ) throws Exception
{
rowNumber=0;
File excelFile = new File("Test2.xlsx");
OutputStream outStream = new FileOutputStream(excelFile);
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("TestSheet");
XSSFRow row ;
XSSFCell cell;
JSONArray msg = (JSONArray) jsonObject.get("messages");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
row = sheet.createRow(rowNumber);
cell= row.createCell(0);
cell.setCellValue(iterator.next());
rowNumber=rowNumber+1;
}
workbook.write(outStream);
outStream.close();
Path path = Paths.get("Test2.xlsx");
byte[] data = Files.readAllBytes(path);
return data;
}
public float addValue(float value) {
return (value + 10);
}
}
so help me to consume the web service.
SimpleDeserializer encountered a child element, which is NOT expected, in something it was trying to deserialize. this error i am getting when i try to invoke client. and another thing input parameter as JSONObject is allowed?
You can use the package Package javax.ws.rs.
import javax.ws.rs.*;
Here would be a short of example of the library in action:
Here is the HTML:
<div>
Welcome and happy <span id="today"></span>.
What's your name?
<input id="name" type="text" autofocus />
<button id="submit" onclick="greet()">Submit</button>
</div>
<div id="greet">
<!-- greeting goes here -->
</div>
<script>
// fills in <span id="today">...</span> with today's day of the week
// returned from /rest/today server endpoint
function today() {
$.get("/rest/today", function(theday) {
$("#today").text(theday);
});
};
// fills in <div id="greeting">...</div> with the greeting
// returned from calling the /rest/hello?name=... server endpoint
// with the name from the input text box
function greet() {
var thename = $("#name").val();
$.get("/rest/hello", { name: thename }, function(thehello) {
$("#greet").text(thehello);
})
.fail(function(jqXHR, textStatus, errorThrown) {
// displays server error message, e.g. if called with empty name
$("#greet").text(textStatus + ": " + errorThrown);
});
};
$(today); // execute today() after DOM is ready, see https://api.jquery.com/ready/
</script>
</body>
</html>
With corresponding java code:
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
/**
* REST service that greets requests.
*
* This is a "root resource class" as explained in
* https://jersey.java.net/documentation/latest/jaxrs-resources.html
*/
#Path("/")
public class HelloService {
#GET
#Path("/today")
public String today() {
return DayOfWeek.today();
}
#GET
#Path("/hello")
public Response hello(#QueryParam("name") String name) {
if (name == null || name.isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST).build();
} else {
return Response.ok("hello " + name).build();
}
}
}
In order to work with JSON objects, you'll need to use Gson.toJson(). Do something along the lines of this:
String json = new Gson().toJson(some_object);
return Response.ok(json, MediaType.APPLICATION_JSON).build();
I hope this was helpful!
You can try to use Jackson: very good library in which you define you Java object model class that you can convert to JSON or parse from JSON.
You will find a lot of examples

Servlet with jdbc response to client [duplicate]

This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 6 years ago.
I have a database with houses, and HTML page with <SELECT>, where user need to select a district where the houses are located.
Servlet:
#WebServlet("/post")
public class HosesBaseServlet extends HttpServlet {
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
//choice from html form
String choice = request.getParameter("district");
//Database parameters
final String DB_CONNECTION = "jdbc:mysql://localhost:3306/mydb2";
final String DB_USER = "root";
final String DB_PASSWORD = "root";
Connection conn;
try {
conn = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
System.out.println("Connection available");
PreparedStatement ps = conn.prepareStatement("SELECT Square, RoomNumbers, Price FROM houses WHERE District = " + choice);
}catch (SQLException ex) {
System.out.println("Fail to connect with base");
}
}
}
How can I put SQL select results into HTML page and give it back to client?
I created class House
public class Hosue implements Serializable {
private String price;
private String square;
private String RoomNumbers;
public String getPrice() {
return price;
}
public String getSquare() {
return square;}
public String getRoomNumbers() {
return RoomNumbers;}
public void setPrice(String price) {
this.price = price;
}
public void setSquare(String square) {
this.square = square;
}
public void setRoomNumbers(String roomNumbers) {
RoomNumbers = roomNumbers;
}
}
and houses
public class Houses {
public List<House> getList() {
}
}
and add script to my html. What next, how to add information from select to this list?
You can solve your problem as said by Jeed in the previous answer. However, it would be better if you model your db entities with Java objects and use them to encapsulate information from and towards the db. You may also use the DAO programming pattern to better organize your code, thus you can define simple objects (beans) to model data (your database entities) and data access object (DAO object) in which you would encode interaction with the db (your jdbc code).
Then you will have something like this to query your db (this code will be in your servlet):
HouseDAO h=new HouseDAO(db connection param...)
ArrayList<House> list=h.selectHouses();
In the HouseDAO object you will create a method selectHouse in which you will basically move the jdbc code you have in your servlet right now. By the way, your are missing a part in which you call the method execute query from the ps object. This method returns a ResultSet object which contains the query result.
With the code above, you will have your data in the ArrayList list, and you can use the code suggested by Jeed to output it.
Clearly, if you want to avoid using jsp, you can print your html code directly in your servlet. I do not recommend this as you would merge view details with control and model code. This is not good especially if you are planning to change your view in the future.
Add result of your query to some List or custom object and set it as attribute in your request object.
request.setAttribute("result", result);
and then forward to your next page using RequestDispatcher.
Use Gson external Library for sending java-List into String form to
HTML,
Your Servlet Code looks likewise,
List<House> listofHouses = getList from Database;
Gson gson = new Gson();
String json_obj = gson.toJson(listofHouses);
response.getWriter().println(json_obj);
Your HTML(use Jquery-ajax for Handling result & send Request to
Servlet ) Code looks some what nearer likewise......
<script>
$.ajax({
url: 'Servlet.do?distinct=YOUR_SELECTED_district_NAME',
type: "POST/GET",
data: query,
dataType: 'application/json; charset=utf-8',
success: function (data) {
var returnedData = JSON.parse(data);
alert(data);
$.each(data, function(index, value) {
('#your_drop_down_tag_id').append($('<option>').text(value).attr('value', index));
});
}
});
</script>
NOTE: jquery-XXX.js file must be inclue into your project and into your html file properly.

Can't display StreamedContent in Primefaces media in JSF [duplicate]

I use the <p:media> to display static PDF content.
<p:media value="/resource/test.pdf"
width="100%" height="300px" player="pdf">
</p:media>
How can I change it to display dynamic content?
Like as in <p:graphicImage>, the value attribute can point to a bean property returning StreamedContent. This only requires a special getter method for the reasons which is explained in detail in the following answer on using <p:graphicImage> with a dynamic resource from a database: Display dynamic image from database with p:graphicImage and StreamedContent.
In your particular example, it would look like this:
<p:media value="#{mediaManager.stream}" width="100%" height="300px" player="pdf">
<f:param name="id" value="#{bean.mediaId}" />
</p:media>
With
#ManagedBean
#ApplicationScoped
public class MediaManager {
#EJB
private MediaService service;
public StreamedContent getStream() throws IOException {
FacesContext context = FacesContext.getCurrentInstance();
if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
// So, we're rendering the HTML. Return a stub StreamedContent so that it will generate right URL.
return new DefaultStreamedContent();
} else {
// So, browser is requesting the media. Return a real StreamedContent with the media bytes.
String id = context.getExternalContext().getRequestParameterMap().get("id");
Media media = service.find(Long.valueOf(id));
return new DefaultStreamedContent(new ByteArrayInputStream(media.getBytes()));
}
}
}

Java Servlet FileUpload error

I am learning java servlet programming and I wrote a program to upload files, I'm having a strange problem with the program. when it says it finished uploading the file and when i click the link to see it I get a 404 error and when i check the directory (where the file is supposed to be saved ) its empty. I checked the log and there are no error messages.I got the code from a book I'm using to learn servlet and jsp.
here is my java code
import java.io.*;
import java.util.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class FileUpload
*/
#WebServlet("/FileUpload")
public class FileUpload extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public FileUpload() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.print("File upload success. <a href=\"/Project_One/files");
out.print("\">Click here to browse through all uploaded ");
out.println("files.</a><br>");
ServletInputStream sis = request.getInputStream();
StringWriter sw = new StringWriter();
int i = sis.read();
for(;i!=-1 && i!= '\r';i=sis.read())
{
sw.write(i);
}
sis.read(); //ditch \'n'
String delimiter = sw.toString();
while(true)
{
StringWriter h = new StringWriter();
int[] temp = new int[4];
temp[0] = (byte)sis.read();
temp[1] = (byte)sis.read();
temp[2] = (byte)sis.read();
h.write(temp[0]);
h.write(temp[1]);
h.write(temp[2]);
//read header
for(temp[3]=sis.read();temp[3]!=-1;temp[3]=sis.read())
{
if(temp[0] == '\r' &&
temp[1] == '\n' &&
temp[2] == 'r' &&
temp[3] == '\n')
{
break;
}
h.write(temp[3]);
temp[0]= temp[1];
temp[1]= temp[2];
temp[2]= temp[3];
}
String header = h.toString();
int StartName = header.indexOf("name=\"");
int endName = header.indexOf("\"",StartName+6);
if(StartName == -1|| endName == -1)
{
break;
}
String name = header.substring(StartName+6,endName);
if(name.equals("file"))
{
StartName = header.indexOf("filename=\"");
endName = header.indexOf("\"",StartName+10);
String filename = header.substring(StartName+10,endName);
ServletConfig config = getServletConfig();
ServletContext sc = config.getServletContext();
//File file = new File(sc.getRealPath("/files"));
//file.mkdirs();
FileOutputStream fos = new FileOutputStream(sc.getRealPath("/")+"/"+filename);
//write the file to disk
int length = delimiter.length();
//delimiter ="\r\n"+delimiter;
byte[] body = new byte[delimiter.length()];
for(int j=0;j<body.length-1;j++)
{
body[j]=(byte)sis.read();
fos.write(body[j]);
}
//check it wasn't a 0 length file
//if(!delimiter.equals(new String (body)))
//{
int e = body.length-1;
i=sis.read();
for(;i!=-1;i=sis.read())
{
body[e]=(byte)i;
/*fos.write(body[0]);
for(int l=0;l<body.length-1;l++)
{
body[l]=body[l+1];
}*/
//body[e]=(byte)i;
if(delimiter.equals(new String (body)))
{
break;
}
//length++;
fos.write(body[e]);
for(int k=0;k<body.length-1;k++)
{
body[k]=body[k+1];
}
length++;
}
fos.flush();
fos.close();
out.println("<p><b>Saved File:</b>"+filename+"</p>");
out.println("<p><b>Length:</b>"+ length+"</p>");
}
if(sis.read() == '-' && sis.read()=='-')
{
break;
}
}
out.println("</html>");
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
There were few changes made in the code , the changes were given in the book.
here is my HTML code
<html>
<head>
<title>Test HTML Form</title>
</head>
<body>
<p>Select a file to upload or browse currently uploaded files.</p>
<form action="http://127.0.0.1/Project_One/FileUpload"
method="post" enctype="multipart/form-data">
File:<input type="file" name:"file"><br>
<input value="Upload File" type="submit">
</form>
</body>
</html>
I'm using TomCat sever for this.
Where did you get this code from? From a decade old servlet tutorial/book? This is all unnecessarily overcomplicated. Please make sure that you're reading an up to date tutorial/book which is no older than one year.
Here's how the file upload could be done with the standard servlet 3.0 API:
#MultipartConfig
#WebServlet("/FileUpload")
public class FileUpload extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
String filename = getFilename(filePart);
InputStream filecontent = filePart.getInputStream();
// ... (do your job here)
}
private static String getFilename(Part part) {
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
}
}
return null;
}
}
That's all. It also takes into account that the proper filename is returned. Some browsers such as MSIE namely incorrectly includes the full client side path along the filename. That might be the cause of your problem.
Further there are 2 other problems not directly related:
You should not store the uploaded file in the deploy folder. It will get lost whenever you redeploy the webapp. Store the file in a fixed path somewhere outside the deploy folder. See also for example How I save and retrieve an image on my server in a java webapp.
You should be delegating the job of generating HTML to JSP. In the end of doPost(), forward the request to a JSP:
request.getRequestDispatcher("/WEB-INF/uploadresult.jsp").forward(request, response);
See also:
Our Servlets wiki page - contains hello world examples how to use servlets properly
How to upload files to server using JSP/Servlet?
well i think this code is a bit complicated to read but there are a few points where the error could be, first of all this part :
out.println("<html>");
out.print("File upload success. <a href=\"/Project_One/files");
out.print("\">Click here to browse through all uploaded ");
out.println("files.</a><br>");
In this part your link points to Project_One/files but when you write your file :
FileOutputStream fos = new FileOutputStream(sc.getRealPath("/")+"/"+filename);
you write the file directly in the Project_One folder ( not in the files folder your html points ) , so you could try to see if the file was written in the main folder of your workspace.
Anyway i think you could understand better a code like this :
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
MultipartFile multipartFile = multipartRequest.getFile("file");
byte[] content =multipartFile.getBytes();
File archivoParaGuardar= new File("/your_directory/"+multipartFile.getOriginalFilename());
try {
baos.write(content);
FileOutputStream fos = new FileOutputStream(archivoParaGuardar);
baos.writeTo(fos);
fos.close();
} catch (Exception e) {
logger.error("Error saving file ", e);
}
Hope this helps you.

Categories