0

I have deployed the spring boot application in a vm in tomcat server. When I load the page, I get to see only the static part, none of the uri mapping to the ajax functions in the controller seem to work here. But the same works fine in my local application. Can anyone please help. I am attching the code of my rest controller class below.

import org.springframework.data.rest.webmvc.RepositoryRestController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.abc.xyz.util.DLCUtils;
import java.util.Date;
import java.util.List;


@RestController

public class HomeController {

    @RequestMapping("/home")
    public ModelAndView home(Model model) {
        int lastWeekInMonth = 0;
        lastWeekInMonth = DLCUtils.getLastWeekInMonth(2, 2016);
        System.out.println("last week"+lastWeekInMonth);
        model.addAttribute("lastweek", lastWeekInMonth);
        ModelAndView mav = new ModelAndView("/index");
        return mav;
    }
    @RequestMapping("/review")
    public ModelAndView reviewHours(Model model) {
        ModelAndView mav = new ModelAndView("/review");
        return mav;
    }
    @RequestMapping("/manage")
    public ModelAndView manageHours(Model model) {

        ModelAndView mav = new ModelAndView("/manage");
        return mav;
    }
    @RequestMapping("/addnewemployee")
    public ModelAndView addnewemployee(Model model) {
        ModelAndView mav = new ModelAndView("/addemployee");
        return mav;

    }

    @RequestMapping("/populateWeek")
    @ResponseBody
    public Integer lastweekMethod() {
        int lastWeekInMonth = 0;
        lastWeekInMonth = DLCUtils.getLastWeekInMonth(2, 2016);
        System.out.println("last week in lastweek"+lastWeekInMonth);
        return lastWeekInMonth;
    }

    @RequestMapping("/getCurrentWeek")
    @ResponseBody
    public Integer getCurrentweek() {
        int weekOfMonth = 0;
        weekOfMonth = DLCUtils.getWeekOfTheMonth();
        //System.out.println("last week in lastweek"+lastWeekInMonth);
        return weekOfMonth;
    }

    @RequestMapping(value="/getCurrentMonth",method=RequestMethod.GET)
    @ResponseBody
    public int getCurrentMonth(@RequestParam("monthname") String month) {
        int monthnumber = 0;
        monthnumber = DLCUtils.getMonthNumber(month.toUpperCase());
        //System.out.println("last week in lastweek"+lastWeekInMonth);
        return monthnumber;
    }



    @RequestMapping(value="/getRangeOfDate",method=RequestMethod.GET)
    @ResponseBody
    public String getRangeOfDate(@RequestParam("week") int week,@RequestParam("month") int month,@RequestParam("year") int year) {
        System.out.println("week val"+week);
        List<Date> dateRange=null;
        StringBuilder submitList = new StringBuilder("");
        Date fd=null,ld=null;
        dateRange = DLCUtils.getAllDays(week, month, year);
        for (int i = 0; i < dateRange.size(); i++) {
            if (i == 0) {
                fd = dateRange.get(0);
            }
            if (i == dateRange.size() - 1) {
                ld = dateRange.get(i);
            }

        }
        String firstdate = null;
        String lastdate = null;
        int fdate = 0;
        int ldate = 0;
        firstdate = fd.toString();
        lastdate = ld.toString();
        String firstdate1 = firstdate.substring(8, 10);
        String lastdate1 = lastdate.substring(8, 10);
        fdate = Integer.parseInt(firstdate1);
        ldate = Integer.parseInt(lastdate1);
        String monthName=DLCUtils.getMonthName(month);
        submitList.append(monthName);submitList.append("+");submitList.append(fdate);submitList.append("+");submitList.append(ldate);submitList.append("+");submitList.append(DLCUtils.getCurrentYear());
        return submitList.toString();
    }
    @RequestMapping(value="/getLastDate",method=RequestMethod.GET)
    @ResponseBody
    public String getLastDate(@RequestParam("month") int month,@RequestParam("year") int year){

        return  (DLCUtils.getEndDateOfTheMonth(month, year).toString());

    }
    @RequestMapping(value="/getAlldaysInweek",method=RequestMethod.GET)
    @ResponseBody
    public String getListDatesInAWeek(@RequestParam("week") int week,@RequestParam("month") int month,@RequestParam("year") int year){

        List<Date> lstDates = null;
        lstDates = DLCUtils.getAllDays(week, month, year);
        String dayOfWeek=null;
        StringBuilder submitList = new StringBuilder("");
        String formattedDate = null;
        String pattern = "yyyy/MM/dd";
        for (Date date : lstDates) {
        formattedDate = DLCUtils.getDateInPattern(date, pattern);
        dayOfWeek=DLCUtils.getDayOfTheWeek(date);
        submitList.append(dayOfWeek);submitList.append(",");submitList.append(formattedDate);submitList.append("+");
        }
        return submitList.toString();
    }
    @RequestMapping(value="/populatedetails",method=RequestMethod.GET)
    @ResponseBody
    public String populatedetails(@RequestParam("name") String name,@RequestParam("Id") String id,@RequestParam("Email") String email){

        StringBuilder submitList = new StringBuilder("");
        String place="Bangalore";String joiningdate="2014-01-01";String enddate="9999-12-31";String rights="Employee";String status="Active";String dept="EBU";String manager="David";
        submitList.append("Name"+"+"+name+","+"GlobalId"+"+"+id+","+"Email"+"+"+email+","+"Location"+"+"+place+","+"Joining Date"+"+"+joiningdate+","+"Resignation Date"+"+"+enddate+","+"Rights"+"+"+rights+",");


        submitList.append("Status"+"+"+status+","+"Division"+"+"+dept+","+"Manager"+"+"+manager+","+"Projects"+"+");
        submitList.append("SPT"+".");submitList.append("SPM"+".");submitList.append("DLC"+".");submitList.append("TEST1"+".");submitList.append("TEST2"+".");submitList.append("TEST3"+".");
        return submitList.toString();
    }   
}

