小编Bil*_*rza的帖子

如何获得正则表达式匹配的组值

我有以下几行代码

String time = "14:35:59.99";
String timeRegex = "(([01][0-9])|(2[0-3])):([0-5][0-9]):([0-5][0-9])(.([0-9]{1,3}))?";
String hours, minutes, seconds, milliSeconds;
Pattern pattern = Pattern.compile(timeRegex);
Matcher matcher = pattern.matcher(time);
if (matcher.matches()) {
    hours = matcher.replaceAll("$1");
    minutes = matcher.replaceAll("$4");
    seconds = matcher.replaceAll("$5");
    milliSeconds = matcher.replaceAll("$7");
}
Run Code Online (Sandbox Code Playgroud)

我使用matcher.replace正则表达式组的方法和反向引用获得小时,分钟,秒和毫秒.有没有更好的方法来获得正则表达式组的价值.我试过了

hours = matcher.group(1);
Run Code Online (Sandbox Code Playgroud)

但它抛出以下异常:

java.lang.IllegalStateException: No match found
    at java.util.regex.Matcher.group(Matcher.java:477)
    at com.abnamro.cil.test.TimeRegex.main(TimeRegex.java:70)
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么吗?

java regex

44
推荐指数
2
解决办法
5万
查看次数

以角$ http确定请求超时

我正在使用angular发送http请求,如下所示.

$http({
    url: url,
    params: params,
    method:'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    timeout: 60000    //60 seconds
}).success(function(data, status, headers, config) {
    //do something 
}).error(function(data, status, header, config) {
    if(timedout){  //determine occurrence of timeout.
        //invoke timeout handler
    } else  
        //handle other error
    }
});
Run Code Online (Sandbox Code Playgroud)

如何确定超时?

我观察到在这种情况下收到状态码"0".检查status == 0 for timeout是否安全?

请注意,我不是在询问HTTP请求超时(状态码408).

angularjs

17
推荐指数
2
解决办法
8781
查看次数

Deci和Centi Seconds在java中解析

我有时间戳作为字符串"2013-01-28 11:01:56.9".这里提到56.9秒.

.9秒= 900毫秒

我们可以说它是9分秒或90厘秒

但在java ...

String string = "2013-01-28 11:01:56.9";
String pattern = "yyyy-MM-dd hh:mm:ss.S";
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
Date date = formatter.parse(string);
System.out.println(date.getTime());
Run Code Online (Sandbox Code Playgroud)

输出为:1359388916009

这里9解析为009毫秒,因为"S"(Capital-S)用于毫秒.

类似地,如果提供.95秒并用"SS"模式解析,则它给出"095"毫秒而不是"950"毫秒.

  • 为什么java不提供解析/格式化deci-seconds和centi-seconds的模式以使事情变得更容易?
  • 这样做的好方法是什么?

java

9
推荐指数
1
解决办法
799
查看次数

具有自动装配功能的动态代理Bean

在我正在开发的基于Spring的项目中,有一层用于调用Web服务的功能.对于每个Web服务操作,创建的方法具有几乎相同的代码,但具有一些不同的特定于操作的信息(例如,服务名称,操作名称,命名空间等).

我正在使用接口和带注释的方法替换此层.例如,下面的代码是为web服务("foo")的操作"fetchBar"提供的.

package a.b.c.webservices;

@WebService(service="foo", namespace="...")
public interface FooWebService {

    @WebServiceOperation(operation="fetchBar")
    BarRespons fetchBar(BarRequest request) throws WebServiceException;
}
Run Code Online (Sandbox Code Playgroud)

现在我想,通过一些机制,spring允许我从一些指定的包创建动态代理bean,我可以使用以下代码来调用Web服务.

package a.b.c.business;

import a.b.c.webservices.FooWebService;

public class FooBusiness {

    @Autowired 
    FooWebService fooWebService;


    public Bar getBar() {

        Bar bar = null;            

        BarRequest request; 

        //create request
        BarResponse response = fooWebService.fetchBar(request);
        //extrac bar from response

        return bar;
    }
}
Run Code Online (Sandbox Code Playgroud)

为了实现这一点,我java.lang.reflect.Proxy.newProxyInstance通过提供实现来创建动态bean实例InvocationHandler.但是,自动装配在提供的实现invocationHandler及其进一步的依赖性中不起作用.

我尝试了以下方法来实现这一目标.

  • BeanFactoryPostProcessor.postProcessBeanFactory使用ConfigurableListableBeanFactory.registerSingleton方法实现和注册bean .
  • 已实现ImportBeanDefinitionRegistrar.registerBeanDefinitions并尝试使用,BeanDefinitionRegistry.registerBeanDefinition但我很困惑如何提供支持自动装配的正确Bean定义.

任何人都可以告诉我缺少什么吗?如果我没有朝着正确的方向前进,请指导我.

spring dynamic-proxy

8
推荐指数
1
解决办法
4016
查看次数

Struts2 BigDecimal Converter未转换为String

