如何跨源资源共享与集成Spring MVC的4.0.0 RESTful Web服务资源共享、Spring、MVC、Web

2023-09-13 04:19:37 作者:怀念或痛

我有一个简单的Web服务返回的 JSON 数据。

的用户级( com.bargadss.SpringService.Domain )是在 POJO 类含

  

USER_ID,名字,姓氏,电子邮件

在 UserService类( com.bargadss.SpringService.DAO )两大操作

     getAllUser() - >查询DB来的选择的用户,从表中的所有用户和返回列表{}用户   getUserById(INT USER_ID) - >查询DB来的选择的基于ID的特定用户  

在 SpringServiceController ( com.bargadss.SpringService.Controller )如下:

 包com.bargadss.SpringService.Controller;进口的java.util.List;进口org.springframework.web.bind.annotation.PathVariable;进口org.springframework.web.bind.annotation.RequestMapping;进口org.springframework.web.bind.annotation.RequestMethod;进口org.springframework.web.bind.annotation.RestController;进口com.bargadss.SpringService.DAO.UserService;进口com.bargadss.SpringService.Domain.User;@RestController@RequestMapping(/服务/用户/)公共类SpringServiceController { UserService userService =新UserService(); @RequestMapping(值=/(编号),方法= RequestMethod.GET,标题=接受=应用程序/ JSON) 公共用户的getUser(@PathVariable INT ID){  用户的用户= userService.getUserById(ID);  返回用户; } @RequestMapping(方法= RequestMethod.GET,标题=接受=应用程序/ JSON) 公开名单<使用者> getAllUsers(){  清单<使用者>用户= userService.getAllUsers();  回报用户; }} 

