小编vig*_*age的帖子

在Java中实现忘记密码功能

我目前正在Java项目中实现忘记密码功能.我的方法是,

  1. 用户单击忘记密码链接.
  2. 在忘记密码页面中,系统提示用户输入他/她已注册到系统的电子邮件地址.
  3. 包含重置密码的链接的电子邮件将在上面的步骤中发送到给定的电子邮件地址.
  4. 用户单击该链接,他/她将被重定向到页面(重置密码),用户可以在其中输入新密码.
  5. 在"重置密码"页面中,"电子邮件地址"字段自动填写,无法更改.
  6. 然后用户输入他的新密码,并更新与数据库中的电子邮件地址相关的字段.

虽然我已经限制了email address重置密码页面中的字段进行编辑(只读字段),但任何人都可以更改浏览器地址栏中的URL并更改电子邮件地址字段.

如何限制每个用户更改重置密码页面中的电子邮件地址?

java change-password forgot-password password-recovery

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

我应该明确发送刷新令牌以获得新的访问令牌 - JWT

在我的应用程序中,当用户成功登录时,我返回访问令牌和刷新令牌.访问和刷新令牌的到期时间分别设置为10和40分钟.(我应该对这些值做更多的研究.这只是为了测试)

我使用了下面文章中描述的实现

http://www.svlada.com/jwt-token-authentication-with-spring-boot/

假设我在登录10分钟后向服务器发出请求.由于访问令牌已过期,我收到401错误响应.

但是,作为初学者,我发现很难理解是否需要显式发送刷新令牌以获取新的访问令牌.如果我应该这样做,怎么做?我应该发送刷新令牌作为什么?标题?

或者,当我的请求被服务器拒绝,因为访问令牌已过期,刷新令牌本身是否会自动向服务器发送请求以获取新的访问令牌?

我发现很难从网上找到的资源中理解刷新令牌行为的本质.请在这些问题上澄清我.

spring-security access-token jwt spring-boot refresh-token

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

所需的请求部分'文件'不存在 - Angular2 Post请求

我试图使用Angular2和SpringBoot完成我的文件上传功能.我可以证明我的文件上传的java代码工作正常,因为我已经使用Postman成功测试了它.

但是,当从Angular2前端发送文件时,我收到HTTP 400响应说Required request part 'file' is not present.

这是我从Angular2发送POST请求的方式.

savePhoto(photoToSave: File) {

    let formData: FormData = new FormData();
    formData.append('file', photoToSave);

    // this will be used to add headers to the requests conditionally later using Custom Request Options
    this._globals.setRequestFrom("save-photo");


    let savedPath = this._http
        .post(this._endpointUrl + "save-photo", formData)
        .map(
        res => {
            return res.json();
        }
        )
        .catch(handleError);

    return savedPath;

}
Run Code Online (Sandbox Code Playgroud)

请注意,我编写了一个CustomRequestOptions扩展的类,BaseRequestOptions以便附加Authorization标头和Content Type标头.内容类型标题将有条件地添加.

以下是代码.

