简体   繁体   中英

HttpServletRequest getting request

I need really help. I have a login.jsp page

<html>

<head></head>

<body>
  <form method="post" action="j_security_check">
    <table>
      <tr>
        <td>
          <input type="text" name="j_username" autofocus="autofocus" required="required" />
        </td>
      </tr>
      <tr>
        <td>
          <input type="password" name="j_password" required="required" />
        </td>
      </tr>
      <tr>
        <td>
          <input type="submit" value="Login" />
      </tr>
    </table>
  </form>
</body>

</html>

this is my web.xml

All Pages /*
MY_User

<security-role>
    <role-name>MY_User</role-name>
</security-role>

<login-config>
    <auth-method>FORM</auth-method>
     <realm-name>myRealm</realm-name>
    <form-login-config>
        <form-login-page>/login.jsp</form-login-page>
        <form-error-page>/error.jsp</form-error-page>
    </form-login-config>
</login-config>

In my filter I get the Principal. But somehow when I get into my main Class. The request is gone!

How can I pass my Request to another Java class?

1) As per your query in comments, you can convert Command.java to a servlet just by extending it with the HttpServlet class. Then you can have access to request and response objects in Command.java class.

2) other way to pass request and response objects to your Command.java class is as below:
Let's say you have a servlet MyServlet from where you want to call the methods of Command.java class

public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try{
        Command c =new Command();//object creation depends on your project. e.g you can create it using beans of spring
        c.doSomething(request, response);
    }catch(Exception e){
        e.printStackTrace();
    }
}
}

Then, your Command class methods should have below parameters:

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Command {

    public void doSomething(HttpServletRequest request,HttpServletResponse response) {
        System.out.println("doing something");
    }
}

Remember, Servlet request and response are just objects of a simple java class. They does not depend on any api like servlet, you can pass these objects to any java class and their properties will remain same, no matter its servlet or a java class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM