Hello All,

Can anybody plz guide me how to write a new method in servlet. I am using netbeans 6.8
A code snippet will be highly appreciated.
Also I will be calling these method of servlet B from servlet A. In Servlet A there are 2 hyper links, which should display appropriate contents.
I want to generate these contents through method.
Any suggestion will be highly appreciated.
Thank You,
Maya

Dani AI

Generated

You generally do not call methods on another servlet to share logic. Servlets are controllers; they should delegate work to plain Java classes. Put the reusable code in a small service/helper and have both Servlet A and Servlet B call that. If you merely want to aggregate output, dispatch the request to the other servlet (include/forward), but avoid coupling business logic to a servlet. Also, keep request-specific state local to methods; do not store a PrintWriter or request data in servlet fields, which can break under concurrency (a small tweak to what showed).

For your login case, move the credential check into a helper and submit the form with POST to a servlet. Example:

// AuthService.java
import java.util.*;
public final class AuthService {
  private final Map<String,String> users = new HashMap<>();
  public AuthService() { users.put("jojo","jojo1"); users.put("tim","tim1"); }
  public boolean authenticate(String u, String p) {
    String expected = users.get(u);
    return expected != null && expected.equals(p);
  }
}

// LoginServlet.java
import javax.servlet.*; import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*; import java.io.IOException;

@WebServlet("/login") // if your container lacks annotations, add a web.xml mapping instead
public class LoginServlet extends HttpServlet {
  private final AuthService auth = new AuthService();
  @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String u = req.getParameter("uname");
    String p = req.getParameter("pswrd");
    if (auth.authenticate(u, p)) {
      req.getSession().setAttribute("user", u);
      resp.sendRedirect("home.jsp");
    } else {
      req.setAttribute("error", "Invalid username or password");
      req.getRequestDispatcher("/login.jsp").forward(req, resp);
    }
  }
}

Tips:

  • is right: let the button submit to the servlet; put the if-logic in doPost, not JavaScript.
  • Never write to the response before a forward/redirect.
  • Replace hardcoded arrays with a database later; never store real passwords in plain text.
  • Use HTTPS and invalidate the session on logout.

Recommended Answers

All 5 Replies

Well i am not sure if we can directly call a user-defined method of one servlet from another servlet....but we can achieve this in this way....I have defined an user defined method in servletB and called it in doGet() lifecycle method of SerletB and from the ServletA's life cycle method i created a RequestDispatcher object and used the method rd.include(req,res)...and it worked fine.....Here's the code...

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class ServletA extends HttpServlet{

	public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException{
		PrintWriter pw=res.getWriter();
		pw.println(" This is service method of ServletA ");
		ServletContext ctx=getServletContext();
		RequestDispatcher rd=ctx.getRequestDispatcher("/tt");
		rd.include(req,res);
	}//end of doGet


}//endof servlet A
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class ServletB extends HttpServlet{
	PrintWriter pw;
	

	public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException{
		
		
		pw=res.getWriter();
		pw.println(" This is service method of servletB and i am being called by ServletA ");
		hello();
		
	}
	public void hello(){
		pw.println(" This is hello method of serveltB and i am being called in service method ");
	}
}//end of ServletB

web.xml file

<web-app>
  <servlet>
     <servlet-name>serva</servlet-name>
	 <servlet-class>ServletA</servlet-class>
  </servlet>
  <servlet-mapping>
     <servlet-name>serva</servlet-name>
	 <url-pattern>/ss</url-pattern>
  </servlet-mapping>

  <servlet>
     <servlet-name>servb</servlet-name>
	 <servlet-class>ServletB</servlet-class>
  </servlet>
  <servlet-mapping>
     <servlet-name>servb</servlet-name>
	 <url-pattern>/tt</url-pattern>
  </servlet-mapping>
</web-app>

Hope this is the solution to ur question....

Hye thanks buddy

:)

Actually I am trying to write a method which has two arrays and a if loop. I neet to ecxute the If loop condition on a button click, and I am writing this in servlet.
Can u plz help?

Hi you should take a little bit pain to tell me what type of arrays are you taking and what is the if condition doing there?.....If you post the question in a vague form no one will first understand ur question to help you...thanks...

Also what you want will not be in a separate method but you will submit the form "towards" the servlet when you click the button and execute the code inside the toGet method of the servlet

Also what you want will not be in a separate method but you will submit the form "towards" the servlet when you click the button and execute the code inside the toGet method of the servlet

hye thanks for the replies.
Ok I will be more elaborative.
I am writing a servlet for login, where I need to verify the user. To verify the user I need to submit some valid usernames and passwords in two arrays. And then if the entered usernames and passwors matches, the user will be taken to next step, else a validation message should be displayed.

This is the javascript which i designed. But now I want to write it in servlet.

<script type="text/javascript">

function hr(form)

{
var uname= new Array("jojo","tim");

var pswrd= new Array("jojo1","tim1");

if
(form.uname.value == uname[0] && form.password.value == pswrd[0] || form.uname.value == uname[1] && form.pswrd.value ==pswrd[1] )

{
window.location="http://google.com";
}

else

{
alert("Invalid Username or password!");
}


}


</script>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.