@Injectable()
export class CustomRequestOptions extends BaseRequestOptions {
    constructor(private _globals: Globals) {
        super(); …
Run Code Online (Sandbox Code Playgroud)

spring file-upload http spring-boot angular

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

Form.reset() - Angular2后,表格无效

我在Angular2应用程序中有一个基于模板的表单供用户注册.在那里,我将表单实例传递给Submit函数,并在完成对服务器的异步调用后重置from.

以下是表格中的一些重要部分.

<form class="form-horizontal" #f="ngForm" novalidate (ngSubmit)="onSignUpFormSubmit(f.value, f.valid, newUserCreateForm, $event)" #newUserCreateForm="ngForm">

    <div class="form-group">
        <label class="control-label col-sm-3" for="first-name">First Name:</label>
        <div class="col-sm-9">
            <input type="text" class="form-control" placeholder="Your First Name" name="firstName" [(ngModel)]="_userCreateForm.firstName"
                #firstName="ngModel" required>
            <small [hidden]="firstName.valid || (firstName.pristine && !f.submitted)" class="text-danger">
               First Name is required !
            </small>
        </div>
    </div>

    .......

    .......

    <div class="form-group">
        <div class="col-sm-offset-3 col-sm-12">
            <button type="submit" class="btn btn-default">Submit</button>
            <button type="reset" class="btn btn-link">Reset</button>
        </div>
    </div>

</form>
Run Code Online (Sandbox Code Playgroud)

在我的组件文件中,我编写了以下函数.

onSignUpFormSubmit(model: UserCreateForm, isValid: boolean, form: FormGroup, event:Event) {

    event.preventDefault();

    if (isValid) {
        this._userEmail = model.email;

        this._authService.signUp(this._userCreateForm).subscribe( …
Run Code Online (Sandbox Code Playgroud)

forms validation angular

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

使用 HttpServletRequestWrapper 进行复制后缺少必需的请求正文

在我的项目中,我有一组 api 调用,应通过某些常见验证集进行过滤。在这种情况下,我必须在请求到达 REST 控制器之前拦截该请求,读取请求正文,进行验证,如果请求通过验证,则将其传递给控制器​​。

由于HttpServletRequest不能多次反序列化,因此我使用 aHttpServletRequestWrapper来复制实际请求。我使用它制作的副本进行验证。

下面是拦截请求的配置类。

public class InterceptorConfig extends WebMvcConfigurerAdapter {

     @Autowired     
     CustomInterceptor customInterceptor;

     @Override  
     public void addInterceptors(InterceptorRegistry registry) { 
        registry.addInterceptor(customInterceptor).addPathPatterns("/signup/**");

     }   
}
Run Code Online (Sandbox Code Playgroud)

这是我在类中扩展的preHandle方法CustomInterceptorHandlerInterceptorAdaptor

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

    ServletRequest copiedRequest = new HttpRequestWrapper(request);

    Map<String, Object> jsonMap = mapper.readValue(copiedRequest.getInputStream(), Map.class);

    if(jsonMap.containsKey("userId")){
        long userId = jsonMap.get("userId");
        MyClass myObject= myAutowiredService.getMyObject(userId);
        if(myObject == null){
            response.setStatus(HttpStatus.SC_NOT_ACCEPTABLE);
            return false;
        } 
        // some more validations which end up …
Run Code Online (Sandbox Code Playgroud)

java json spring-mvc httprequest spring-boot

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

处理 204-HTTP Observable 中的无内容响应 - Angular2

在我的 Angular2 应用程序中,我从 REST API 获取响应并操作它们以便在用户界面中显示它们。

我根据以下教程编写了我的应用程序。

https://www.barbarianmeetscoding.com/blog/2016/04/02/getting-started-with-angular-2-step-by-step-6-sumption-real-data-with-http/

这是我从服务器获取响应的方法

getTendersByCategory(categoryName: string){

        console.log("get tenders by category "+categoryName);

        let tendersByCategory = this._http
            .get(this._endpointUrl + "tender/get-by-category-name/" + categoryName)
            .map(mapTenders)
            .catch(handleError);

        return tendersByCategory;

}
Run Code Online (Sandbox Code Playgroud)

以下函数用于操作响应

function mapTenders(response: Response): Tender[] {
    console.log('tender.service.ts -> mapTenders');

    /*if(response.status == 204){
        console.log("response = 204 - No content in response");
        return null;
    }*/

    return response.json().map(toTender);
}


function toTender(r: any): Tender {
    console.log('tender.service.ts -> toTender');
    let tender = <Tender>({
        id: r.id,
        name: r.name,
        publisher: r.publisher,
    });
    return tender;
}

function handleError(error: …
Run Code Online (Sandbox Code Playgroud)

angular2-services angular2-http angular2-observables angular

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

User、UserRole 的数据库设计 - 多对多关系

在我的项目中,我有一个 User 实体和一个 UserRole 实体。根据我的数据库设计,一个用户可以扮演多个角色,一个角色可以关联多个用户。我在系统中的用户角色是 USER 和 ADMIN。

需要将用户角色存储在表中,并且当用户在其相关表中持久化时需要引用它们。

但是,根据我实现的代码,每次将用户插入数据库时​​,记录也会插入到用户角色表中。我需要的是将数据插入到用户表和连接表中。

这些是我的实体。

用户:

@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false, updatable= false)
    private Long id;

    @Column(name = "email", nullable = false, unique = true)
    private String email;

    @Column(name = "first_name", nullable = false)
    private String firstName;

    @Column(name = "last_name", nullable = false)
    private String lastName;

    @Column(name = "password_hash", nullable = false)
    private String passwordHash;

    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(name = …
Run Code Online (Sandbox Code Playgroud)

java many-to-many hibernate jpa entitymanager

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

@Transactional 注解是否避免并发访问业务层方法

我对@Transactional 注释在业务/服务层的使用有点不清楚。

我的问题是,当在业务层中与ISOLATION_SERIALIZABLE一起使用时,@Transactional注解是否保证不允许对特定方法进行并发访问?

@Transactional(isolation = Isolation.SERIALIZABLE)
public void businessMethod() {

    // calls subBusinessMethod
    subBusinessMethod();
    ---------------
    ---------------
    ---------------

}
Run Code Online (Sandbox Code Playgroud)

想象一下subBusinessMethod调用 DAO 层来做一些数据库事务。调用之后的代码执行(可能会有更多的 db 调用)subBusinessMethod取决于subBusinessMethod.

我需要确保对 的后续调用businessMethod不应该调用 dao 层从/向数据库读/写,而不知道先前调用的 db 表发生了什么。已在业务逻辑中添加了必需的验证。

首先,我的方法有效吗?如果是这样,我是否以正确的方式使用它。?

java spring hibernate transactions transactional

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

无法访问net.sf.ehcache.CacheManager,找不到net.sf.ehcache.CacheManager的类文件

我一直在使用我的项目中实现一些缓存EhCache.我已将以下依赖项添加到我的pom.xml中

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.8.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>4.3.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.ehcache/ehcache -->
<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>3.3.1</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

请注意第三个依赖项EhCache.在我在网上找到的所有教程中,组ID都不同.我改变组ID的原因是它被移动到了org.ehcache.

我的classpath中有以下ehcache.xml文件.

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd"
         updateCheck="true"
         monitoring="autodetect"
         dynamicConfig="true">

    <diskStore path="java.io.tmpdir"/>

    <cache name="cardTypes"
           maxEntriesLocalHeap="100"
           maxEntriesLocalDisk="1000"
           eternal="false"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="localTempSwap"/>
    </cache>

</ehcache>
Run Code Online (Sandbox Code Playgroud)

以下是我的配置文件.

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.cache.CacheManager;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.core.io.ClassPathResource;

@EnableCaching
@Configuration
public class CacheConfig {

    @Bean
    public CacheManager …
Run Code Online (Sandbox Code Playgroud)

terracotta ehcache maven spring-boot spring-cache

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

每个步骤都有单独组件的角度材质步进器 - ExpressionChangedAfterItHasBeenCheckedError

我有一个材料步进器,步进器的每个步骤都有表格。在那里,每个步骤都应该由与其关联的表单控制。

尽管这个问题已经在 SO 中提出,但这些问题的答案并不能解决我的问题。因此我才问。

父 HTML

<mat-horizontal-stepper linear #stepper>
    <mat-step [stepControl]="frmStepOne">
        <ng-template matStepLabel>Step One Details</ng-template>
        <app-first-step #stepOne></app-first-step>
    </mat-step>
    <mat-step [stepControl]="frmStepTwo">
        <ng-template matStepLabel>Step Two Details</ng-template>
        <app-second-step #stepTwo></app-second-step>
    </mat-step>
</mat-horizontal-stepper> 
Run Code Online (Sandbox Code Playgroud)

在我的父组件中,我有以下内容。

@ViewChild('stepOne') stepOneComponent: FirstStepComponent;
@ViewChild('stepTwo') stepTwoComponent: SecondStepComponent;


get frmStepOne() {
    return this.stepOneComponent ? this.stepOneComponent.frmStepOne : null;
}

get frmStepTwo() {
    return this.stepTwoComponent ? this.stepTwoComponent.frmStepTwo : null;
}
Run Code Online (Sandbox Code Playgroud)

我的孩子类组件

frmStepOne: FormGroup;

constructor(private formBuilder: FormBuilder) {

    this.frmStepOne = this.formBuilder.group({
      name: ['', Validators.required]
    });
}
Run Code Online (Sandbox Code Playgroud)

子类 HTML

<mat-card>

  <form [formGroup]="frmStepOne">

    <mat-form-field>
      <input matInput formControlName="name" matInput …
Run Code Online (Sandbox Code Playgroud)

typescript angular-material angular angular-material-stepper angular9

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

Jquery change()方法无法正常工作

我需要在我的html页面的一个输入文本字段中设置日期,然后在设置日期后调用脚本并将新的日期值分配给另一个文本字段.使用第一个日期值计算新的日期值.我用$("#id").change()它.但它不像我预期的那样有效.这是我的代码.

<html>
    <head>
        <title>my file</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

        <!-- Load jQuery JS -->
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
        <!-- Load jQuery UI Main JS  -->
        <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
        <script>
            $(function() {
                $("#firstDate,#lastDate").datepicker({dateFormat: 'dd-mm-yy'});
            });
        </script>

        <script>
            $(document).ready(function() {
                $("#firstDate").change(function(event) {
                    event.preventDefault();
                    var initialDate = ("#firstDate").val();
                    var totDate = initialDate;
                    var dateArray = totDate.split("-");

                    var dateObj = new Date(dateArray[2], dateArray[1] - 1, dateArray[0]);
                    dateObj.setDate(dateObj.getDate() + 14);
                    totDate = (dateObj.getDate() + 14) + "-" + dateObj.getMonth() + …
Run Code Online (Sandbox Code Playgroud)

javascript jquery jquery-ui jquery-ui-datepicker

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

将jasper导出为pdf时,NoClassDefFoundError:com/itextpdf/text/DocumentException

我创建了一个jasper报告,现在我需要将该报告导出为pdf格式化.这是我的代码.

        // compiles jrxml
        JasperCompileManager.compileReportToFile(reportName + ".jrxml");
        // fills compiled report with parameters and a connection
        JasperPrint print = JasperFillManager.fillReport(reportName + ".jasper", parameters, connection);

        // to view the report
        //JasperViewer.viewReport(print, false);

        // export repor to pdf
        JasperExportManager.exportReportToPdfFile(print, "fromXml.pdf");
Run Code Online (Sandbox Code Playgroud)

当我使用查看报告时JasperViewer,它工作正常.但是当我将报告导出为pdf格式时,它会给我以下异常.

Exception in thread "main" java.lang.NoClassDefFoundError: com/itextpdf/text/DocumentException
Run Code Online (Sandbox Code Playgroud)

但我已将iText jar放入我的库中.

在此输入图像描述

但有一点,我之前有另一个版本的iTextjar.它给了我同样的例外.我认为它的版本可能存在一些问题.(我遵循了一个教程,所以我添加了与教程中使用的相同的jar替换我使用的新jar).

但问题仍然存在.我认为可能是现在的问题(问题的接受答案).但我不知道如何解决它.我删除了整个库,并iText使用本教程使用的jar 再次添加它.但我没有运气.

你能帮我解决这个问题吗?谢谢!

java jasper-reports itext

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