out of this, only those that returns model and view woorks and all other mappings to functions called from angular js ajax calls are not invoked, it shows in the console that

angular.js:8611 GET http://172.16.77.83:8083/getCurrentWeek 404 (Not Found)

Similarly for other calls as well. Because of which, the data in my html pages are not populated properly. The same application works fine in my local machine. Only in this external vm, it shows this problem.

Adding the ajax call code of the js file.

function getCurrentWeek(){
        console.log("in ajax");

        $http({
            method : "GET",
            url : "/getCurrentWeek"
        }).then(function mySucces(response) {
            $scope.currentWeek=response.data;
              var j=parseInt($scope.currentWeek)-1;


              $('table.ui-datepicker-calendar tr:eq('+$scope.currentWeek+')').css({"border":"3px solid #e1e1e1"});
              var weekVal=$('#weekvalues a')[j];
             weekVal.style.border="3px solid #50a8e5";
              weekVal.style.paddingRight="2px";
              weekVal.style.paddingLeft="2px";
              weekVal.style.paddingTop="1px";

        }, function myError(response) {
            //$scope.dateRange = response.statusText;
        });

    }

Thanks, Poorna.

Eli Johnes
  • 301
  • 3
  • 13

2 Answers2

2

It appears to me that you're using a different context path when you're deploying on the Tomcat container (inside the VM). If you ran the application locally using mvn spring-boot:run, or by launching the JAR without setting the server.contextPath property, you probably ran it on the root context within the embedded container.

The URL http://172.16.77.83:8083/getCurrentWeek operates on that root context, while on Tomcat you probably have to go to http://172.16.77.83:8083/MyApplicationNam/getCurrentWeek.

To solve this issue there are a few solutions:

1. Deploying the application on the root context:

  1. Rename the WAR to ROOT.war before deploying it on Tomcat
  2. Changing the context path in server.xml

Check this answer for more information about it: Deploying my application at the root in Tomcat


2. Using relative URLs (probably the best solution):

By using relative URLs you will always work relative based on your HTML page. If the HTML page is within the same application, the context path will also be applied to the HTML page, so relatively towards the HTML page REST API should always stay the same.

$http({
    method : "GET",
    url : "./getCurrentWeek"
})

For more information about this topic check these answers: Absolute vs relative URLs

Community
  • 1
  • 1
g00glen00b
  • 41,995
  • 13
  • 95
  • 133
-1

Your application which is a RESTful service is deployed on tomcat server. And your trying to access these services in AngularJS which is deployed on different server.

And you will have to add the CORS filtering(CROSS Domain origin access), to give access to the HTTP verbs for cross services.(Domain to Domain access) Add the following Bean in your class path, it will work fine.

@Component
public class CORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}
Hareesh
  • 694
  • 6
  • 18
  • Why do you think the OP, Poorna, is running the AngularJS code on a different server? Considering that she has issues to show her views (= HTML) and her REST API in the same controller, I would rather consider that both are running on the same application. Also, even if it was a CORS issue, in Spring it's a lot easier using the `@CrossOrigin` annotation: http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/cors.html – g00glen00b Mar 23 '16 at 12:23
  • @g00glen00b Why should n't I consider it? I just considered that both are on different server, with that approach I suggested my answer. But your consideration was correct and gave good answer I accept it, that doesnt mean that you discourage other answer. – Hareesh Mar 24 '16 at 05:20
  • because she has multiple `ModelAndView`'s on her controller, which means she is serving HTML's as well on her application. And even if the answer was correct, then it would have been a lot easier to use `@CrossOrigin`, rather than adding a CORS filter like in regular Java applications. – g00glen00b Mar 24 '16 at 06:39