开发者

servlet code structure / pattern ideas ? writing response

开发者 https://www.devze.com 2023-03-11 07:22 出处:网络
I have a simple servlet at the moment. I need it to call a static jar method and return its response.

I have a simple servlet at the moment. I need it to call a static jar method and return its response.

1) Can someone recommend a suitable structure ie do I need to create factories and handler classes etc...

2) How should I encode the hash in the response ... Is the simply writing to output stream ok do something else ? Ie write to headers etc.. Another App will be reading the response.

3) Not sure about handling nulls etc..

package myproj.servlet;

//Std imports
//Serlet imports
import myproj.hash.HashGe开发者_如何学Gonerator;

public class MyServlet extends HttpServlet{

String hashcode;

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    String accountName = req.getParameter("accountName");

    try {
        hashcode = HashGenerator.hash(accountName);
        resp.setContentType("text/plain");
        PrintWriter out = resp.getWriter(); 
        //[EDIT] was returning accountName by accident
        out.print(hashcode );

    } catch (Exception e) {
        //Some logging code
    }

}


First and foremost, your hashcode is not thread-safe.

  1. After looking to your provided snippet. I don't think so. It is fairly simple thing.

  2. You are getting accountName as parameter, and then writing the same back. Is that you want? Or you mean respond the hashed version.

  3. You might like to validate accountName parameter, since it is the input provided by user.


When working with Servlets directly, it helps to create a BaseServlet class to inherit from, which provides convenience methods for:

  • parameter handling / validation
  • parsing path information
  • mapping Java exceptions to HTTP result codes
  • etc...

Usually you want to define a single handle(HttpRequest req, HttpResponse) method, called from doGet/doPost, so you can move all the generic error handling outside your implementing class. Depending on how complex your responses are, you may even want to do handle(PrintWriter out) so you don't have to fuss with the io stuff every time.

Having factories for the sake of having factories is a very Java thing to do, but I don't see how that would benefit you here.

2) depends entirely on what the contract between your apps is, and how complex you expect their interaction to become in the future.

3) you definitely want to validate your parameters and send back a 400 status code if you don't have valid input.

Adeel already pointed out the glaring issue with hashcode.

If you expect this to become more complex, Jersey is an excellent framework for implementing app-to-app remote services (even if they aren't, strictly speaking, RESTful).

0

精彩评论

暂无评论...
验证码 换一张
取 消