0

I've been trying to find the solution for my problem since a week but couldn't succeed. There may be more than 100 same questions of this type, but they not helping me at all. Pls if anyone can explain what exactly is URL mapping and how it is done?

I'm using tomcat 7 and eclipse java EE. my jsp file is running properly but when I click submit the error appears. I have tried almost everthing. pls let me know what mistake I'm making.

here's my jsp code:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="/calculator/calc">
<input type="text" name="n1"><br>
<input type="text" name="n2"><br>
<input type="submit">
</form>
</body>
</html>

Servlet code:

public class calc extends GenericServlet 
{
public void service(ServletRequest req,ServletResponse res) throws IOException
{
    res.setContentType("text/jsp");
    PrintWriter pw=res.getWriter();
    String s1=req.getParameter("n1");
    String s2=req.getParameter("n2");
    int a=Integer.parseInt(s1);
    int b=Integer.parseInt(s2);
    pw.println(a+b);
   }
}

And web.xml

<?xml version="1.0" encoding="UTF-8"?>

<display-name>calculator</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
 </welcome-file-list>
</web-app>
ManishPrajapati
  • 459
  • 1
  • 5
  • 16

2 Answers2

3

In web.xml you need to give the servlet a name, indicating which will be the class serving it:

<servlet>
    <servlet-name>mycalc</servlet-name>
    <servlet-class>yourpackage.calc</servlet-class>
</servlet>

And then the url mapping to the servlet...

<servlet-mapping>
    <servlet-name>mycalc</servlet-name>
    <url-pattern>/calculator/calc</url-pattern>
</servlet-mapping>

The url you put in the servlet-mapping is the one that you must put in the action of the post

ipinyol
  • 336
  • 2
  • 12
0

In the action of your form you specified the url as /calculator/calc so in your web.xml Ithe container dint find any mapping for the url or not even you are not using annotaion based mapping try something like this

<servlet>
    <servlet-name>s1</servlet-name>
    <servlet-class>packageName.servletName</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>s1</servlet-name>
    <url-pattern>/calculator/calc</url-pattern>
</servlet-mapping>

or

@WebServlet(name="calServlet", urlPatterns = { "/calculator/calc" })

above your class defination. But remember if you use this there is no need to specify the mapping in web.xml but you should have Servlet-3 and tomcat 7

SparkOn
  • 8,806
  • 4
  • 29
  • 34