Behrouz Takhti
Behrouz Takhti

Reputation: 158

How to use spring message source inside js file?

I have a function in js file(exp : validateMyfile.js) that get a string parameter, this String has a value in myFile.properties and I need this value. Now I want to get parameter value by spring message source.

How to use spring message source inside js file?

function validate(msg){
  -- so I  need msg value (value iside myFile.properties);

}

Upvotes: 0

Views: 1090

Answers (1)

amdg
amdg

Reputation: 2239

We normally read the message into a javascript variable in jsp file before passing it to a js function as follows

<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<script type="text/javascript">
    var successmsg = "<fmt:message key='message.key'/>";

    function validate(){
      alert(successmsg);
    }  
</script>

Sometimes, we also pass it as a message from the Controller for a ajax call.

@Controller
public class EmployeeController{

   @Value("${employee.add.success}")
   private String successMessage;
   @Value("${employee.add.failure}")
   private String failureMessage;

   @ResponseBody
   @RequestMapping("/addEmployee")
   public String addEmployee(...){
      ... 
      if(added){
        StatusObject status = new StatusObject();
        status.setCode(..);
        status.setMessage(successMessage);
      }else{
        StatusObject status = new StatusObject();
        status.setCode(..);
        status.setMessage(failureMessage);
      }
    //return status object
    }
}

And access it as follows

$.ajax({
        ...
        success: function(status){
          $("#result").text(status.message);
        }
});

Upvotes: 1

Related Questions