小编Tin*_*iny的帖子

在Java中使用带有String和Object的equals()方法

Object o1 = new Object();
Object o2 = new Object();
//o1=o2;
System.out.println(o1.equals(o2));
Run Code Online (Sandbox Code Playgroud)

它回来了false.true如果删除了注释,它可以返回.


为什么不适合String同班同学?

String s1=new String();
String s2=new String();
System.out.println(s1.equals(s2));
Run Code Online (Sandbox Code Playgroud)

它回来了true.为什么?(因为String使用实习生或其他涉及的东西?)

java string equals

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

在启用HiddenHttpMethodFilter之后使用Spring MVC 3.0.2上载多个文件

重要提示:对于高于3.0.4的任何Spring版本,此问题完全无用,因为此版本中讨论的问题很久以前已在该版本中修复,并且在后续版本的Spring中不再可重现.


我使用的是Spring 3.0.2版.我需要使用multiple="multiple"文件浏览器的属性上传多个文件,例如,

<input type="file" id="myFile" name="myFile" multiple="multiple"/>
Run Code Online (Sandbox Code Playgroud)

(并没有使用多个文件浏览器,就像这个答案所说的那样,它确实有效,我试过).

虽然没有版本的Internet Explorer支持这种方法,除非使用适当的jQuery插件/小部件,我现在不关心它(因为大多数其他浏览器都支持这个).

这适用于commons fileupload,但除了使用RequestMethod.POSTRequestMethod.GET方法之外,我还想使用Spring支持和建议的其他请求方法,RequestMethod.PUT并且RequestMethod.DELETE在他们自己的适当位置.为此,我已经配置了Spring,HiddenHttpMethodFilter正如这个问题所示.

但即使选择了文件浏览器中的多个文件,它也可以一次只上传一个文件.在Spring控制器类中,方法映射如下.

@RequestMapping(method={RequestMethod.POST}, value={"admin_side/Temp"})
public String onSubmit(@RequestParam("myFile") List<MultipartFile> files, @ModelAttribute("tempBean") TempBean tempBean, BindingResult error, Map model, HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException {
    for (MultipartFile file : files) {
        System.out.println(file.getOriginalFilename());
    }
}
Run Code Online (Sandbox Code Playgroud)

即使请求参数@RequestParam("myFile") List<MultipartFile> files是一个List类型MultipartFile(它一次只能有一个文件).


我可以找到一个可能与 …

spring file-upload spring-mvc spring-3

7
推荐指数
1
解决办法
8916
查看次数

如何每隔一小时以固定的时间间隔删除会话数据?

我正在生成随机令牌,原因在于这个问题中提到的放在a中的内容java.util.ListList保存在会话范围内.

经过一些谷歌搜索后,我决定List在会话中每隔一小时删除所有元素(令牌).

我可以想到使用Quartz API,但这样做,似乎不可能操纵用户的会话.我在Spring中尝试使用Quartz API(1.8.6,2.x与我正在使用的Spring 3.2不兼容)可以在下面看到.

package quartz;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public final class RemoveTokens extends QuartzJobBean
{    
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException
    {
        System.out.println("QuartzJobBean executed.");
    }
}
Run Code Online (Sandbox Code Playgroud)

它在application-context.xml文件中配置如下.

<bean name="removeTokens" class="org.springframework.scheduling.quartz.JobDetailBean">
    <property name="jobClass" value="quartz.RemoveTokens" />
    <property name="jobDataAsMap">
        <map>
            <entry key="timeout" value="5" />
        </map>
    </property>
</bean>

<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
      <property name="jobDetail" ref="removeTokens"/>
      <property name="startDelay" value="10000"/>
      <property name="repeatInterval" value="3600000"/>
</bean>

<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
  <property name="triggers">
      <list> …
Run Code Online (Sandbox Code Playgroud)

java session spring jsp quartz-scheduler

7
推荐指数
1
解决办法
6833
查看次数

静态成员未按预期初始化

以下代码只是从使用java.util.Calendar该类获得的当前年份中减去一个值(在本例中为10,仅用于演示).

public final class Test
{   
    private static final Test TEST = new Test();
    private static final int YEAR = Calendar.getInstance().get(Calendar.YEAR);
    private final int eval=YEAR - 10;

    public static void main(String[] args)
    {
        System.out.println("Evaluation "+TEST.eval);
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望这段代码显示2003(当前年份 - 10),但显示它-10.我假设常量YEAR尚未初始化.为什么会发生这种情况?

java static static-members

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

<f:viewParam>的验证/转换错误不会本地化为<f:view locale>,而是默认语言环境

<f:viewParam>在JSF页面上有一个标记,它在转换和验证后将GET参数设置为相应的托管bean.

如果发生转换或验证错误,则从资源束中获取相应的错误消息并显示在<p:messages>(也可能是<p:growl><h:messages>)上.

该应用程序是多语言的.因此,当选择其他语言时,应以该语言显示消息,但它始终根据默认语言环境显示消息en(对于英语).

Test.xhtml:

<!DOCTYPE html>
<html lang="#{localeBean.language}"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">

    <f:view locale="#{localeBean.locale}">
        <f:metadata>
            <f:viewParam name="id" converter="#{myConverter}" />
        </f:metadata>
        <h:head>
            <title>Test</title>
        </h:head>
        <h:body>
            <h:messages />
        </h:body>
    </f:view>
</html>
Run Code Online (Sandbox Code Playgroud)

转换器:

@FacesConverter("myConverter")
public final class MyConverter implements Converter
{
    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value)
    {
        ResourceBundle bundle = context.getApplication()
            .evaluateExpressionGet(context, "#{messages}", ResourceBundle.class);
        String message = bundle.getString("id.conversion.error");
        throw new ConverterException(
            new FacesMessage(FacesMessage.SEVERITY_ERROR, message, null));
    }

    @Override
    public String getAsString(FacesContext …
Run Code Online (Sandbox Code Playgroud)

validation jsf localization jsf-2 viewparams

7
推荐指数
1
解决办法
670
查看次数

p:fileUpload required ="true",自定义验证器不起作用

由于required属性<p:fileUpload>仍然在PrimeFaces 4.0 final中不起作用,我试图创建一个自定义验证器,如下所示.

@FacesValidator(value="fileUploadValidator")
public final class FileUploadValidator implements Validator
{
    @Override
    public void validate(FacesContext fc, UIComponent uic, Object o) 
    throws ValidatorException
    {
        System.out.println("fileUploadValidator called.");

        if(!(o instanceof UploadedFile))
        {
            FacesMessage message = new FacesMessage();
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            message.setSummary("Error");
            message.setDetail("Required");
            throw new ValidatorException(message);      
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并指定<p:fileUpload>.

<p:fileUpload mode="advanced" 
              required="true"
              multiple="true"
              allowTypes="/(\.|\/)(gif|jpe?g|png)$/"
              fileUploadListener="#{bean.fileUploadListener}">
    <f:validator validatorId="fileUploadValidator"/>
</p:fileUpload>
Run Code Online (Sandbox Code Playgroud)

但是从未调用过validate方法.由于我正在显示图像<p:dataGrid>,因此非常需要此验证.有没有办法验证空<p:fileUpload>

validation jsf primefaces jsf-2.2

7
推荐指数
1
解决办法
6173
查看次数

java.lang.IllegalStateException:在JSF中实现自定义标记处理程序时出现java.lang.InstantiationException

给出以下标记处理程序类.

public final class ViewParamValidationFailed extends TagHandler implements ComponentSystemEventListener
{
    private final String redirect;

    public ViewParamValidationFailed(TagConfig config) {
        super(config);
        redirect = getRequiredAttribute("redirect").getValue();
    }

    @Override
    public void apply(FaceletContext context, UIComponent parent) throws IOException {
        if (parent instanceof UIViewRoot && !context.getFacesContext().isPostback()) {
            ((UIViewRoot) parent).subscribeToEvent(PostValidateEvent.class, this);
        }
    }

    @Override
    public void processEvent(ComponentSystemEvent event) throws AbortProcessingException {
        FacesContext context = FacesContext.getCurrentInstance();

        if (context.isValidationFailed()) {
            try {
                ExternalContext externalContext = context.getExternalContext();
                externalContext.redirect(externalContext.getRequestContextPath() + redirect);
            }
            catch (IOException e) {
                throw new AbortProcessingException(e);
            }
        }
    } …
Run Code Online (Sandbox Code Playgroud)

jsf jsf-2.2

7
推荐指数
1
解决办法
3877
查看次数

如何强制使用excel单元格?

我正在尝试强制使用某些excel单元格,以便在用户将其留空时显示消息.

Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Data Validation");

DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper();
DataValidationConstraint lengthConstraint = dataValidationHelper.createTextLengthConstraint(
        DataValidationConstraint.OperatorType.BETWEEN, "2", "45");

CellRangeAddressList cellList = new CellRangeAddressList(0, 0, 1, 1);
DataValidation validation = dataValidationHelper.createValidation(lengthConstraint, cellList);

validation.setErrorStyle(ErrorStyle.STOP);
validation.createErrorBox("Error", "The length must be between 2 and 45.");
validation.setEmptyCellAllowed(false);

if (validation instanceof XSSFDataValidation) {
    validation.setSuppressDropDownArrow(false);
    validation.setShowErrorBox(true);
} else {
    validation.setSuppressDropDownArrow(true);
}

sheet.addValidationData(validation);

Row row = sheet.createRow(0);
Cell cell = row.createCell(1);
cell.setCellValue("Text");
Run Code Online (Sandbox Code Playgroud)

我使用validation.setEmptyCellAllowed(false);并期望它应该防止细胞被清空但它不起作用.但是,强制执行此约束的单元格的长度为2到45个字符.

为什么validation.setEmptyCellAllowed(false);在这种情况下不起作用?如何使一个单元格成为必需的,以便它不能留空?


使用该validation.setEmptyCellAllowed(false);方法时,似乎验证约束在Excel中正确应用.

在此输入图像描述

未选中" 忽略空白 "复选框.Excel仍允许将强制执行此约束的单元格留空. …

java excel excel-2007 apache-poi

7
推荐指数
1
解决办法
1810
查看次数

正在处理的页面仅在错误/异常中途留空,而不是转发到web.xml中指定的错误页面

在web.xml中,我有一个全局错误页面的以下配置.

<error-page>
    <error-code>401</error-code>
    <location>/WEB-INF/error_pages/GeneralError.xhtml</location>
</error-page>

<error-page>
    <error-code>403</error-code>
    <location>/WEB-INF/error_pages/GeneralError.xhtml</location>
</error-page>

<error-page>
    <error-code>404</error-code>
    <location>/WEB-INF/error_pages/GeneralError.xhtml</location>
</error-page>

<error-page>
    <error-code>500</error-code>
    <location>/WEB-INF/error_pages/GeneralError.xhtml</location>
</error-page>

<error-page>
    <error-code>503</error-code>
    <location>/WEB-INF/error_pages/GeneralError.xhtml</location>
</error-page>
Run Code Online (Sandbox Code Playgroud)

当发生任何异常时(导致500内部服务器错误),请求将被分派到指定的错误页面,但是当发生异常时,正在处理的页面在中途保持空白.它不会转发到错误页面.

配置java.lang.Throwablejava.lang.Exception如下,

<error-page>
    <exception-type>java.lang.Throwable</exception-type>
    <location>/WEB-INF/error_pages/GeneralError.xhtml</location>
</error-page>
Run Code Online (Sandbox Code Playgroud)

也没有帮助了.


web.xml的全部内容:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <context-param>
        <param-name>javax.faces.FACELETS_LIBRARIES</param-name>
        <param-value>/WEB-INF/my.taglib.xml</param-value>
    </context-param>

    <context-param>
        <param-name>javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Production</param-value>
    </context-param>

    <context-param>
        <param-name>com.sun.faces.enableViewStateIdRendering</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <param-name>com.sun.faces.enableRestoreView11Compatibility</param-name>
        <param-value>true</param-value>
    </context-param>

    <context-param>
        <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
        <param-value>server</param-value>
    </context-param>

    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/log4j.properties</param-value>
    </context-param>

    <context-param>
        <param-name>log4jExposeWebAppRoot</param-name>
        <param-value>false</param-value>
    </context-param>

    <filter>
        <filter-name>PrimeFaces FileUpload Filter</filter-name>
        <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
    </filter> …
Run Code Online (Sandbox Code Playgroud)

jsf servlets glassfish java-ee glassfish-4.1

7
推荐指数
1
解决办法
586
查看次数

何时在JPA标准API中使用select子句?

  1. 不使用CriteriaQuery#select():

    public List<Address> getAddressOfManager(String designation, String name, String orderByColumn) {
    
        Boolean ascending = false;
        CriteriaBuilder cb = emanager.getCriteriaBuilder();
        CriteriaQuery<Address> cq = cb.createQuery(Address.class);
        Root<Address> root = cq.from(Address.class);
        //cq.select(root);  <-------------
        Join<Address, Employee> employeeAddress = root.join(Address_.employee);
        Join<Employee,Project> employeeProject = employeeAddress.join(Employee_.project);
        cq.where(cb.or(cb.equal(employeeProject.get(Project_.name), name),cb.equal(employeeAddress.get(Employee_.designation), designation)));
        Order order = ascending ? cb.asc(root.get(orderByColumn))
                : cb.desc(root.get(orderByColumn));
        cq.orderBy(order);
        List<Address> result = emanager.createQuery(cq).getResultList();
        return result;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. CriteriaQuery#select():

    public List<Address> getAddressOfManager(String designation, String name, String orderByColumn) {
    
        Boolean ascending = false;
        CriteriaBuilder cb = emanager.getCriteriaBuilder();
        CriteriaQuery<Address> cq …
    Run Code Online (Sandbox Code Playgroud)

hibernate jpa criteria criteria-api

7
推荐指数
1
解决办法
7233
查看次数