某些功能的控制器映射在部署的Spring引导应用程序中不起作用

时间:2016-03-23 06:35:53

标签: java spring spring-boot

我已经在tomcat服务器的vm中部署了spring boot应用程序。当我加载页面时,我只看到静态部分,没有任何uri映射到控制器中的ajax函数似乎在这里工作。但同样在我的本地应用程序中工作正常。谁能请帮忙。我正在附上我的休息控制器类的代码。

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();
    }   
}

出于这一点,只有那些返回模型并查看woorks和所有其他映射到从angular js ajax调用调用的函数的函数都没有被调用,它在控制台中显示

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

同样适用于其他电话。因此,我的html页面中的数据没有正确填充。相同的应用程序在我的本地机器上工作正常。仅在此外部虚拟机中,它才显示此问题。

添加js文件的ajax调用代码。

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;
        });

    }

谢谢, Poorna。

2 个答案:

答案 0 :(得分:2)

在我看来,当您在Tomcat容器(VM内部)上进行部署时,您正在使用不同的上下文路径。如果使用mvn spring-boot:run在本地运行应用程序,或者在未设置server.contextPath属性的情况下启动JAR,则可能在嵌入式容器中的根上下文中运行它。

网址http://172.16.77.83:8083/getCurrentWeek在该根上下文上运行,而在Tomcat上,您可能需要转到http://172.16.77.83:8083/MyApplicationNam/getCurrentWeek

要解决这个问题,有一些解决方案:

<强> 1。在根上下文中部署应用程序:

  1. 在将WAR部署到Tomcat之前将WAR重命名为ROOT.war
  2. 更改server.xml
  3. 中的上下文路径

    查看此答案以获取更多相关信息:Deploying my application at the root in Tomcat

    <强> 2。使用相对URL(可能是最佳解决方案):

    通过使用相对URL,您将始终根据HTML页面进行相对工作。如果HTML页面位于同一个应用程序中,则上下文路径也将应用于HTML页面,因此相对于HTML页面,REST API应始终保持不变。

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

    有关此主题的详细信息,请查看以下答案:Absolute vs relative URLs

答案 1 :(得分:-1)

您的应用程序是一个RESTful服务部署在tomcat服务器上。并且您尝试在部署在不同服务器上的AngularJS中访问这些服务。

您必须添加CORS过滤(CROSS域原始访问权限),才能访问HTTP谓词以进行跨服务。(域到域访问) 在类路径中添加以下Bean,它可以正常工作。

@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() {}

}