小编bes*_*art的帖子

Spring ResponseEntity返回自定义状态代码

我正在尝试实现一个自定义 HttpStatus 代码系统来提供有关我的 REST 服务的错​​误信息。

为此,我实现了一个新的枚举 CustomHttpStatus

public enum CustomHttpStatus {

    ERROR1(42, "Error 1"),
    ERROR2(43, "Error 2"),
    ERROR3(44, "Error 3"),
    ERROR4(45, "Error 4"),
    ERROR5(46, "Error5");

    private CustomHttpStatus(int value, String reason) {
        this.value = value;
        this.reason = reason;
    }

    private final int value;

    private final String reason;

    public int getValue() {
        return value;
    }

    public String getReason() {
        return reason;
    }

}
Run Code Online (Sandbox Code Playgroud)

然后,我有一个类,它携带有关错误的信息并管理标准 HTTPStatus 和我的 CustomHttpStatus

public class ApiError {

    private HttpStatus status;
    private CustomHttpStatus customStatus;
    private String message;
    private List<String> …
Run Code Online (Sandbox Code Playgroud)

java spring

5
推荐指数
0
解决办法
2087
查看次数

SpringData JPA - 为 class 提供了错误类型的 id。预期:类 java.lang.Integer,得到类 java.lang.Long

我在使用 Spring JPA 并尝试检索对象列表时遇到了这个问题。

这是我试图检索的课程

@Entity
@Table(name="OBJECTSTERMIC")
public class TermicObject {

    @Id
    @Column(name="TERMICID")
    private long termicId;

    @MapsId
    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="OBJECTID",columnDefinition="INTEGER")
    private Object object;

    @Column(name="CONTECA_RIF")
    private int contecaRif;

    @Column(name="CONTECA_VAL")
    private int contecaVal;

    @Column(name="TYPE")
    private String type;

//getters and setters
Run Code Online (Sandbox Code Playgroud)

Object班有存储为整数MySQL的主键,这的确是Object

@Entity
public class Object {

