小编Tin*_*iny的帖子

如果尝试使用反射将值设置为String类的值[]字段,则Java 6和Java 7会产生不同的结果

以下代码尝试使用Java 7将值设置为private final char value[]String类的字段.

package test;

import java.lang.reflect.Field;

public final class Test 
{
    static
    {
        try
        {
            Field value = String.class.getDeclaredField("value");
            value.setAccessible(true);
            value.set("Hello World", value.get("1234567890"));
        }
        catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e)
        {
            System.out.println(e.toString());
        }
    }

    public static void main(String[] args) 
    {
        System.out.println("Hello World");
    }
}
Run Code Online (Sandbox Code Playgroud)

它默默地显示1234567890在控制台上,毫无疑问.


当我尝试使用Java 6做同样的事情,如下所示,

package test;

import java.lang.reflect.Field;

public final class Test
{
    static
    {
        try
        {
            Field value = String.class.getDeclaredField("value");
            value.setAccessible(true);
            value.set("Hello …
Run Code Online (Sandbox Code Playgroud)

java string reflection java-6 java-7

2
推荐指数
1
解决办法
238
查看次数

在 Spring 中使用 setAllowedFields() 方法

我正在使用 Spring 3.2.0。我已经注册了一些自定义属性编辑器以满足一些基本需求,如下所示。

import editors.DateTimeEditor;
import editors.StrictNumberFormatEditor;
import java.math.RoundingMode;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import org.joda.time.DateTime;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.beans.propertyeditors.URLEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.WebRequest;

@ControllerAdvice
public final class GlobalDataBinder 
{
    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request)
    {
        binder.setIgnoreInvalidFields(true);
        binder.setIgnoreUnknownFields(true);
        //binder.setAllowedFields(someArray);
        NumberFormat numberFormat=DecimalFormat.getInstance();
        numberFormat.setGroupingUsed(false);
        numberFormat.setMaximumFractionDigits(2);
        numberFormat.setRoundingMode(RoundingMode.HALF_UP);

        binder.registerCustomEditor(DateTime.class, new DateTimeEditor("MM/dd/yyyy HH:mm:ss", true));
        binder.registerCustomEditor(Double.class, new StrictNumberFormatEditor(Double.class, numberFormat, true));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
        binder.registerCustomEditor(URL.class, new URLEditor());
    } 
}
Run Code Online (Sandbox Code Playgroud)

到目前为止我已经注册了这么多编辑。其中两个DateTimeEditorStrictNumberFormatEditor通过重写各自的方法进行定制,以满足数字格式和Joda-Time的自定义需求。

由于我使用的是 Spring 3.2.0,因此我可以利用@ControllerAdvice …

spring spring-mvc propertyeditor databinder spring-3

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

在p:向导中以编程方式设置当前显示的选项卡

是否可以设置当前显示的标签编程<p:wizard>

例如,我想要对包含向导的同一页面的两个不同请求,以选择不同的选项卡.

我目前正在尝试做的是,有一个带有许多选项卡的向导,在第二个选项卡中我有一个重定向到另一个页面,所以当我回来时,我想进入导致重定向的最后一步.

你能帮我么 ?非常感谢 !

jsf primefaces jsf-2

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

如何有条件地检查来自 JSP 中 Spring 的空验证错误消息?

我有一个简单的问题。我们可以显示由 Spring 验证器生成的错误消息,如下所示。

<form:errors path='edId' cssStyle='font-weight: normal; color: red;'/>
Run Code Online (Sandbox Code Playgroud)

我正在使用一些 HTML 之类的<ul><li></li></ul>和 CSS来显示此类消息。因此,即使没有错误,也会不必要地显示空白项目符号。

因此,我需要在 JSP 页面上有条件地检查消息是否实际上是空白的,例如,

<c:if test="${not empty edIdError}">
    <form:errors path='edId' cssStyle='font-weight: normal; color: red;'/>       
</c:if>
Run Code Online (Sandbox Code Playgroud)

但是测试这种if情况需要将错误消息存储到 JSP 上的某个变量中,例如<c:set var="edIdError"/>(作为示例),这对我来说似乎是不可能的。是否可以?有没有其他方法可以做到这一点?

无论如何,我只想在消息不为空时显示带有一些 HTML 和 CSS 的消息。我正在使用 Spring 3.2.0。

是的,我有一个不同的场景,不能使用这种方法。

spring jsp jstl el

2
推荐指数
1
解决办法
5225
查看次数

如何在Java中获取BigInteger的精度

我正在我的Web应用程序中实现一个可以验证BigIntegerbean属性的自定义验证器.此属性映射到一种Number(8, 0)Oracle表.

就像BigDecimal,我没有看到一个方法BigInteger可以返回给定数字的精度.

基本上,我首先将一个BigInteger值转换BigDecimal为获得其精度,如下所示(仅用于演示).

int minPrecision=1;
int maxPrecision=8;

BigInteger bigInteger=new BigInteger("12345");
BigDecimal bigDecimal=new BigDecimal(bigInteger, 0);

int precision=bigDecimal.precision();
boolean isValid=precision>=minPrecision && precision<=maxPrecision;

System.out.println(isValid+" : "+precision);
Run Code Online (Sandbox Code Playgroud)

是否BigInteger提供了返回其值精度的精确方法?

java biginteger bigdecimal

2
推荐指数
1
解决办法
1773
查看次数

使用 JPA 条件在另一个表中使用搜索条件构建搜索查询

我需要StateTable根据表中给定的国家/地区名称(不是countryId)搜索州Country,该名称应like使用 JPA 标准 API 与 SQL 运算符匹配(顾名思义,countryId是外键)。StateTable

CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<StateTable> criteriaQuery = criteriaBuilder
                                          .createQuery(StateTable.class);
Root<StateTable>root=criteriaQuery.from(StateTable.class);

List<Predicate>predicates=new ArrayList<Predicate>();

predicates.add(criteriaBuilder
          .like(root.<String>get("countryName"), "%"+countryName+"%"));

criteriaQuery.where(predicates.toArray(new Predicate[0]));

entityManager.createQuery(criteriaQuery)
             .setFirstResult(first)
             .setMaxResults(pageSize)
             .getResultList();
Run Code Online (Sandbox Code Playgroud)

如何修改以下语句以满足需要?(同样countryName在表中可用Country,并且此条件查询是关于StateTable)。

predicates.add(criteriaBuilder
          .like(root.<String>get("countryName"), "%"+countryName+"%"));
Run Code Online (Sandbox Code Playgroud)

使用 JPQL 很乏味,因为需要为多个搜索条件构建查询。这只是一个演示/说明。


实体Country

@Entity
public class Country implements Serializable {
    @Id
    private Long countryId;             //<----------------------
    @Column(name = "country_name")
    private String countryName;
    @Column(name = "country_code")
    private String …
Run Code Online (Sandbox Code Playgroud)

jpa criteria-api

2
推荐指数
1
解决办法
9482
查看次数

如果<p:selectOneMenu>和<h:outputText>的value属性不同,则Primefaces DataTable不会使用下拉框更新显示值

我有一个使用Primefaces 3.5的dataTable,如下所示.

在此输入图像描述

现在我正在使用id 43编辑第二行,如下所示.

在此输入图像描述

当我单击刻度线(最右边的列)时,将对该行进行编辑,如下图所示.

在此输入图像描述

它可以很容易地注意到,国家的名字是从改变xxxxzzz,但该国仍显得预计将被更新为相同AmericaGermany.

实际上,已对数据库进行了更改,但在rowEdit事件完成时它们似乎没有反映到dataTable .

要观察对国家/地区所做的更改,需要重新加载页面.仅当重新加载此页面时,它才会显示正确的数据,如下所示.

在此输入图像描述


这是列出国家/地区下拉框的列.

<p:ajax event="rowEdit" listener="#{stateManagedBean.onRowEdit}" update=":form:dataTable :form:systemMessages :form:messages" process=":form:dataTable :form:systemMessages :form:messages"/>
<p:ajax event="rowEditCancel" listener="#{stateManagedBean.onRowEditCancel}" update=":form:systemMessages :form:messages" process=":form:systemMessages :form:messages"/>


<p:column headerText="Country" sortBy="#{state.country.countryName}" filterBy="#{state.country.countryName}" filterMaxLength="45">                    
    <p:cellEditor>
        <f:facet name="output">
            <h:outputText value="#{state.country.countryName}" />
        </f:facet>
        <f:facet name="input">
            <p:selectOneMenu id="cmbCountryMenu" value="#{state.country.countryId}" rendered="true" editable="false" converter="#{longConverter}" converterMessage="The supplied value is incorrect." required="true" requiredMessage="Select an appropriate option." style="width:100%;">
                <f:selectItems var="country" value="#{stateManagedBean.countries}"  itemLabel="${country.countryName}" itemValue="${country.countryId}" …
Run Code Online (Sandbox Code Playgroud)

jsf selectonemenu primefaces

2
推荐指数
1
解决办法
5621
查看次数

无法在jsf中获取servletcontext路径

我写了一个liferay richfaces portlet.但是我无法在web-inf文件夹中获取css路径或图像.我的portlet配置是

 <portlet>
    <portlet-name>testLR6_PB3_RF4</portlet-name>
    <instanceable>true</instanceable>

    <render-weight>1</render-weight>
    <ajaxable>true</ajaxable>
    <header-portlet-css>/resources/css/style.css</header-portlet-css>
        <header-portlet-javascript>/js/eims.js</header-portlet-javascript>
        <footer-portlet-javascript>/js/fileupload.js</footer-portlet-javascript>
  </portlet>
Run Code Online (Sandbox Code Playgroud)

并在我的jsf页面

<link href="${facesContext.externalContext.requestContextPath}/resources/css/style.css" rel="stylesheet" type="text/css" />

<div class="floatleft1"><img src="${facesContext.externalContext.requestContextPath}/resources/images/eims_logo.jpg"  /></div>
Run Code Online (Sandbox Code Playgroud)

如何获得资源路径.

这是我的java servletcontext代码

FacesContext context = FacesContext.getCurrentInstance();
        ServletContext servletContext= (ServletContext) context.getCurrentInstance().getExternalContext().getContext();
        String path=servletContext.getRealPath("/");
        MainBean mainBean = new MainBean();
        mainBean.getUserBean().setUserPath(path);
Run Code Online (Sandbox Code Playgroud)

jsf servletconfig jsf-2

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

修改finally块中方法的返回值不会返回实际修改的值

作为一项规则,该finally块总是执行中的异常是否被抛出try块或continue,breakreturn在声明中遭遇try块本身.

因此,应该更改下面给出的代码片段中的方法的返回值,但不会.

final class Product
{
    private String productName=null;

    public Product(String productName)
    {
        this.productName=productName;
    }

    public String getProductName()
    {
        try
        {
            return this.productName;
        }
        finally
        {
            this.productName="The product name has been modified in the finally block.";
            System.out.println("Product name in the finally block : "+this.productName);
        }
    }
}

public final class Test
{
    public static void main(String...args)
    {
        System.out.println(new Product("Intel core i3").getProductName());
    }
}
Run Code Online (Sandbox Code Playgroud)

在调用此方法之前,该方法getProductName()只返回由构造函数指定给字段的产品名称productName. …

java

2
推荐指数
1
解决办法
924
查看次数

p:dataTable 中的自定义过滤器和转换器

由于 PrimeFaces 尚不支持<p:dataTable>过滤器的转换器,我正在尝试实现我自己的自定义过滤器<p:calendar>(当然,这个过滤器的设计看起来仍然有些丑陋。它需要应用我不能的正确 CSS)。

<p:column id="discountStartDate" sortBy="#{row.discountStartDate}" style="width:140px;">
    <f:facet name="header">
        Start Date<br/>

        <p:calendar id="startDateFilter" converter="#{dateTimeConverter}"
                    timeZone="Asia/Kolkata" locale="#{localeBean.locale}"
                    pattern="dd-MMM-yyyy hh:mm:ss a" 
                    readonly="#{facesContext.currentPhaseId.ordinal eq 6}"
                    label="Start Date"
                    effect="slide" required="true"
                    size="12"
                    showButtonPanel="true" navigator="true">

            <p:ajax event="dateSelect" listener="#{discountManagedBean.startDateListener}" 
                    onstart="PF('blockDataTableUIWidget').block()"
                    oncomplete="PF('blockDataTableUIWidget').unblock()"
                    update="dataTable"/>
        </p:calendar>

    </f:facet>

    <!--No need to refer to-->

    <p:cellEditor>
        <f:facet name="output">
            <h:outputText value="#{row.discountStartDate}" converter="#{dateTimeConverter}"/>
        </f:facet>
        <f:facet name="input">
            <p:tooltip for="dataTableTxtDiscountStartDate" value="#{messages['tooptip.dataTable.popup.calendar']}"/>
            <p:calendar id="dataTableTxtDiscountStartDate" binding="#{edStartDate}" value="#{row.discountStartDate}" converter="#{dateTimeConverter}" timeZone="Asia/Kolkata" locale="#{localeBean.locale}" pattern="dd-MMM-yyyy hh:mm:ss a" readonly="#{facesContext.currentPhaseId.ordinal eq 6}" label="#{messages['discount.startdate']}" effect="explode" required="true" showButtonPanel="true" navigator="true"/>
        </f:facet>
    </p:cellEditor>
</p:column> …
Run Code Online (Sandbox Code Playgroud)

datatable jsf primefaces jsf-2.2

2
推荐指数
1
解决办法
8654
查看次数