Spring Rest + Spring安全示例
以下是使用Spring安全性创建简单的Spring Restful Web服务的步骤,这将返回JSON。
1)使用Maven在Eclipse中创建动态Web项目。
2)我们需要在类路径中添加Spring Securit Y和Hymanson Json实用程序。
<dependency>
<groupId>com.fasterxml.Hymanson.core</groupId>
<artifactId>Hymanson-databind</artifactId>
<version>2.4.1</version>
</dependency>
Spring将Hymanson2jsonmessageConverter自动加载到其应用程序上下文中。
每当我们使用Accep Headers ="Accept = Application/JSON"时请求资源作为JSON,那么Hymanson2jsonMessageConverter就会进入图片并将资源转换为JSON格式。
现在更改pom.xml如下: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.igi.theitroad</groupId>
<artifactId>SpringRestSpringSecurityExample</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringRestSpringSecurityExample Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.Hymanson.core</groupId>
<artifactId>Hymanson-databind</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${security.version}</version>
</dependency>
</dependencies>
<build>
<finalName>SpringRestSpringSecurityExample</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<spring.version>4.2.1.RELEASE</spring.version>
<security.version>4.0.3.RELEASE</security.version>
<jdk.version>1.7</jdk.version>
</properties>
</project>
3)更改Web.xml如下:
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>springrest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springrest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
4)在/Web-Inf /文件夹中创建名为springrest-servlet.xml的XML文件。
请更改上下文:组件扫描如果要使用不同的套装来搜索控制器。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven
<context:component-scan base-package="org.igi.theitroad.controller"
</beans>
配置Spring Security:
在Web-Inf文件夹中创建名为spring-security.xml的文件:
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.0.xsd">
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/resources/**" access="permitAll"
<intercept-url pattern="/count*" access="hasRole('ROLE_ADMIN')"
<logout logout-success-url="/" logout-url="/j_spring_security_logout"
<csrf disabled="true"
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="theitroad" password="java123" authorities="ROLE_ADMIN"
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
我们可以更好地阅读更多有关Spring Security以了解上面的配置。
当用户将尝试访问国家或者国家/地区/{id} URL时,他将获得登录表单,他需要放置正确的凭据(用户名:onIrad和password = java123)来访问Spring REST API。
创建bean类
5)在org.igi.theitroad.Bean中创建bean名称"country.java"。
package org.igi.theitroad.bean;
public class Country{
int id;
String countryName;
public Country(int i, String countryName) {
super();
this.id = i;
this.countryName = countryName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
}
创建控制器
6)创建名为"countrycontroller.java"的控制器
package org.igi.theitroad.controller;
import java.util.ArrayList;
import java.util.List;
import org.igi.theitroad.bean.Country;
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;
@RestController
public class CountryController {
@RequestMapping(value = "/countries", method = RequestMethod.GET,headers="Accept=application/json")
public List getCountries()
{
List listOfCountries = new ArrayList();
listOfCountries=createCountryList();
return listOfCountries;
}
@RequestMapping(value = "/country/{id}", method = RequestMethod.GET,headers="Accept=application/json")
public Country getCountryById(@PathVariable int id)
{
List listOfCountries = new ArrayList();
listOfCountries=createCountryList();
for (Country country: listOfCountries) {
if(country.getId()==id)
return country;
}
return null;
}
//Utiliy method to create country list.
public List createCountryList()
{
Country NetherlandsCountry=new Country(1, "Netherlands");
Country chinaCountry=new Country(4, "China");
Country nepalCountry=new Country(3, "Nepal");
Country bhutanCountry=new Country(2, "Bhutan");
List<Country> listOfCountries = new ArrayList<gt;();
listOfCountries.add(NetherlandsCountry);
listOfCountries.add(chinaCountry);
listOfCountries.add(nepalCountry);
listOfCountries.add(bhutanCountry);
return listOfCountries;
}
}
@PathVariable:用于将来自URL的值注入方法参数。
我们在getCountrybyID方法中注入的方式。
我们没有提供任何View Information inspringrest-servlet.xml,因为我们在Spring MVC中做到了。
如果我们需要直接从控制器获取资源,我们需要根据Spring 3返回@ResponseBody,但使用Spring 4,我们可以使用@RestController。
在Spring 4.0中,我们可以使用@Controller + @ResponseBody的组合@RestController。
@RestController = @Controller + @ResponseBody
6)这是时候建立了Maven的时间。
右键单击项目 - >运行AS - > Maven Build
7)将目标作为清洁安装(下面给出),然后单击运行
运行应用程序
8)右键单击"项目 - >在服务器上运行"
选择Apache Tomcat,然后单击"完成"
运行应用程序时,我们可能会得到这种警告
Mar 26, 2015 1:45:51 AM org.springframework.web.servlet.PageNotFound noHandlerFound WARNING: No mapping found for HTTP request with URI [/SpringRestfulWebServicesWithJSONExample/] in DispatcherServlet with name 'SpringRestfulWebServicesWithJSONExample'
请忽略上面的警告。
如果启动应用程序,如果我们未提供开始,则在URL下面有以下位置:http://localhost:8080/springrestspringsecurityexample /
当我们在Web.xml中使用DispatcherServlet时,此请求进入Spring DispatcherServlet,它没有找到控制器中的相应映射,因此我们可以获得该警告。
9)测试REST服务下:"http://localhost:8080/springrestspringsecurityexample/countrates"。
当我们尝试访问上面的URL时,我们将获得登录页面如下所示
如果我们输入正确的用户名和密码,我们将得到以下页面:
我们使用Spring Specural示例进行了Spring休眠Web服务。
如果我们仍然面临任何问题,请发表注释。
如果使用上述步骤获得404错误,则可能需要按照以下步骤操作:
1)如果我们在Tomcat启动控制台日志中获取此警告,则可能导致问题
警告:[SetPropertieSrule] {Server/Service/Engine/Host/Context}将属性"源"设置为"org.eclipse.jst.j2ee.server:springrestfulwebservicesexample"没有找到匹配的属性。
此特定警告基本上意味着Tomcat Server.xml中的元素包含一个未知的属性源,Tomcat不知道该属性如何处理,因此将忽略它。
在Eclipse中解决这个问题,
从服务器视图中从服务器中删除项目。
右键单击服务器 - >添加和删除
然后从服务器配置中删除项目。
然后在同一服务器下运行项目。
应立即删除警告
或者如果警告仍然仍然存在
- 转到服务器视图
- 双击Tomcat服务器。它将打开服务器配置。
- 在"服务器选项"下,检查"发布模块内容以单独分隔XML文件"复选框。
- 重新启动服务器。这次你的页面将没有任何问题。
2)尝试更新Maven项目。
右键单击项目 - > Maven->更新项目

