Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Duplicate code  RSS feed

 
Ryan McClain
Ranch Hand
Posts: 153
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the following code:



The problem I have is: I am trying to avoid duplicate code. I thought of making my PrintWriter a class variable or instance variable but then I will hit the wall of thread-safety, so that idea is out.

Is there any thread-safe way I could just set the content type and make a print writer only once, regardless of doGet() or doPost()? I want both methods to implement that, so that the only line would have to be out.write("text") per method and that's it.

 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66141
141
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why? The text/html mime type is the default content type, so why set it at all?

Also, if you don't support POST, don't override doPost(). The base implementation will do the right thing (return a not allowed status), rather than the wrong thing that your servlet is doing (return a 200 status).
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66141
141
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
P.S If there's something that you actually need to do before each and every request (or a subset identifiable by url pattern), then a servlet filter is a good way to do that without code repetition, or polluting the servlet code.
 
Ryan McClain
Ranch Hand
Posts: 153
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah yes, the intercepting filter pattern. Thanks.
 
suraj august
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
write a private static method inside the servlet and call it or use an existing utility class.
so something like....
 
Tim Cooke
Marshal
Posts: 3838
221
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suraj, your code is not valid Java. You do not define a return type in the signature, and the "response" variable is not defined. Please take the time to make sure any code presented at least compiles, otherwise it might end up just confusing matters even further.

Edit: I also added code tags (see UseCodeTags), see how much easier it is to read now?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!