【发布时间】:2017-03-23 17:41:54
【问题描述】:
我使用 Spring4、maven、jquery、tomcat 开发了一个 web 应用程序。 我正在使用 java config 类而不是 web.xml 和 spring applicationContext.xml。在控制器类中使用 @RestController 而不是 @Controller 来解耦应用程序。不想使用@Controller,因为在这种情况下我必须返回我不想返回的视图名称和模型。
问题:- 我的 Web 应用程序启动良好,并且从 dashboard.jsp 调用了 dashboard.js。 但是当我尝试调用 DashboardController.java 服务 '/dashboard/getDashboardDetails' 时,它会给出 404 page not found 错误。 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>
【问题讨论】:
-
为什么你有 3 个 jquery 脚本?为什么要动态加载js文件而不是静态加载?为什么你的控制器被映射到dashboard/getDashboardDetails,并且不返回html,而是json,为什么还要请求dashboard/getDashboardDetails.htm?
-
@JB Nizet 3 jquery 脚本输入错误。更正了。
-
@JB Nizet 1. 3 jquery 脚本输入错误。纠正它。 2. 静态添加脚本会有所不同。我应该改变它吗? 3. DashboardController.java 路径是“/dashboard”,getDashBoardDetails() 方法的路径是“/getDashboardDetails”,我试图将此服务称为
/dashboard/getDashboardDetails.htm。此服务返回 json,它将动态填充 dashbard.jsp 上的字段。我在这里做错了什么吗? -
再次:您的控制器映射到
/dashboard//getDashboardDetails。您的请求已发送至/dashboard/getDashboardDetails.htm。你没看出区别吗?.htm后缀不应该在那里。而且它甚至没有意义,因为.htm通常用于引用返回 HTML 的资源。但是您的资源返回 JSON。删除该后缀。 -
你能解释一下 url 'dashboard//getDashboardDetails' 是如何用 // 形成的吗?
标签: spring-mvc web-applications spring-4 spring-restcontroller