我有可以正常工作的 Apache Wiket + Spring Web 应用程序。目前 Spring 使用 DI 框架并过滤 Mobile 访问。我们计划在我们的应用程序中使用 Spring Rest,你能告诉我如何在我们现有的 web xml 中做到这一点。
最初,现有的 Web 会话将使用 Rest Api 来访问数据(使用 ajax 调用的 ui 页面),因此我希望 Rest 控制器能够访问现有的 Wicket http 会话(如果使用登录)。例如:来自现有http 会话的rest 调用应该能够访问现有http 会话。任何的想法 ?感谢并感谢您的时间。
我的想法是使用org.springframework.web.servlet.DispatcherServlet带有标签的' ',但是我怀疑我是否希望以这种方式共享同一个会话?
我现有的web.xml(工作)
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:myapp-spring-config.xml
</param-value>
</context-param>
<filter>
<filter-name>myapp</filter-name>
<filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
<init-param>
<param-name>applicationFactoryClassName</param-name>
<param-value>org.apache.wicket.spring.SpringWebApplicationFactory</param-value>
</init-param>
</filter>
<filter>
<filter-name>myappMobileRequestFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>myappMobileRequestFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用休息服务,我正在发布一些数据,RestTemplate postForObjectMethod但是我得到了一个null响应,即使我可以在有效负载中看到请求和响应.
[更新]我正在使用拦截器实施ClientHttpRequestInterceptor,如果我删除它,我得到了响应.
[PS:该服务配置为POST,理想情况下它应该是GET,原因很明显,但我仍然很好奇为什么没有响应作为帖子的一部分来,即使我可以在http日志中看到相同.]
配置基于Spring MVC 4的应用程序
应用背景:
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</list>
</property>
<property name="interceptors">
<list>
<bean class="com.sipl.interceptors.LoggingRequestInterceptor" />
</list>
</property>
</bean>
Run Code Online (Sandbox Code Playgroud)
杰克逊POM
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
拦截器类
public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor {
final static Logger logger = LoggerFactory.getLogger(LoggingRequestInterceptor.class);
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
traceRequest(request, body);
ClientHttpResponse response = execution.execute(request, body);
traceResponse(response); …Run Code Online (Sandbox Code Playgroud) 任何人都可以为我提供一个代码示例来为使用HTTPS保护的控制器编写集成测试吗?使用HTTP我能够写,但使用HTTPS我得到认证错误.
调节器
@RestController
@RequestMapping("/rest/otm/v1")
public class LoginController {
@Autowired
UserAuthenticationService userAuthService;
@ExceptionHandler({ AuthenticationFailedException.class})
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public void login(HttpServletRequest request,HttpServletResponse response) throws AuthenticationDeniedException {
//some code
}
}
Run Code Online (Sandbox Code Playgroud)
测试类
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest("server.port:0")
public class IdentityControllerTest {
@Value("${local.server.port}")
int port;
@Test
public void test_Login_Controller() {
SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("some-proxy", 8080));
clientHttpRequestFactory.setProxy(proxy);
RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("credential", "pratap");
requestHeaders.set("deviceid", "xyz123");
HttpHeaders …Run Code Online (Sandbox Code Playgroud) spring-test spring-test-mvc spring-boot spring-restcontroller
我尝试创建spring rest服务,whis是我自己的oauth2资源服务器的高手.我创建了资源服务器:
@Configuration
@EnableResourceServer
protected static class ResourceServer extends ResourceServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenStore(tokenStore).resourceId("mobileapp");
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/api/shop /**").authenticated().and()
.authorizeRequests().antMatchers("/auth/**").anonymous();
}
}
Run Code Online (Sandbox Code Playgroud)
和授权服务器:
@Configuration
@EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager auth;
@Autowired
private DataSource dataSource;
@Autowired
private BCryptPasswordEncoder passwordEncoder;
@Bean
public JdbcTokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
@Bean
protected AuthorizationCodeServices authorizationCodeServices() {
return new JdbcAuthorizationCodeServices(dataSource);
}
@Override
public …Run Code Online (Sandbox Code Playgroud) spring-mvc spring-security spring-security-oauth2 spring-restcontroller
由于在angular2和spring应用程序之间维护用户会话,我在java后端(在SecurityConfig.java文件中)启用了CSRF .但是当帖子提交被解雇时,我还没有看到任何绑定到POST请求的CSRF令牌.
如何将CSRF令牌添加到我的angular2应用程序中.(添加到帖子请求)
loginService.ts
userLogin(loginDTO){
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
var result = this._http.post(this._rest_service_login, JSON.stringify(loginDTO),options)
.map(res => res.json());
return result;
}
Run Code Online (Sandbox Code Playgroud) csrf spring-security csrf-protection spring-restcontroller angular
如何POST向应用程序本身发送请求?
如果我只发送一个相对的帖子请求:java.lang.IllegalArgumentException: URI is not absolute.
@RestController
public class TestServlet {
@RequestMapping("value = "/test", method = RequestMethod.GET)
public void test() {
String relativeUrl = "/posting"; //TODO how to generate like "localhost:8080/app/posting"?
new RestTemplate().postForLocation(relativeUrl, null);
}
}
Run Code Online (Sandbox Code Playgroud)
所以使用上面的例子,我如何在url前加上绝对服务器url路径localhost:8080/app?我必须动态地找到路径.
我将Spring / Spring Boot和Spring MVC与@RestController一起使用
我有一个复合模型对象:
public abstract class BaseQuery {
private final Long characteristicId;
...
}
public abstract class ComparableQuery extends BaseQuery {
private final Object value;
private final String comparisonOperator;
...
}
public class GreaterOrEqualQuery extends ComparableQuery {
public GreaterOrEqualQuery(Long characteristicId, Object value) {
super(characteristicId, value, ">=");
}
}
public class EqualQuery extends ComparableQuery {
public EqualQuery(Long characteristicId, Object value) {
super(characteristicId, value, "=");
}
}
public class GreaterQuery extends ComparableQuery {
public GreaterQuery(Long characteristicId, Object value) { …Run Code Online (Sandbox Code Playgroud) 我想记录所有传入的请求,这些请求将是json格式.我使用spring @RestController和@RequestBody注释将传入的json内容绑定到java对象.但是我想将这些请求记录到logger文件.我搜索过用于objectmapper和jacksonbinding.
@RestController
public class restClassName{
@RequestMapping(value={"/uri"})
public ObjectResponse functionRestName(@RequestBody ObjectRequest or){
String jsonInString = mapper.writeValueAsString(staff);//Redundant stuff as the request json is already read by MappingJackson2HttpMessageConverter
logger.info("request::"+jsonInString)
return instance;
}
}
Run Code Online (Sandbox Code Playgroud)
但这似乎是一种非常重要的做法.由于MappingJackson2HttpMessageConverter已经读取了httprequest以将json请求转换为java对象.我只需要在MappingJackson2HttpMessageConverter将请求json转换为java对象之前记录json.
我想从 spring 控制器方法返回一个 JSONArray(org.json.jar) 对象,这是我的 java spring 控制器:
import org.json.JSONArray;
import org.json.JSONException;
@RestController
public class BICOntroller{
@RequestMapping(value="/getStatus", method = RequestMethod.GET)
public ResponseEntity<JSONArray> getStatus() throws JSONException{
ResponseEntity<JSONArray> response = null;
JSONArray arr = new JSONArray();
JSONObject obj = new JSONObject();
//process data
arr.put(obj);
response = new ResponseEntity<JSONArray>(arr, HttpStatus.OK);
return response;
}
}
Run Code Online (Sandbox Code Playgroud)
角度js调用:
$http({
url: 'getStatus',
method: 'GET',
responseType: 'json'
}).then(function(response){
console.log(response);
return response;
}, function(error){
console.log(error);
return error;
});
Run Code Online (Sandbox Code Playgroud)
这给出了 500 错误:
java.lang.IllegalArgumentException: No converter found for return value of …Run Code Online (Sandbox Code Playgroud) @RestController
@RequestMapping("/employee")
public class Employee {
@RequestMapping("/save")
public void saveEmployee() {
// saving employee
}
}
Run Code Online (Sandbox Code Playgroud)
@RequestMapping内部如何将请求映射到saveEmployee方法?
spring ×6
java ×4
spring-mvc ×3
json ×2
spring-boot ×2
angular ×1
angularjs ×1
csrf ×1
jackson ×1
rest ×1
resttemplate ×1
spring-rest ×1
spring-test ×1
spring-web ×1
web-services ×1
web.xml ×1
wicket ×1
wicket-6 ×1