Home page

How can I get the html data inside a Java servlet?

Good day! How can I access the HTML text field value inside a servlet? My example code is as follows:

 out.println(" "); out.println(""); out.println("Item not found. "); out.println("

Add Item:

"); out.println("
"); out.println("Item Name:
"); out.println("Unit Price:
"); out.println("On Stock :

"); out.println(""); out.println("
"); out.println(""); out.println("");

I need to get the value of name, unit price and stock after the user presses the button so i can put it in an arraylist. Is it possible to assign it on the same servlet? I tried using this code:

but it is not working because the button must be pressed first. Can i use a getter and setter method or anything equivalent? I need a textfield for the data entry and it must be done inside a servlet. The result must also be generated inside the same servlet. Thank you.

5 Answers 5

I tried using this code: String > but it is not working because the button must be pressed first.

You do need to use the getParameter(. ) . But I suspect that you were trying to do this in the same doGet(. ) method created the form HTML . before you sent the response containing that HTML to the user.

What needs to happen is this:

  1. Create HTML and send to the writer.
  2. Return from doGet(. ) .
  3. Wait for user to click the submit button.
  4. Get a new call on the doGet(. ) method.
  5. Figure out that this is an AddandSearch request . e.g. by looking at the request URI
  6. Call getParameter(«name») to get the parameter.
Читайте также:  Прямоугольник из звездочек питон

Given that your servlet is (now) handling requests from different forms, the doGet method needs to dispatch to different parts of your code(e.g. different methods) to handle each form type.

(We’ve also mentioned here and elsewhere that embedding HTML in your code like that is not good engineering practice. It is better to use JSP + JSTL, or some other templating technology.

But if this is what your instructor told you to do for this exercise, go with the flow. He may have a good reason . like not having time in the course to cover JSP, JSTL and other «advanced» Java EE stuff. Curriculum congestion can be a serious issue.)

Источник

Java Servlet read web page

Java Servlet read web page tutorial shows how to read a web page in a Java web application using a Servlet.

Java Servlet

is a Java class which responds to a network request. Java servlets are used to build web applications. They run in servlet containers such as Tomcat or Jetty. Modern-day Java web development uses frameworks that are built on top of servlets, including Spring and Vaadin.

is a Java library that validates data. We use this library to validate correct URL values.

Java Servlet read web page example

In the following example, we read a web page with InputStream and display the HTML code of the page to the client. The name of the web page is sent from an input tag of an HTML form.

$ tree . ├── nb-configuration.xml ├── pom.xml └── src ├── main │ ├── java │ │ └── com │ │ └── zetcode │ │ ├── service │ │ │ └── WebPageReader.java │ │ └── web │ │ └── ReadWebpage.java │ └── webapp │ ├── index.html │ ├── META-INF │ │ └── context.xml │ └── WEB-INF └── test └── java

This is the project structure.

  javax.servlet javax.servlet-api 3.1.0 provided  commons-validator commons-validator 1.6   

We need these two Maven dependencies. The javax.servlet-api artifact is for servlets. The commons-validator dependency is used for data validation.

In the Tomcat context.xml file, we define the context path. It is the name of the web application.

package com.zetcode.web; import com.zetcode.service.WebPageReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(name = "ReadWebPage", urlPatterns = ) public class ReadWebpage extends HttpServlet < @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < response.setContentType("text/plain;charset=UTF-8"); String page = request.getParameter("webpage"); String content = new WebPageReader().setWebPageName(page).getWebPageContent(); ServletOutputStream os = response.getOutputStream(); os.write(content.getBytes(StandardCharsets.UTF_8)); >>

The ReadWebPage servlet reads the contents of the given web page and sends the text to the client.

response.setContentType("text/plain;charset=UTF-8");

The response is in plain text and the text encoding is UTF-8.

String page = request.getParameter("webpage");

We get the name of the web page from the request parameter with getParameter .

String content = new WebPageReader().setWebPageName(page).getWebPageContent();

WebPageReader is used to get the contents of the web page.

ServletOutputStream os = response.getOutputStream(); os.write(content.getBytes(StandardCharsets.UTF_8));

We send the data to the client through ServletOutputStream .

package com.zetcode.service; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import org.apache.commons.validator.routines.UrlValidator; public class WebPageReader < private String webpage; private String content; public WebPageReader setWebPageName(String name) < webpage = name; return this; >public String getWebPageContent() < try < boolean valid = validateUrl(webpage); if (!valid) < content = "Invalid URL; use http(s)://www.example.com format"; return content; >URL url = new URL(webpage); try (InputStream is = url.openStream(); BufferedReader br = new BufferedReader( new InputStreamReader(is, StandardCharsets.UTF_8))) < content = br.lines().collect( Collectors.joining(System.lineSeparator())); >> catch (IOException ex) < content = String.format("Cannot read webpage %s", ex); Logger.getLogger(WebPageReader.class.getName()).log(Level.SEVERE, null, ex); >return content; > private boolean validateUrl(String webpage) < UrlValidator urlValidator = new UrlValidator(); return urlValidator.isValid(webpage); >>

WebPageReader reads the contents of a web page.

private boolean validateUrl(String webpage)

Before we read the web page, we validate the URL with UrlValidator from Apache Commons Validator library.

URL url = new URL(webpage); try (InputStream is = url.openStream(); BufferedReader br = new BufferedReader( new InputStreamReader(is, StandardCharsets.UTF_8)))

A web page is read through InputStream . The data is loaded into a String . Alternatively, we could use the JSoup library.

     

Java read web page

The home page contains the form, which sends the web page to be read to the application. Note that the web page must be entered in the full http(s)://www.example.com format. Figure: Java read web page

In the screenshot we can see the contents of a simple web page.

In this tutorial, we have created a Java Servlet application, which reads the contents of a chosen web page and sends the HTML back to the client in plain text.

Источник

Generate an HTML Response in a Java Servlet

You normally forward the request to a JSP for display. JSP is a view technology which provides a template to write plain vanilla HTML/CSS/JS in and provides ability to interact with backend Java code/variables with help of taglibs and EL. You can control the page flow with taglibs like JSTL. You can set any backend data as an attribute in any of the request, session or application scope and use EL (the $<> things) in JSP to access/display them. You can put JSP files in /WEB-INF folder to prevent users from directly accessing them without invoking the preprocessing servlet.

@WebServlet("/hello") public class HelloWorldServlet extends HttpServlet < @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < String message = "Hello World"; request.setAttribute("message", message); // This will be available as $request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response); > > 

And /WEB-INF/hello.jsp look like:

     

Message: $

When opening http://localhost:8080/contextpath/hello this will show

This keeps the Java code free from HTML clutter and greatly improves maintainability. To learn and practice more with servlets, continue with below links.

Also browse the «Frequent» tab of all questions tagged [servlets] to find frequently asked questions.

Источник

How to return an html document from java servlet? [duplicate]

Sorry for being noob! EDIT: I already have the html in separate documents. So I need to either return the document, or read/parse it somehow, so I’m not just retyping all the html. EDIT: I have this in my web.xml

 Monkey com.self.edu.MonkeyServlet  Monkey /monkey  

1 Answer 1

You either print out the HTML from the Servlet itself (deprecated)

PrintWriter out = response.getWriter(); out.println(""); out.println("

My HTML Body

"); out.println("");

or, dispatch to an existing resource (servlet, jsp etc.) (called forwarding to a view) (preferred)

RequestDispatcher view = request.getRequestDispatcher("html/mypage.html"); view.forward(request, response); 

The existing resource that you need your current HTTP request to get forwarded to does not need to be special in any way i.e. it’s written just like any other Servlet or JSP; the container handles the forwarding part seamlessly.

Just make sure you provide the correct path to the resource. For example, for a servlet the RequestDispatcher would need the correct URL pattern (as specified in your web.xml)

RequestDispatcher view = request.getRequestDispatcher("/url/pattern/of/servlet"); 

Also, note that the a RequestDispatcher can be retrieved from both ServletRequest and ServletContext with the difference that the former can take a relative path as well.

Sample Code

public class BlotServlet extends HttpServlet < public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException < // we do not set content type, headers, cookies etc. // resp.setContentType("text/html"); // while redirecting as // it would most likely result in an IllegalStateException // "/" is relative to the context root (your web-app name) RequestDispatcher view = req.getRequestDispatcher("/path/to/file.html"); // don't add your web-app name to the path view.forward(req, resp); >> 

Источник

Оцените статью