1

I have a jsp+servlet web application, which runs on tomcat server. All the strings which i use are hardcoded now. If possible I want to move all the hardcoded strings to one resource file and point to particular string in jsp code. How can i do it. Is there any other way other than resource file.For example: In below switch statement, i want to remove all hardcoded strings in case statement and move to one resource file or so and point to that string in my code.

switch (request.getParameter("mode")) {
                case "check1": {

                    break;
                }
                case "check2": {

                    break;
                }
                case "active_inactive": {

                    break;
                }
                default:
                    break;
            }
Vinod
  • 19
  • 7

1 Answers1

2

Use class named Constants for this pupose.

 public class Constants{

   public static String CHECK_1 = "Check1";
   public static String CHECK_2 = "Check2";


 }

And use this in anywhere you want.

      switch (request.getParameter("mode")) {
            case Constants.CHECK_1: {

                break;
            }
            case Constants.CHECK_2: {

                break;
            }
            default:
                break;
        }
Sandunka Mihiran
  • 556
  • 4
  • 19
  • Thats one way, but is there any way that i can copy all strings to an xml or any other resource file and point to it – Vinod Nov 12 '18 at 10:48
  • I'm sure that's possible. Though I do not know the exact reason for your requirement , I would not recommend such approach to store constants as it would cost you performance and management issues – Sandunka Mihiran Nov 12 '18 at 10:51
  • @Vinod You can only use constants or literals in a switch, so if you want to get those strings from a resource file, you'll need to switch to another solution (eg using a map). – Mark Rotteveel Nov 12 '18 at 16:54
  • @Mark Rotteveel That was just an example. I have strings which i want to move to resource file such as xml. This is my primary concern. – Vinod Nov 13 '18 at 05:44
  • @Vinod Then you shouldn't be asking about about your actual problem and not the switch construct, because there strings can't be externalized. – Mark Rotteveel Nov 13 '18 at 10:21