We help IT Professionals succeed at work.

How to click a hyperlink to call a servlet instead of a jsp page?

techques
techques asked
on
Medium Priority
3,997 Views
Last Modified: 2013-11-24
Hi

I have the following jsp to list out rows of data from a table and each row of data has its id. When I click the "click me" link, it will pass a parameter to a jsp.

However, my code to process it is written in a servlet. How can I pass id directly to a servlet when I click the hyperlink?

The servlet code:
String in = request.getParameterValues("id");

<%  
String sql = "SELECT s.id as id, s.name as name FROM customer s";
ResultSet rs = s.executeQuery(sql);
%>
<% while (rs.next()) {%>
<tr><td>
<%=rs.getInt("id")%></td><td><%=rs.getString("name")%></td><td><a href="test.jsp?id=<%=rs.getInt("id")%>">click me</a></td></tr>
<%}%>
<%
rs.close();
s.close();
con.close();
%>

Open in new window

Comment
Watch Question

Commented:
Just call your servlet like in the web.xml declared

<a href="/myservlet?id=<%=rs.getInt("id")%>
 
web.xml
-------
  <servlet>
    <servlet-name>myservlet</servlet-name>
    <servlet-class>test.MyServlet</servlet-class>
  </servlet>
 
  <servlet-mapping>
    <servlet-name>myservlet</servlet-name>
    <url-pattern>/myservlet</url-pattern>
  </servlet-mapping>

Open in new window

Author

Commented:
I did add the servlet to web.xml

when I call it, throw error:The requested resource (/myservlet) is not available

Do I need to <%@page import="myservlet",myservlet.*;"%> in the head of the jsp page?
Commented:
No it has nothing to do with your JSP. Test it directly in your browser:

http://localhost:8080/mycontext/myservlet?id=123

Check your web.xml:
<servlet-class> hat to be full qualified: for example com.myCompany.servlets.MyServlet

Post a stacktrace.

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
The requested resource (/myservlet) is not available

it will come if your url pattern is different in web.xml

post the section of your web xml where you are specifying your servlet.
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.