我使用Spring4,maven,jquery,tomcat开发了一个Web应用程序。 我使用java配置类而不是web.xml和spring applicationContext.xml。在控制器类中使用@RestController而不是@Controller来实现解耦应用程序。不想使用@Controller,因为在这种情况下我必须返回我不想要的视图名称和模型。
问题: - 我的web应用程序启动正常,dashboard.js从dashboard.jsp调用。 但是当我尝试调用DashboardController.java服务' / dashboard / 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() {}
}
配置类 package 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 :(得分:0)
自从我在这个论坛(约一个月前)发布以来,我一直在研究上述问题。最后,我能够解决这个问题。 以下是我错过的内容并纠正它以解决问题: -
1。 ManageBudgetConfiguration.java: 我错过了在ManageBudgetConfiguration类中扩展WebMvcConfigurerAdapter。
public class ManageBudgetConfiguration **extends WebMvcConfigurerAdapter**{ ... }
2. 覆盖ManageBudgetConfiguration.java类中的addResourceHandlers(...)方法
包括静态ui资源,如js,css等。我的javascript和css文件位于<basedir>/webapp/resources/
文件夹
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
上面的方法是application-contex mapping的等效代码: -
<mvc:resources mapping="/resources/**" location="/resources/theme-new/" />
3a。将Gson包含在pom中。 Gson是google lib,用于将Java Object转换为JSON,反之亦然。
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
3b 更改rest-endpoints方法的返回类型: -
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;
}