在 ListUserController ( com.bargadss.SpringService.Controller )如下:

 包com.bargadss.SpringService.Controller;进口java.util.LinkedHashMap中;进口的java.util.List;进口org.springframework.stereotype.Controller;进口org.springframework.web.bind.annotation.PathVariable;进口org.springframework.web.bind.annotation.RequestMapping;进口org.springframework.web.client.RestTemplate;进口org.springframework.web.servlet.ModelAndView;进口com.bargadss.SpringService.Domain.User;@Controller公共类ListUserController {@RequestMapping(/ listUsers)公众的ModelAndView listUsers(){    RestTemplate restTemplate =新RestTemplate();    字符串URL =HTTP://本地主机:8080 / SpringServiceWithRESTAndJSONExample /服务/用户/;    清单<&LinkedHashMap的GT;用户= restTemplate.getForObject(URL,List.class);    返回新的ModelAndView(listUsers,用户,用户);}@RequestMapping(/ dispUser / {用户ID})公众的ModelAndView dispUser(@PathVariable(用户id)INT用户id){    RestTemplate restTemplate =新RestTemplate();    字符串URL =HTTP://本地主机:8080 / SpringServiceWithRESTAndJSONExample /服务/用户/用户ID {}​​;    用户的用户= restTemplate.getForObject(URL,User.class,用户ID);    返回新的ModelAndView(dispUser,用户,用户); }} 
tianchao87的个人空间 开源中国

在 CorsFilter ( com.bargadss.CORS )如下:

 包com.bargadss.CORS;进口java.io.IOException异常;进口javax.servlet.FilterChain;进口javax.servlet.ServletException;进口javax.servlet.http.HttpServletRequest;进口javax.servlet.http.HttpServletResponse;进口org.springframework.web.filter.OncePerRequestFilter;公共类CorsFilter扩展OncePerRequestFilter {@覆盖保护无效doFilterInternal(HttpServletRequest的请求,HttpServletResponse的响应,FilterChain filterChain)        抛出了ServletException,IOException异常{    如果(request.getHeader(访问控制请求法)= NULL和放大器;!&安培;选项.equals(request.getMethod())){        // CORSpre-飞行的要求        response.addHeader(访问控制允许原产地,*);        response.addHeader(访问控制允许的方法,GET,POST,PUT,DELETE);        response.addHeader(访问控制允许报头,内容类型);        response.addHeader(访问控制-max-age的,1800); // 30分钟    }    filterChain.doFilter(请求响应);}} 

在的web.xml 如下:

 <?XML版本=1.0编码=UTF-8&GT?;< web应用程序的xmlns:XSI =htt​​p://www.w3.org/2001/XMLSchema-instance     的xmlns =htt​​p://java.sun.com/xml/ns/javaee     的xmlns:网络=htt​​p://java.sun.com/xml/ns/javaee/web-app_2_5.xsd     XSI:的schemaLocation =htt​​p://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd     ID =WebApp_ID版本=3.0><显示-名称>&SpringServiceWithRESTAndJSONExample LT; /显示-名称><&servlet的GT;   < servlet的名称>&休息LT; / servlet的名称>  <的servlet类>         org.springframework.web.servlet.DispatcherServlet  < / servlet的类>  &所述;负载上启动→1&下; /负载上启动>< / servlet的><&servlet的GT;  < servlet的名称>&JSP LT; / servlet的名称>  <的servlet类> org.apache.jasper.servlet.JspServlet< / servlet的类>< / servlet的>< Servlet映射>  < servlet的名称>&休息LT; / servlet的名称>  < URL模式> / *< / URL模式>< / Servlet映射>< Servlet映射> < servlet的名称>&JSP LT; / servlet的名称> < URL模式> / WEB-INF / JSP / *< / URL模式>< / Servlet映射>&所述;滤光器>  <过滤器名称>&CORS LT; /过滤器名称>  <过滤器类和GT; com.bargadss.CORS.CorsFilter< /过滤器类>< /滤光器><过滤器映射>  <过滤器名称>&CORS LT; /过滤器名称>  < URL模式> / *< / URL模式>< /过滤器映射>< / web-app的> 

在被AngularJS从另一个Web服务器调用的Web服务返回错误指的是跨源资源共享的问题!

什么样的​​变化必须在控制器端进行,以消除错误?

有没有在AngularJS侧做任何必要的修改,以避免这种情况?

解决方案

检查 cors-过滤器

下载 CORS过滤-2.1.2.jar Java的性能-utils的-1.9.1.jar

MVN依赖

 <&依赖性GT;    <&的groupId GT; com.thetransactioncompany< /的groupId>    <&的artifactId GT; CORS-滤波器LT; / artifactId的>    <&版GT; 2.1.2< /版本>< /依赖性><&依赖性GT;  <&的groupId GT; com.thetransactioncompany< /的groupId>  <&的artifactId GT; Java的性能-utils的< / artifactId的>  <&版GT; 1.9.1< /版本>< /依赖性> 

的web.xml

 <滤光器>    <过滤器名称>&CORS LT; /过滤器名称>    <过滤器类和GT; com.thetransactioncompany.cors.CORSFilter< /过滤器类>< /滤光器> <过滤器映射>        <过滤器名称>&CORS LT; /过滤器名称>    < URL模式> / *< / URL模式> < /过滤器映射> 

I have a Simple Web Service returning JSON data.

The User Class (com.bargadss.SpringService.Domain) is The POJO class containing

user_ID, firstName, lastName, eMail

The UserService class (com.bargadss.SpringService.DAO) two major operation

getAllUser() -> Queries the DB to Select all Users from User Table and returns List{User} getUserById(int user_ID) -> Queries the DB to Select a specific user based on ID

The SpringServiceController (com.bargadss.SpringService.Controller) is as follows :

package com.bargadss.SpringService.Controller;

import java.util.List;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.bargadss.SpringService.DAO.UserService;
import com.bargadss.SpringService.Domain.User;


@RestController
@RequestMapping("/service/user/")
public class SpringServiceController {
 UserService userService=new UserService();

 @RequestMapping(value = "/{id}", method = RequestMethod.GET,headers="Accept=application/json")
 public User getUser(@PathVariable int id) {        
  User user=userService.getUserById(id);
  return user;
 }

 @RequestMapping(method = RequestMethod.GET,headers="Accept=application/json")
 public List<User> getAllUsers() {   
  List<User> users=userService.getAllUsers();
  return users;
 }
}

The ListUserController (com.bargadss.SpringService.Controller) is as follows :

package com.bargadss.SpringService.Controller;

import java.util.LinkedHashMap;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import com.bargadss.SpringService.Domain.User;


@Controller
public class ListUserController {

@RequestMapping("/listUsers")
public ModelAndView listUsers() { 
    RestTemplate restTemplate = new RestTemplate();
    String url="http://localhost:8080/SpringServiceWithRESTAndJSONExample/service/user/";    
    List<LinkedHashMap> users=restTemplate.getForObject(url, List.class);
    return new ModelAndView("listUsers", "users", users);
}

@RequestMapping("/dispUser/{userid}")
public ModelAndView dispUser(@PathVariable("userid") int userid) { 
    RestTemplate restTemplate = new RestTemplate();
    String url="http://localhost:8080/SpringServiceWithRESTAndJSONExample/service/user/{userid}";
    User user=restTemplate.getForObject(url, User.class,userid);
    return new ModelAndView("dispUser", "user", user);
 }

}

The CorsFilter (com.bargadss.CORS) is as follows :

package com.bargadss.CORS;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;


public class CorsFilter extends OncePerRequestFilter{

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {
    if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
        // CORS "pre-flight" request
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type");
        response.addHeader("Access-Control-Max-Age", "1800");//30 min
    }
    filterChain.doFilter(request, response);
}

}

The web.xml is as follows :

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns="http://java.sun.com/xml/ns/javaee" 
     xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
     id="WebApp_ID" version="3.0">
<display-name>SpringServiceWithRESTAndJSONExample</display-name>

<servlet>
   <servlet-name>rest</servlet-name>
  <servlet-class>
         org.springframework.web.servlet.DispatcherServlet
  </servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet>
  <servlet-name>jsp</servlet-name>
  <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>rest</servlet-name>
  <url-pattern>/*</url-pattern>
</servlet-mapping>

<servlet-mapping>
 <servlet-name>jsp</servlet-name>
 <url-pattern>/WEB-INF/jsp/*</url-pattern>
</servlet-mapping>

<filter>
  <filter-name>cors</filter-name>
  <filter-class>com.bargadss.CORS.CorsFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>cors</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

</web-app>

The Web Service when being invoked by AngularJS from another Web Server returns Error referring to Cross Origin Resource Sharing problem !!!

What Changes must be performed in the Controller side to eliminate the error ?

Is there any changes necessary to be done at the AngularJS side to avoid this situation ?

解决方案

Check the cors-filter

Download cors-filter-2.1.2.jar and java-property-utils-1.9.1.jar.

mvn dependency

<dependency>
    <groupId>com.thetransactioncompany</groupId>
    <artifactId>cors-filter</artifactId>
    <version>2.1.2</version>
</dependency>
<dependency>
  <groupId>com.thetransactioncompany</groupId>
  <artifactId>java-property-utils</artifactId>
  <version>1.9.1</version>
</dependency>

and in web.xml

<filter>
    <filter-name>CORS</filter-name>
    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
</filter>
 <filter-mapping>
        <filter-name>CORS</filter-name>
    <url-pattern>/*</url-pattern>
 </filter-mapping>

 
精彩推荐