我有以下代码:

xwork-conversion.properties

java.math.BigDecimal=demo.BigDecimalConverter
Run Code Online (Sandbox Code Playgroud)

BigDecimalConverter.java

package demo;

import java.math.BigDecimal;
import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;

public class BigDecimalConverter extends StrutsTypeConverter{

    @Override
    public Object convertFromString(Map context, String[] values, Class clazz) {
        System.out.println("BigDecimal : Converting from String : " + values[0]);
        return new BigDecimal(values[0]);
    }


    @Override
    public String convertToString(Map context, Object value) {
        String str = ((BigDecimal)value).toPlainString();
        System.out.println("BigDecimal : Converted to String : " + str);
        return str;
    }
}
Run Code Online (Sandbox Code Playgroud)

TheAction.java

package demo;

//imports...

public class TheAction extends ActionSupport {
    private BigDecimal bigField;   //with getter …
Run Code Online (Sandbox Code Playgroud)

javascript java struts2 bigdecimal struts2-json-plugin

6
推荐指数
2
解决办法
1545
查看次数

Spring REST Controller的单元测试'Location'标题

在Spring REST Controller中创建资源后,我将在标题中返回它的位置,如下所示.

@RequestMapping(..., method = RequestMethod.POST)
public ResponseEntity<Void> createResource(..., UriComponentsBuilder ucb) {

    ...

    URI locationUri = ucb.path("/the/resources/")
        .path(someId)
        .build()
        .toUri();

    return ResponseEntity.created(locationUri).build();
}
Run Code Online (Sandbox Code Playgroud)

在单元测试中,我正在检查其位置如下.

@Test
public void testCreateResource(...) {
    ...
    MockHttpServletRequestBuilder request = post("...")
        .content(...)
        .contentType(MediaType.APPLICATION_JSON)
        .accept(MediaType.APPLICATION_JSON);

    request.session(sessionMocked);

    mvc.perform(request)
        .andExpect(status().isCreated())
        .andExpect(header().string("Location", "/the/resources" + id);
}
Run Code Online (Sandbox Code Playgroud)

此结果案例失败,并显示以下消息.

java.lang.AssertionError: Response header Location expected:</the/resources/123456> but was:<http://localhost/the/resources/123456>
Run Code Online (Sandbox Code Playgroud)

好像我必须为http://localhost期望的Location头提供上下文前缀.

  • 硬编码上下文是否安全?如果是这样,为什么?
  • 如果没有,为测试用例正确生成它的正确方法是什么?

rest testng spring mockmvc

6
推荐指数
2
解决办法
2615
查看次数

如何使用struts 2 json插件在json响应中包含父类字段

我有以下实施

public abstract class BaseAcion extends ActionSupport {
    private String result;
    private String message;

    //getters, setters
}

public class MyAction extends BaseAction {
    private String myFirstField;
    private String mySecondField;

    public String execute() {
         ...
         myFirstField = "someValue";
         mySecondField = "someOtherValue";
         ...
         result = SUCCESS;
         message = "Some message here";
         ...
         return result;
    }

    //methods, getters, setters
}
Run Code Online (Sandbox Code Playgroud)

我用过struts2-json插件,动作映射是

<package name="my-package" namespace="/" extends="json-default" >
    <action name="myAction" class="MyAction">
        <result type="json"></result>
    </action> 
</package>
Run Code Online (Sandbox Code Playgroud)

我收到的回复是这样的.

{
    "myFirstField":"someValue",
    "mySecondField":"someOtherValue"
}
Run Code Online (Sandbox Code Playgroud)

我想得到"结果"和"消息"字段作为回应.

如何在json响应中包含BaseAction字段?

json struts2

5
推荐指数
1
解决办法
3930
查看次数

在Struts2拦截器中使用资源包

Struts2 Actions通常扩展ActionSupport实现TextProvider接口的类,并使用getText()方法以方便的方式提供对资源包文件的访问.

我想在拦截器中使用资源包.我想我必须复制TextProvider实现并将其粘贴到我的拦截器中.

我已经定义了全球资源档案 struts.xml

<constant name="struts.custom.i18n.resources" value="resources.global" /> 
Run Code Online (Sandbox Code Playgroud)

并放置global.propertiesresources包中.

它在Action Classes中工作正常

是否有更简单的方法在拦截器中使用资源包?

java struts2 java-ee web

5
推荐指数
1
解决办法
2427
查看次数

如何在将tile插入页面之前检查tile属性的存在

我在struts2应用程序中使用tile.在定义基本布局时,我定义了一个属性"scriptFile".

<definition name="baseLayout" template="/application/base-layout.jsp" >
    ... 
</definition>

<definition name="custom.tiles" extends="baseLayout">
    <put-attribute name="scriptFile" value="js/custom-script.js"></put-attribute>
</definition>
Run Code Online (Sandbox Code Playgroud)

如果开发人员在切片定义文件"tiles.xml"中提供"scriptFile",则应使用以下行包含此脚本文件

<script language="javascript" src="<tiles:insertAttribute name="scriptFile"></tiles:insertAttribute>"></script>
Run Code Online (Sandbox Code Playgroud)

但是,如果未定义scriptFile属性,则必须跳过此行.

如何检查tile中是否存在"scriptFile"属性.有没有更好的方法来做这件事?

struts2 tiles java-ee apache-tiles

5
推荐指数
1
解决办法
6067
查看次数

在Struts 2中获取拦截器参数

我有以下动作映射

<action name="theAction" ...>
...
    <param name="param1">one</param>
    <param name="param2">two</param>
    ...
    <param name="paramN">nth-number</param>
...
</action>
Run Code Online (Sandbox Code Playgroud)

我可以在Interceptor中使用以下行获取参数映射

Map<String, Object> params = ActionContext.getContext().getParameters();
Run Code Online (Sandbox Code Playgroud)

如上所述,是否有任何方法可以获得以下映射中定义的拦截器参数.

<action name="theAction" ...>
...
    <interceptor-ref name="theInterceptor">
        <param name="param1">one</param>
        <param name="param2">two</param>
        ...
        <param name="paramN">nth-number</param>
    </interceptor-ref>
...
</action>
Run Code Online (Sandbox Code Playgroud)

并且动作参数以下列方式定义,动作参数和拦截器参数应该可以单独访问.

<action name="theAction" ...>
...
    <param name="param1">one</param>
    <param name="param2">two</param>
    ...
    <param name="paramN">nth-number</param>
    ....
    <interceptor-ref name="theInterceptor">
        <param name="param1">one</param>
        <param name="param2">two</param>
        ...
        <param name="paramN">nth-number</param>
    </interceptor-ref>
...
</action>
Run Code Online (Sandbox Code Playgroud)

请注意,我不想在拦截器中声明参数字段

//all fields with their getters and setters
private String param1;
private String param2; …
Run Code Online (Sandbox Code Playgroud)

java parameters struts2 interceptor interceptorstack

5
推荐指数
1
解决办法
1万
查看次数

Struts2 web.xml中的配置文件名

http://struts.apache.org/2.3.1.2/docs/webxml.html

根据以上链接,我们可以在web.xml中指定配置文件名.所以我config在后面的映射中添加了param.

<filter>
    <filter-name>struts2</filter-name>
    <filter-class>
        org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
    </filter-class>
    <init-param>
        <param-name>config</param-name>
        <param-value>struts.xml</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>*.action</url-pattern>
</filter-mapping>
Run Code Online (Sandbox Code Playgroud)

现在我无法启动Web应用程序.日志记录在控制台上.

SEVERE: Dispatcher initialization failed

com.opensymphony.xwork2.inject.DependencyException: com.opensymphony.xwork2.inject.ContainerImpl$MissingDependencyException: No mapping found for dependency [type=com.opensymphony.xwork2.ObjectFactory, name='default'] in public void com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.setObjectFactory(com.opensymphony.xwork2.ObjectFactory).
at com.opensymphony.xwork2.inject.ContainerImpl.addInjectorsForMembers(ContainerImpl.java:144)
at com.opensymphony.xwork2.inject.ContainerImpl.addInjectorsForMethods(ContainerImpl.java:113)
at com.opensymphony.xwork2.inject.ContainerImpl.addInjectors(ContainerImpl.java:90)
at com.opensymphony.xwork2.inject.ContainerImpl.addInjectors(ContainerImpl.java:86)
at com.opensymphony.xwork2.inject.ContainerImpl$1.create(ContainerImpl.java:71)
at com.opensymphony.xwork2.inject.ContainerImpl$1.create(ContainerImpl.java:67)
at com.opensymphony.xwork2.inject.util.ReferenceCache$CallableCreate.call(ReferenceCache.java:150)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:284)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at com.opensymphony.xwork2.inject.util.ReferenceCache.internalCreate(ReferenceCache.java:76)
at com.opensymphony.xwork2.inject.util.ReferenceCache.get(ReferenceCache.java:116)
at com.opensymphony.xwork2.inject.ContainerImpl.inject(ContainerImpl.java:483)
at com.opensymphony.xwork2.inject.ContainerImpl$6.call(ContainerImpl.java:523)
at com.opensymphony.xwork2.inject.ContainerImpl$6.call(ContainerImpl.java:521)
at com.opensymphony.xwork2.inject.ContainerImpl.callInContext(ContainerImpl.java:574)
at com.opensymphony.xwork2.inject.ContainerImpl.inject(ContainerImpl.java:521)
at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:203)
at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:66)
at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:390)
at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:436)
at org.apache.struts2.dispatcher.ng.InitOperations.initDispatcher(InitOperations.java:69)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.init(StrutsPrepareAndExecuteFilter.java:51) …
Run Code Online (Sandbox Code Playgroud)

struts2

4
推荐指数
1
解决办法
1万
查看次数