    @Column(name="OBJECTID")
    @Id
    @JsonProperty("OBJECTID")
    private int objectId;
    ....
Run Code Online (Sandbox Code Playgroud)

所以,无处设置长...

现在,我只是调用一个服务类

@Override
    public List<TermicObject> findAll() {

        return repository.findAll();
    }
Run Code Online (Sandbox Code Playgroud)

并得到了这个例外

org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TypeMismatchException: Provided id of the wrong type for class it.besmart.db_eipo.persistence.model.Object. Expected: class java.lang.Integer, got …
Run Code Online (Sandbox Code Playgroud)

mysql spring-data-jpa

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

Spring security - 当身份验证为空时该怎么办

我正在使用 Spring Security 来管理我的 Web 应用程序中的身份验证。使用它,我可以根据用户名管理对某些对象的访问。

因此,在我的 DAO 级别中,我有这个方法,它为我提供了用户的 Park 对象列表

public List<Park> findParkByUser(int offset) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        List<Park> parks = new ArrayList<Park>();
        try {
        if(auth != null){
            String name = auth.getName();
            User user = userService.findBySso(name);

        int userId = user.getId();
        Criteria criteria = createEntityCriteria();

            criteria.createAlias("users", "u");
            if(offset >= 0){
            criteria.add(Restrictions.eq("u.id", userId)).setFirstResult(offset).setMaxResults(elementsPerPage);
            }
            criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
            parks = (List<Park>) criteria.list();

        } else {

            logger.debug("Auth error");

        }
        } catch (NullPointerException e) {
            logger.error("Auth error",e);

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

现在的问题是,当会话超时或cookie过期时,我会得到一个nullauth。我想将用户重定向到登录页面,但我处于 DAO …

spring spring-security

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

Java Timer.schedule仅运行一次

我有一个TiimerTask,应该基于Timer.schedule运行。问题是,它仅在应用程序启动时运行一次...也许这有待解决,但我不明白是什么...

这是我的类,它扩展了TimerTask

public class ClientScheduler extends TimerTask {

    public String serverUrl = Start.getHost();
    public String append = "/client/checkVersion";
    public String numeroClient = null;
    public String actualVersion = null;
    public String filePrefix = "eparkclient-";
    public String fileSuffix = "-jar-with-dependencies.jar";
    private final Logger logger = Logger.getLogger(ClientScheduler.class);

    public ClientScheduler() {

    }

    @Override
    public void run() {



                logger.debug("Scheduler starts");
                String finalUrl = null;
                try {
                     numeroClient = PropertyConfig.getClientId();

                     actualVersion = PropertyConfig.getFirmwareVersion();
                     finalUrl = serverUrl + append + "?numeroClient=" + numeroClient;

                     HttpConnection http = new …
Run Code Online (Sandbox Code Playgroud)

java timertask

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

杰克逊(Jackson)无法读取文档:无法识别的令牌“ contactForm”:正在等待(“ true”,“ false”或“ null”)

我想将带有JQuery的POST请求发送到Spring Controller,但我不断从jquery收到此错误

Could not read document: Unrecognized token 'contactForm': was expecting ('true', 'false' or 'null')
 at [Source: java.io.PushbackInputStream@38220bcd; line: 1, column: 13]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'contactForm': was expecting ('true', 'false' or 'null')
 at [Source: java.io.PushbackInputStream@38220bcd; line: 1, column: 13]
Run Code Online (Sandbox Code Playgroud)

这是POST请求

$('#contactForm').on('submit', function(e){
        e.preventDefault();
        var contactForm = new Object;
        var firstName = $('#firstName').val();
        var lastName = $('#lastName').val();
        var email = $('#email').val();
        var message = $('#message').val();
        contactForm.firstName = firstName;
        contactForm.lastName = lastName;
        contactForm.email = email;
        contactForm.message = message;
        contactForm.accepted …
Run Code Online (Sandbox Code Playgroud)

jquery spring json

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

Spring Boot - 如何避免并发访问控制器

我们有一个Spring Boot应用程序,它链接到该领域的各种客户端.该应用程序具有一个控制器,该控制器从客户端调用并与DB和物理开关交互,以关闭或打开灯.

当两个或多个客户端访问服务器上的API时会出现问题,因为该方法会检查指示灯是打开还是关闭(在数据库上)以更改其状态.如果指示灯熄灭,并且2个客户端同时调用该服务,则第一个打开指示灯并更改数据库上的状态,但第二个访问指示灯也是如此,数据库上的状态为OFF但是第一个客户端已经调整了灯光,所以秒钟最终将其关闭以为打开它...也许我的解释有点不清楚,问题是:我可以告诉spring当时访问控制器一个请求吗?

感谢下面的答案,我们对切换开关的方法引入了悲观锁定,但我们继续从客户那里得到200状态......

我们正在使用spring boot + hibernate

现在控制器有悲观锁定的例外

  try {

                                String pinName = interruttore.getPinName();
                                // logger.debug("Sono nel nuovo ciclo di
                                // gestione interruttore");
                                if (!interruttore.isStato()) { // solo se
                                                                // l'interruttore
                                                                // è
                                                                // spento

                                    GpioPinDigitalOutput relePin = interruttore.getGpio()
                                            .provisionDigitalOutputPin(RaspiPin.getPinByName(pinName));
                                    interruttoreService.toggleSwitchNew(relePin, interruttore, lit);                                                            // accendo
                                    interruttore.getGpio().unprovisionPin(relePin);
                                }



                        } catch (GpioPinExistsException ge) {
                            logger.error("Gpio già esistente");
                        } catch (PessimisticLockingFailureException pe){
                            logger.error("Pessimistic Lock conflict", pe);
                            return new ResponseEntity<Sensoristica>(sensoristica, HttpStatus.CONFLICT);
                        }
Run Code Online (Sandbox Code Playgroud)

toggleSwitchNew 如下

@Override
@Transactional(isolation=Isolation.REPEATABLE_READ)
public void toggleSwitchNew(GpioPinDigitalOutput relePin, Interruttore interruttore, boolean …
Run Code Online (Sandbox Code Playgroud)

java spring

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

Vue js - 如何使用查询字符串路由请求

我有一个以这种方式制作的路由器视图对象

export default new Router({
  linkExactActiveClass: 'active', // active class for *exact* links.
  mode: 'history',
  routes: [
    {
      path: '/admin',
      name: 'dashboard',
      component: Dashboard
    },
    {
      path: '/company',
      name: 'company',
      component: ObjectList,
      props: {
        url: '/web/company',
        idColumn: 'companyId'
      }
    }
  ]
})
Run Code Online (Sandbox Code Playgroud)

当我点击 /company 链接时,路由器正确地将我发送到ObjectList组件

在这个页面中,我有一个以这种方式制作的简单分页组件

<template>
  <div class="overflow-auto">
    <b-pagination-nav
      align="center"
      :link-gen="linkGen"
      :number-of-pages="totalPages"
      use-router
    ></b-pagination-nav>
  </div>
</template>

<script>
export default {
  data() {
    return {
    };
  },
  name: "pagination",
  props: {
    current: Number,
    url: String,
    totalPages: Number
  }, …
Run Code Online (Sandbox Code Playgroud)

vue-router vuejs2

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

Tomcat 7 Maven插件-处理请求时捕获了I / O异常(java.net.SocketException):管道中断

我阅读了有关我的问题的所有问题,但都没有成功...我正在将与Maven的战争分配给我,我希望它可以在另一个IP上的tomcat服务器上使用。

我遵循了所有设置...

我的插件的POM

<plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
        <configuration>
            <url>http://192.168.3.67:8080/manager/text</url>
            <server>TomcatServer</server>
            <path>webapp</path>
        </configuration>
    </plugin>
Run Code Online (Sandbox Code Playgroud)

我的/conf/settings.xml for tomcat有

<server>
        <id>TomcatServer</id>
        <username>maven</username>
        <password>maven</password>
</server>
Run Code Online (Sandbox Code Playgroud)

并且tomcat-user.xml如下

<role rolename="manager-gui"/>
<role rolename="manager-script"/>
<user username="system" password="raspberry" roles="manager-gui"/>
<user username="maven" password="maven" roles="manager-script"/>
Run Code Online (Sandbox Code Playgroud)

当我尝试部署应用程序时,我得到了

[INFO] Deploying war to http://192.168.3.67:8080/manager/webapp  
Uploading: http://192.168.3.67:8080/manager/text/deploy?path=webapp
2472/14845 KB   
[INFO] I/O exception (java.net.SocketException) caught when processing request: Broken pipe
[INFO] Retrying request
Uploading: http://192.168.3.67:8080/manager/text/deploy?path=webapp
2384/14845 KB   
[INFO] I/O exception (java.net.SocketException) caught when processing request: Broken pipe
[INFO] Retrying request
Uploading: http://192.168.3.67:8080/manager/text/deploy?path=webapp
2398/14845 KB   
[INFO] I/O …
Run Code Online (Sandbox Code Playgroud)

java tomcat maven

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

Spring Hibernate MySql-无法添加外键约束

我有一个运行Mysql和Hibernate的Spring Boot应用程序。

启动它时,出现此错误

Unsuccessful: alter table SMARTPARK.illuminazione add constraint FK_4kmtr3q9e2hnaoutsxgahhm63 foreign key (id_interruttore) references SMARTPARK.interruttori (id_interruttore)
2016-05-05 08:46:35 ERROR SchemaUpdate:262 - Cannot add foreign key constraint
Run Code Online (Sandbox Code Playgroud)

我有两个表/实体

Illuminazione.java是(只是有趣的部分...)

@Entity
@Table(name = "illuminazione", catalog = "SMARTPARK")
public class Illuminazione {
    private int idilluminazione;
    private Interruttore interruttore;
    private Date dateTime;
    private Date lastDateTime;
    private boolean isLit;

    @ManyToOne
    @JoinColumn(name = "id_interruttore")
    public Interruttore getInterruttore() {
        return this.interruttore;
    }

    public void setInterruttore(Interruttore interruttore) {
        this.interruttore = interruttore;
    }
Run Code Online (Sandbox Code Playgroud)

在Interruttore.java中,我@OneToMany与Illuminazione 有关系

@Entity
@Table(name …
Run Code Online (Sandbox Code Playgroud)

mysql spring hibernate

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

Bootstrap datetimepicker - minDate 不是一个函数

我正在使用带引导程序的 datetimepicker。

一切顺利,然后我尝试使用 2 个日期时间选择器来选择一个日期间隔,但是当我尝试选择一个日期时,我进入了控制台

TypeError: $('#datetimepicker2').data("DateTimePicker").maxDate is not a function. (In '$('#datetimepicker2').data("DateTimePicker").maxDate(e.date)', '$('#datetimepicker2').data("DateTimePicker").maxDate' is undefined)
Run Code Online (Sandbox Code Playgroud)

我正在使用来自https://eonasdan.github.io/bootstrap-datetimepicker/ 的bootstrap-datetimepicker

(maxDate 也会出现一些错误)

这是我正在调用的脚本

$(function() {
    $('#datetimepicker2').datetimepicker({
        locale : 'it',
        format : 'DD/MM/YYYY HH:mm'
    });
    $('#datetimepicker3').datetimepicker({
        locale : 'it',
        format : 'DD/MM/YYYY HH:mm',
        useCurrent: false //Important! See issue #1075
    });
     $("#datetimepicker2").on("dp.change", function (e) {
         $('#datetimepicker3').data("DateTimePicker").minDate(e.date);
     });
     $("#datetimepicker3").on("dp.change", function (e) {
         $('#datetimepicker2').data("DateTimePicker").maxDate(e.date);
     });

});
Run Code Online (Sandbox Code Playgroud)

我错过了什么吗?

datetimepicker twitter-bootstrap

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

Hibernate - org.hibernate.hql.internal.ast.QuerySyntaxException:未映射客户端

我刚开始休眠,我正试图解决一些我无法理解的问题......

例如,我有这个查询

Query query = session.createQuery("from Client where clientId = "+clientId+")");
List result = query.list();
Run Code Online (Sandbox Code Playgroud)

我的Client.hbm.xml是

    <class name="it.besmart.models.Client" table="client" catalog="SMARTPARK">
        <id name="idClient" type="int">
            <column name="id_client" />
            <generator class="identity" />
        </id>
        <property name="nomeClient" type="string">
            <column name="nome_client" length="65535" not-null="true" />
        </property>
        <property name="numPosti" type="int">
            <column name="num_posti" not-null="true" />
        </property>
        <property name="numLuci" type="int">
            <column name="num_luci" not-null="true" />
        </property>
        <property name="inizioPosti" type="int">
            <column name="inizio_posti" not-null="true" />
        </property>
        <property name="inizioLuci" type="int">
            <column name="inizio_luci" not-null="true" />
        </property>
    </class>
</hibernate-mapping>
Run Code Online (Sandbox Code Playgroud)

DB上的表称为客户端,列为client_id

hibernate.cfg.xml中的映射是

<hibernate-configuration>
 <session-factory name="parkserver">
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> …
Run Code Online (Sandbox Code Playgroud)

java hibernate

0
推荐指数
1
解决办法
3669
查看次数

Spring oauth2授权代码授权 - Impossibile to reach/oauth/authorize

我正在尝试用授权代码流保护我的休息api,但我不明白为什么我收到消息:

User must be authenticated with Spring Security before authorization can be completed.
Run Code Online (Sandbox Code Playgroud)

我有一个具有User和Admin访问权限的应用程序的Web部分,以及带有2个不同授权的REST api部分,/ api/**授权代码和带有client_credentials的/ oauth2/**.

client_credential流程工作,但授权代码nope ...

所以,这是我的授权服务器配置

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authManager;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        endpoints.tokenStore(tokenStore()).authenticationManager(authManager);

    }

    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }

}
Run Code Online (Sandbox Code Playgroud)

这是我的资源服务器配置

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled=true) …
Run Code Online (Sandbox Code Playgroud)

spring spring-security spring-security-oauth2

0
推荐指数
1
解决办法
2947
查看次数