Mayank Rajput
Mayank Rajput

Reputation: 21

Servlet is not redirecting to URL with parameter(s)

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>sendRedirect example</title>
</head>
<body>


<form action="MySearcher">
<input type="text" name="name">
<input type="submit" value="Google Search">
</form>

</body>
</html>

MySearcher.java

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MySearcher extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name=request.getParameter("name");
        response.sendRedirect("https://www.google.co.in/#q="+name);
    }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>GoogleSearcher</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>
  <servlet>
    <description></description>
    <display-name>MySearcher</display-name>
    <servlet-name>MySearcher</servlet-name>
    <servlet-class>MySearcher</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>MySearcher</servlet-name>
    <url-pattern>/MySearcher</url-pattern>
  </servlet-mapping>
</web-app>

I tried to make a program in eclipse using servlet where user will enter what he wants to search and he will be directed to the search results on google. the program ran on eclipse. but there was a bit problem. i was not directed to the search results page. it directed me to google homepage. can someone please tell me the reason for this problem,?? help will be appreciated. i am just a beginner trying to learn servlet and its my second program

Upvotes: 1

Views: 1923

Answers (1)

AsSiDe
AsSiDe

Reputation: 1846

You need to change this line:

response.sendRedirect("https://www.google.co.in/#q="+name);

to

response.sendRedirect("https://www.google.co.in/search?q="+name);

Here is a link to compiled Information by @BalusC

Servlets Examples

Upvotes: 5

Related Questions