0

我已經開發了一個使用Spring4,maven,jquery,tomcat的web應用程序。 我正在使用java配置類而不是web.xml和spring applicationContext.xml。在解耦應用程序的控制器類中使用@RestController而不是@Controller。不想在這種情況下使用@Controller,我必須返回我不想要的視圖名稱和模型。Spring 4 restController服務沒有從web應用程序中的jsp調用

問題: - 我的web應用程序開始正常,dashboard.js從dashboard.jsp中調用。 但是,當我嘗試調用DashboardController.java服務'/儀表板/ getDashboardDetails'它給404頁面未找到錯誤。 在eclipse或tomcat控制檯中沒有錯誤。

過濾級別: -

package com.me.configuration; 

import java.io.IOException; 
import javax.servlet.Filter; 
import javax.servlet.FilterChain; 
import javax.servlet.FilterConfig; 
import javax.servlet.ServletException; 
import javax.servlet.ServletRequest; 
import javax.servlet.ServletResponse; 
import javax.servlet.http.HttpServletResponse; 

public class CORSFilter implements Filter { 

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { 
    System.out.println("Filtering on..........................................................."); 
    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", "x-requested-with"); 
    chain.doFilter(req, res); 
} 

public void init(FilterConfig filterConfig) {} 

public void destroy() {} 

} 

配置類 包com.me.configuration;

import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.ComponentScan; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.web.servlet.ViewResolver; 
import org.springframework.web.servlet.config.annotation.EnableWebMvc; 
import org.springframework.web.servlet.view.InternalResourceViewResolver; 
import org.springframework.web.servlet.view.JstlView; 

@Configuration 
@EnableWebMvc 
@ComponentScan(basePackages = "com.me") 
public class ManageBudgetConfiguration { 

@Bean 
public ViewResolver viewResolver() { 
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); 
    viewResolver.setViewClass(JstlView.class); 
    viewResolver.setPrefix("/pages/"); 
    viewResolver.setSuffix(".jsp"); 

    return viewResolver; 
} 

} 

初始化器類

package com.me.configuration; 

import javax.servlet.Filter; 

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; 

public class ManageBudgetInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { 


@Override 
protected Class<?>[] getRootConfigClasses() { 
    return new Class[] { ManageBudgetConfiguration.class }; 
} 

@Override 
protected Class<?>[] getServletConfigClasses() { 
    return null; 
} 

@Override 
protected String[] getServletMappings() { 
    return new String[] { "/" }; 
} 

@Override 
protected Filter[] getServletFilters() { 
    Filter [] singleton = { new CORSFilter()}; 
    return singleton; 
} 

} 

控制器類

package com.me.controller; 

import java.util.List; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.http.HttpHeaders; 
import org.springframework.http.HttpStatus; 
import org.springframework.http.MediaType; 
import org.springframework.http.ResponseEntity; 
import org.springframework.web.bind.annotation.PathVariable; 
import org.springframework.web.bind.annotation.RequestBody; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.RestController; 
import org.springframework.web.util.UriComponentsBuilder; 

import com.me.model.DashboardBean; 
import com.me.model.User; 
import com.me.service.DashboardServiceInf; 
import com.me.service.UserService; 


@RestController 
@RequestMapping("/dashboard") 
public class DashboardController { 


@Autowired 
UserService userService; //Service which will do all data retrieval/manipulation work 

@Autowired 
DashboardServiceInf dashboardService; 


/** 
* This service returns Dashboard data details 
* @return String 
*/ 
@RequestMapping(value = "/getDashboardDetails", method = RequestMethod.GET) 
public ResponseEntity<List<DashboardBean>> getDashBoardDetails() { 
    System.out.println("Dashboardcontroller : getDashBoardDetails"); 
    String userId ="rahil"; 
    List<DashboardBean> dashboardBeanList = dashboardService.getDashBoardDetails(userId); 
    if(dashboardBeanList.isEmpty()){ 
     return new ResponseEntity<List<DashboardBean>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND 
    } 

    return new ResponseEntity<List<DashboardBean>>(dashboardBeanList, HttpStatus.OK); 
} 

} 

dashboard.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta charset="utf-8"> 
<meta http-equiv="X-UA-Compatible" content="IE=edge"> 
<meta name="viewport" content="width=device-width, initial-scale=1"> 
<meta name="description" content=""> 
<meta name="author" content=""> 

<title>Manage Expense</title> 

<!-- jQuery --> 
<script type ="text/javascript" src="./resources/javascript/vendor/jquery/jquery.min.js"></script> 

<!-- Dashboard Charts --> 
<script src="resources/javascript/js/dashboardCharts.js"></script> 

</head> 
<body> 

<script type ="text/javascript"> 

$(document).ready(function() { 
    console.log("\tdashboard.jsp"); 

    $.ajax({ 
     url : "resources/javascript/system/dashboard.js", 
     dataType : "script", 
     cache : true   
    }).done(function(){ 
     console.log("inside done...."); 
     me.dashboard.onload(); 
    }); 

}); 


</script> 

</body> 
</html> 

dashboard.js

me = new Object(); 

if (typeof me.dashboard == 'undefined') { 
me.dashboard = function() { 
    return { 

     msgArray:[], // variable for checking same message 

     /** 
     * @author rahikhan 
     * @description Function to be called once the dashboard loaded. 
     */ 
     onload : function(){ 
      console.log("dashboard.js : onload..called without error"); 
      me.dashboard.getDashboardDetails(); 
     }, 

     getDashboardDetails : function(){ 
      console.log("dashboard.js : getDashboardDetails..."); 
      var promise = $.ajax({ 
       async: true, 
       url: "dashboard/getDashboardDetails.htm", 
       type: "GET", 
       datatype: "json", 
       accept: "application/json", 
      }).done(function(result) { 
       result = JSON.parse(result); 
       console.log("\tresult : " + result); 
      }).fail(function(jqXHR, textStatus) { 
       console.log("\tgetDashboardDetails : Application Exception Occured "); 
      }); 
      return promise; 
     }, 

    } 
}(); 

}

的pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 
    <modelVersion>4.0.0</modelVersion> 
    <groupId>com.me</groupId> 
    <artifactId>manageBudget</artifactId> 
    <packaging>war</packaging> 
    <version>0.0.1-SNAPSHOT</version> 
    <name>manageBudget</name> 
    <url>http://maven.apache.org</url> 

    <properties> 
     <springframework.version>4.2.0.RELEASE</springframework.version> 
     <jackson.version>2.5.3</jackson.version> 
    </properties> 

    <dependencies> 
     <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-webmvc</artifactId> 
      <version>${springframework.version}</version> 
     </dependency> 
     <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-tx</artifactId> 
      <version>${springframework.version}</version> 
     </dependency> 

     <dependency> 
      <groupId>com.fasterxml.jackson.core</groupId> 
      <artifactId>jackson-databind</artifactId> 
      <version>${jackson.version}</version> 
     </dependency> 

    <!-- System Related dependencies --> 
     <dependency> 
      <groupId>javax.servlet</groupId> 
      <artifactId>javax.servlet-api</artifactId> 
      <version>3.1.0</version> 
     </dependency> 
    <dependency> 
     <groupId>javax.servlet.jsp</groupId> 
     <artifactId>javax.servlet.jsp-api</artifactId> 
     <version>2.3.1</version> 
    </dependency> 
    <dependency> 
     <groupId>javax.servlet</groupId> 
     <artifactId>jstl</artifactId> 
     <version>1.2</version> 
    </dependency> 

    </dependencies> 

    <build> 
     <pluginManagement> 
      <plugins> 
       <plugin> 
        <groupId>org.apache.maven.plugins</groupId> 
        <artifactId>maven-compiler-plugin</artifactId> 
        <version>3.2</version> 
        <configuration> 
         <source>1.8</source> 
         <target>1.8</target> 
        </configuration> 
       </plugin> 

       <plugin> 
        <groupId>org.apache.maven.plugins</groupId> 
        <artifactId>maven-war-plugin</artifactId> 
        <version>2.4</version> 
        <configuration> 
         <warSourceDirectory>${basedir}/src/main/webapp</warSourceDirectory> 
         <warName>manageBudgetWar</warName> 
         <failOnMissingWebXml>false</failOnMissingWebXml> 
        </configuration> 
       </plugin> 

      </plugins> 
     </pluginManagement> 
     <finalName>manageBudget</finalName> 
    </build> 

</project> 
+0

爲什麼你有3個腳本的jQuery?爲什麼動態加載你的js文件而不是靜態加載?儘管控制器已映射到儀表板/ getDashboardDetails,並且不返回HTML,但爲什麼請求儀表板/ getDashboardDetails.htm? –

+0

@JB Nizet 3 jQuery腳本輸入錯誤。糾正它。 –

+0

@JB Nizet 1. 3 jquery腳本輸入錯誤。糾正它。 2.靜態添加腳本將會有所作爲。我應該改變它嗎? 3.DashboardController.java路徑爲「/ dashboard」,getDashBoardDetails()方法的路徑爲「/ getDashboardDetails」,我試圖將此服務稱爲 /dashboard/getDashboardDetails.htm。該服務返回json,它將動態地填充dashbard.jsp上的字段。有什麼我在這裏做錯了嗎? –

回答

0

我一直對上述問題,因爲我張貼在這個論壇上(約一個月前)。最後,我能夠解決這個問題。 以下是我錯過了intially和糾正它來解決這個問題: -

ManageBudgetConfiguration.java: 我錯過了在ManageBudgetConfiguration類擴展WebMvcConfigurerAdapter。在ManageBudgetConfiguration.java 類

public class ManageBudgetConfiguration **extends WebMvcConfigurerAdapter**{ ... } 

2.覆蓋addResourceHandlers(...)方法,包括靜態的用戶界面資源,如JS,CSS等我的JavaScript和CSS文件在<basedir>/webapp/resources/文件夾

@Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) { 
     registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); 
    } 

上述方法是用於應用程序CONTEX映射的等效代碼: -

<mvc:resources mapping="/resources/**" location="/resources/theme-new/" /> 

3a。包括gson在pom中。 Gson是谷歌庫將Java對象轉換爲JSON,反之亦然。

<dependency> 
     <groupId>com.google.code.gson</groupId> 
     <artifactId>gson</artifactId> 
     <version>2.8.0</version> 
    </dependency> 

3B更改返回類型的其餘部分的端點方法: -

return new ResponseEntity<List<DashboardBean>>(dashboardBeanList, HttpStatus.OK) 
    to 
return response; 
where response is json string 
eg 


@RequestMapping(value = "/getDashboardDetails", method = RequestMethod.GET) 
    public @ResponseBody 
    String getDashBoardDetails(HttpServletRequest request) { 
     System.out.println("Dashboardcontroller : getDashBoardDetails1"); 
     String response = null; 
     String userId ="rahil"; 

     List<DashboardBean> dashboardBeanList = dashboardService.getDashBoardDetails(userId); 
     response = new Gson().toJson(dashboardBeanList); 
     return response; 
    } 
相關問題