Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

from html to servlet

Tags:

java

servlets

i'm learning html and sevlets,i wrote small aplication but i'm not getting any output when i click submit button from from.html page: below is my code

<html>
<body>
<h1 align="center>Color Selection Page</h1>
<form method="POST" action="/SelectColor.do" >
Select Color Charecterstics<p>
Color:
<select name="color" size="1">
<option>light
<option>amber
<option>brown
<option>dark
</select>

<br><br>

<center>
<input type="submit" value="Submit">
</center>

</form>
</body>
</html>

web.xml file

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   version="2.5">

   <servlet>
    <servlet-name>ColorServlet</servlet-name>
    <servlet-class>com.example.web.ColorServlet</servlet-class>
    </servlet>

    <servlet-mapping>
    <servlet-name>ColorServlet</servlet-name>
    <url-pattern>/SelectColor.do</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
    <welcome-file>form.html</welcome-file>
    </welcome-file-list>

</web-app>

servlet

package com.example.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class ColorServlet extends HttpServlet {
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException{
        res.setContentType("text/html");
        try {
            PrintWriter out = res.getWriter();
            out.println("Beer Selection ADvice<br>");
            String c=req.getParameter("color");
            out.println("<br>Got beer color "+c);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
like image 587
ranjana Avatar asked Nov 19 '25 09:11

ranjana


1 Answers

I've tested your code and the problem comes from this line:

<h1 align="center>Color Selection Page</h1>

The align attribute is not closed, you need to add a double quote to close it.

<h1 align="center">Color Selection Page</h1>

This won't make your HTML valid - Eclipse still complains about "Invalid location of tag (center)" - but, at least, you'll be able to submit the form.

Actually, I'd recommend to write valid HTML or XHTML even if your code is working fine (note that you may have to use action="SelectColor.do" instead of action="/SelectColor.do" depending on the context path of your webapp but this is another story). Writing "bad" HTML will lead you to weird rendering issues and unexpected errors. You should learn to write HTML the right and good way.

like image 114
Pascal Thivent Avatar answered Nov 21 '25 23:11

Pascal Thivent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!