RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-227526

Nick's questions

Martin Hope
Nick
Asked: 2020-05-17 20:06:14 +0000 UTC

为什么需要双击选择表格中的一行?

  • 0

大家好。我有一个页面,上面有一个包含客户姓名的下拉列表。当一个客户被选中时,一个表格被动态加载(使用 ajax),其中包含该客户的配置。

在此处输入图像描述

通过单击相应的行进行配置的选择: 在此处输入图像描述

当表格超过 5 行时,它将滚动,即 有一个滑块(表中的最大行数是五)。当表格超过五行时,它会更改其样式:

在此处输入图像描述

为什么会发生这种情况我不知道。如果我们单击表格中的任何行(表格超过 5 行)或通常在页面上的任何区域,首先下拉列表将散焦,然后(或更早)表格将更改其样式: 在此处输入图像描述

因此,要在超过 5 行的表格中选择配置,您必须双击。(需要一键选择)

js代码:

function changeCustomerName(customerName) {
        getConfigurationsForSpecifiedCustomer(customerName);
    }

function createTableForConfiguration(data){
    fillTable(data);
    $('#configurationTable').show();
}

function fillTable(data){
    $('#tableBody').empty();
    data.forEach(function(item) {
        $('#tableBody').append(
            '<tr>' +
            '<td style="display:none">' +
            item.id +
            '</td>' +
            '<td>' +
            item.name +
            '</td>' +
            '</tr>'
        )
    });
}

function getConfigurationsForSpecifiedCustomer(customerName) {
    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "/getConfigurationsForSpecifiedCustomer",
        data: JSON.stringify(customerName),
        dataType: 'json',
        success: function(response) {
            createTableForConfiguration(response);
        },
        error: function(e){
            // alert('Error from getConfigurationsForSpecifiedCustomer' + e);
            console.log('Error from getConfigurationsForSpecifiedCustomer' + e);
            $('#configurationTable').hide();
        }
    });
}

$(document).ready(function(){

$('#secondTable').on("click", '#tableBody tr', function(){
    var selected = $(this).hasClass("highlight");
    $("#tableBody tr").removeClass("highlight");
    if(!selected)
        $(this).addClass("highlight");
    $("[name='configuration']").val($(this).context.children[0].innerText);
});

});

html:

 <div id="table" class="scroll">
            <table id="secondTable" class ="tableBorder">
                <thead>
                <tr>
                    <th style="display:none">id</th>
                    <th>Configuration Name</th>
                    <th>Product Name</th>
                    <th>Product Version</th>
                    <th>Solution Build</th>
                    <th>Customer Name</th>
                    <th>GP Code</th>
                    <th>Oracle DB Version</th>
                    <th>Configuration Version</th>
                </tr>
                </thead>
                <tbody id="tableBody">
                </tbody>
            </table>
        </div>

风格:

body {
    font-size: 1em;
}

h1 {
    font-size: 2em;
}

table.tableBorder {
    width: 100%;
    border: 1px solid black;
    border-collapse: collapse;
}

table.tableBorder th, table.tableBorder td {
    padding: 4px 3px;
    border: 1px solid black;
}

.scroll{
    width: 100%;
    max-height: 150px;
    overflow: auto;
}

.highlight { background-color: grey; }

阿贾克斯回应:

在此处输入图像描述

Ajax 响应返回一个列表。配置是一个 POJO 类。我注意到,如果您传递一个列表,那么一切正常,表格的样式不会改变,也不需要双击。

响应 ajax 调用的控制器:

@RequestMapping(value = "/getConfigurationsForSpecifiedCustomer", method=RequestMethod.POST)
public @ResponseBody List<Configuration> getConfigurationsForSpecifiedCustomer(@RequestBody String customer) {
    if("".equals(customer))
        return null;
    return configurationService.getConfigurationsOfCustomer(customer.replaceAll("\"", ""));
}

配置类:

@Builder
@AllArgsConstructor
@Data
public class Configuration {
    private final int version;
    private final UUID id;
    private final String name;
    private final String author;
    private final String comment;
    private Map<String, String> customerInfo;
    private Collection<Rule> rules;
    private Collection<WhiteListItem> whiteList;
}

jQuery版本^

/static/js/jquery-2.1.1.min.js

这里有什么问题我无法理解,大脑拒绝。我会很高兴你的建议。

javascript
  • 1 个回答
  • 10 Views
Martin Hope
Nick
Asked: 2020-06-02 22:01:07 +0000 UTC

vmware和无线网络配置

  • 1

您具有以下网络配置在此处输入图像描述。在这个图中,所有组件都是虚拟机:Snort - ubuntu 14,用户 - ubuntu 14,受害者 - ubuntu 14,黑客 - kali linux。我需要在 snort 和 hacker 机器之间建立无线连接。请告知如何做到这一点。所以我可以以某种方式配置 snort 机器作为路由器并允许它通过以太网和无线连接连接到它?

vmware
  • 1 个回答
  • 10 Views
Martin Hope
Nick
Asked: 2020-05-09 13:10:02 +0000 UTC

如何使一对一的无向映射休眠

  • 0

我有以下数据库模式: 在此处输入图像描述

从图中可以看出,Card_balance指的是Cards。我需要 Cards 实体在切换到 ORM 时有一个 Card_balance 字段,并且有一个单向关系,其中 Cards 指的是 Card_balance。我试着这样做:

  @Entity
@Table(name = "CARDS")
public class Cards implements Serializable {

    @Id
    @Column(name = "CARD_ID")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CARDS_SEQ")
    @SequenceGenerator(name = "CARDS_SEQ", sequenceName = "CARDS_SEQ")
    private Long cardId;

    ...

    @OneToOne
    @JoinColumn(name="CARD_ID", nullable = false)
    private CardBalance cardBalance;

并将 cardId 字段添加到 card_balance

 @Entity
@Table(name = "CARD_BALANCE")
public class CardBalance {

    @Id
    @Column(name = "BALANCE_ID")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CARD_BALANCE_SEQ")
    @SequenceGenerator(name = "CARD_BALANCE_SEQ", sequenceName = "CARD_BALANCE_SEQ")
    private Long balanceId;

    ...

    @Column(name="CARD_ID")
    private Long cardId;

但是这种方法不起作用,因为从卡片数据库中提取时,我得到以下信息: 在此处输入图像描述

请告诉我哪里错了。

java
  • 1 个回答
  • 10 Views
Martin Hope
Nick
Asked: 2020-05-02 14:11:29 +0000 UTC

为什么延迟初始化在休眠中不起作用

  • 0

惰性初始化在休眠中不起作用。这是课程

@Entity
@Table(name = "PERSONS")
public class Persons {

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "person", cascade = CascadeType.REMOVE)
    public List<Cards> cards = new ArrayList<Cards>();

    public Persons() {
    }
    //getters and setters

}

卡片类

@Entity
@Table(name = "CARDS")
public class Cards {

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "card", cascade = CascadeType.REMOVE)
    @JsonManagedReference
    public List<BalanceHist> balanceHists = new ArrayList<BalanceHist>();

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "card", cascade = CascadeType.REMOVE)
    @JsonManagedReference
    public List<Events> events = new ArrayList<Events>();

//getters and setters
}

如果你看看前面的 json 中有什么,你可以看到以下内容: 在此处输入图像描述

正如您从图片中看到的那样,该方法有效,但我应该得到一个错误,因为如果您查看在 DAO 中获取用户的方法:

@Repository
@Transactional
public class PersonRepository extends AbstractRepository<Persons> {
    public PersonRepository() {
        super(Persons.class);
    }

    @Override
    public List<Persons> getAll() {
        return super.getAll();
    }
}

DAO 的父类:

@Repository
@Transactional
public abstract class AbstractRepository<Entity> {

    private Class persistentClass;

    public AbstractRepository(Class persistentClass) {
        this.persistentClass = persistentClass;
    }



    @Autowired
    private SessionFactory sessionFactory;

    protected Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    public List<Entity> getAll() {
        return getSession().createCriteria(persistentClass).list();
    }

}

也就是说,我没有在任何地方初始化标有注释的实体字段@OneToMany(fetch = FetchType.LAZY, mappedBy = "card", cascade = CascadeType.REMOVE),并且根据想法,我应该在访问它们时收到错误,但由于某种原因,我立即从数据库中获取了所有依赖项。告诉我可能是什么问题。

        @Repository
    @Transactional
    public class PersonRepository extends AbstractRepository<Persons> {
        public PersonRepository() {
            super(Persons.class);
        }


        @Autowired
        private SessionFactory sessionFactory;
        protected Session getSession() {
            return sessionFactory.getCurrentSession();
        }

        @Override
        public List<Persons> getAll() {
    //        Criteria criteria = createEntityCriteria();
    //        criteria.addOrder(Order.asc("personId"));
    //        return criteria.list();
            List<Persons> personsList =  getSession().createCriteria(Persons.class).list();
            for (Persons persons : personsList) {
                Hibernate.initialize(persons.getCards());
            }
            return personsList;
        }
}


    @Service
@Transactional
public class PersonService {

    public List<Persons> getUsers() {
        List<Persons> personList = new ArrayList<>();
        for (Persons person : personRepository.getAll()) {
            if (person.getRole().getRoleType().equals("USER"))
                personList.add(person);
        }
        return personList;
    }

}



   @Controller
@RequestMapping("/")
public class AppController {

    @RequestMapping(value = {"/", "/home"}, method = RequestMethod.GET)
    public String homePage(ModelMap model) {
        model.addAttribute("greeting", "Welcome to the first page of the project");

        System.out.println("ASASAS");
        for (Persons person: personService.getUsers()) {
            for (Cards card:person.getCards()) {
                System.out.println("TROLOLO");
                System.out.println(card.getCardName());
                if (Const.DEBUG) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(card.getCardName());
                    }
                }
            }
        }
        return "welcome";

    }
}
java
  • 1 个回答
  • 10 Views
Martin Hope
Nick
Asked: 2020-04-18 03:37:47 +0000 UTC

单击 2 次按钮后发送 jsona

  • 1

告诉我为什么在第二次点击按钮后发送 jsona。函数代码:

    function saveChanges() {
    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");
    $("#changeForm").ready(function () {

        $("#changeForm").find("input").each(function () {
            massChanges.push(this.value);
        })
        massChanges.push($( "#cities option:selected" ).text());
        console.log(massChanges);
    })
    $.ajax({
        type: "POST",
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        url: "/admin/saveChanges",
        // headers : {
        //     'Accept' : 'application/json',
        //     'Content-Type' : 'application/json'
        // },
        data: JSON.stringify(massChanges), // Note it is important
        beforeSend: function (xhr) {
            // here it is
            xhr.setRequestHeader(header, token);
        },
        success: function (result) {
            console.log("SUCCESS: ", result);
            alert("success" + result);
        }
//                                ,
//                                error: function (result) {
//                                    console.log("ERROR: ", result);
//                                    alert("Error" + result);
//                                }
    });
    massChanges = [];
}

控制器代码:

    @RequestMapping(value = "/admin/saveChanges", method = RequestMethod.POST)
public
@ResponseBody
String saveChanges(@RequestBody List<String> list) {

    System.out.println("SAVECHANGES");
    for (String s:list) {
        System.out.println(s);
    }
    System.out.println("Success changes");
    return "Success changes";
}

第一次按下后在此处输入图像描述

控制台是空的: 在此处输入图像描述

我还忘了提到按钮是使用脚本生成的,也就是说,它是动态加载的。删除按钮以类似的方式工作,但由于某种原因它第一次工作,它也是静态的。一般来说,我会很高兴有任何帮助,调试没有帮助(

changeForm 如何坚持:

function editUser() {
// массив для взятий информации о пользователе из таблицы
    var userInfo = [];

    // $("table").find("tr").each(function () {
    //
    //     if($(this).is(":visible")){
    //         alert("success");
    //         console.log("SUCCESS")
    //     }
    // })
    var count = 0;
    // здесь надо передать одно значение, то есть один ряд с инфой о пользователе иначе кинуть alert
    $("table").find("tr").each(function () {
        if ($(this).find("input").is(":checked")) {
            count++;
        }
    });
    if (count <= 1) {
        $("table").find("tr").each(function () {
            if ($(this).find("input").is(":checked")) {
                $(this).find("td").each(function () {
                    userInfo.push(this.innerHTML);
                })
                return false;
            }
            count = 0;
        });
    }
    else {
        alert("Выбрано больше одного значения");
        if ($("#tableForUser").length != 0) {
            getUsers();
            count = 0;
            return;
        }
        if ($("#tableForOwners").length != 0) {
            getOwners();
            count = 0;
            return;
        }
        if ($("#tableForDrivers").length != 0) {
            getDrivers();
            count = 0;
            return;
        }
    }
    console.log(userInfo);
    // alert("SUCCESS");
    getCities();
    console.log(listCities);

    $("#head").children().remove();
    var trHTML = '';
    trHTML += '<form id="changeForm" class="form-horizontal" role="form">' +
        '<input id="inputID" class="form-control" type="text" style="visibility:hidden">' +
        '<div class="form-group">' +
        '<label class="col-lg-3 control-label">Ник:</label>' +
        '<div class="col-lg-8">' +
        '<input id="inputNick" class="form-control" type="text">' +
        '</div>' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="col-lg-3 control-label">Имя:</label>' +
        '<div class="col-lg-8">' +
        '<input id="inputFirstname" class="form-control" type="text">' +
        '</div>' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="col-lg-3 control-label">Фамилия:</label>' +
        '<div class="col-lg-8">' +
        '<input id="inputLastname" class="form-control" type="text" >' +
        '</div>' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="col-lg-3 control-label">Мобильный телефон:</label>' +
        '<div class="col-lg-8">' +
        '<input id="inputMobile"class="form-control" type="text">' +
        '</div>' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="col-lg-3 control-label">Электронная почта:</label>' +
        '<div class="col-lg-8">' +
        '<input id="inputEmail" class="form-control" type="text">' +
        '</div>' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="col-lg-3 control-label">Город:</label>' +
        '<div class="col-lg-8">' +
        '<div class="ui-select">' +
        '<select id="cities" class="form-control">' +
        // '<option value="Hawaii">(GMT-10:00) Hawaii</option>' +
        // '<option value="Alaska">(GMT-09:00) Alaska</option>' +
        // '<option value="Pacific Time (US &amp; Canada)">(GMT-08:00) Pacific Time (US &amp; Canada)</option>' +
        // '<option value="Arizona">(GMT-07:00) Arizona</option>' +
        // '<option value="Mountain Time (US &amp; Canada)">(GMT-07:00) Mountain Time (US &amp; Canada)</option>' +
        // '<option value="Central Time (US &amp; Canada)" selected="selected">(GMT-06:00) Central Time (US &amp; Canada)</option>' +
        // '<option value="Eastern Time (US &amp; Canada)">(GMT-05:00) Eastern Time (US &amp; Canada)</option>' +
        // '<option value="Indiana (East)">(GMT-05:00) Indiana (East)</option>' +
        '</select>' +
        '</div>' +
        '</div>' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="col-md-3 control-label">Пароль:</label>' +
        '<div class="col-md-8">' +
        '<input id="inputPassword1" class="form-control" type="password">' +
        '</div>' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="col-md-3 control-label">Подтвердите пароль:</label>' +
        '<div class="col-md-8">' +
        '<input id="inputPassword2" class="form-control" type="password">' +
        '</div>' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="col-md-3 control-label"></label>' +
        '<div class="col-md-8">' +
        // '<input type="button" class="btn btn-primary" onclick="saveChanges();" value="Save Changes">'
        '<button type="button" class="btn btn-primary" onclick="saveChanges();">Сохранить</button><br>' +
        '<span></span>' +
        '<input type="reset" class="btn btn-default" value="Cancel">' +
        '</div>' +
        '</div>' +
        '</form>';
    $("#head").append(trHTML);
    if (userInfo[1] == null) {
        alert("Выберите пользователя для редактирования");
        $("#head").children().remove();
    }
    else {
        //Записываем индекс
        // massChanges.push(userInfo[0]);
        // console.log(massChanges);
        document.getElementById("inputID").value = userInfo[0];
        document.getElementById("inputNick").value = userInfo[1];
        document.getElementById("inputFirstname").value = userInfo[2];
        document.getElementById("inputLastname").value = userInfo[3];
        document.getElementById("inputMobile").value = userInfo[4];
        document.getElementById("inputEmail").value = userInfo[5];
        document.getElementById("cities").value = userInfo[6];
        document.getElementById("inputPassword1").value = userInfo[7];
        document.getElementById("inputPassword2").value = userInfo[7];

        userInfo = [];
    }
}
javascript
  • 1 个回答
  • 10 Views
Martin Hope
Nick
Asked: 2020-04-15 20:36:07 +0000 UTC

生成jquery表后运行函数

  • 0

我有一个通过以下 ajax 请求在单击按钮时生成的表:

function getDrivers() {
  $.ajax({
    type: "GET",
    url: "/admin/getDrivers",
    datatype: "json",
    success: function(response) {
      $("#head").children().remove();
      var trHTML = '';
      trHTML += '<h2>' + "Водители" + '</h2>' +
        '<div class="table-responsive">' +
        '<table id="dataTable" class="table table-hover">' +
        '<thead><tr><th>' +
        'Ник' + '</th><th>' +
        "Имя" + '</th><th>' +
        "Фамилия" + '</th><th>' +
        "Мобильный телефон" + '</th><th>' +
        "Электронная почта" + '</th><th>' +
        "Город" + '</th><th>' +
        '</th></tr></thead><tbody>'

      ;

      $.each(response, function(i, item) {
        trHTML += '<tr><td>' +
          item.nickname + '</td><td>' +
          item.firstName + '</td><td>' +
          item.lastName + '</td><td>' +
          item.mobileNumber + '</td><td>' +
          item.email + '</td><td>' +
          item.city.cityName + '</td><td>' +
          '<input type="checkbox" value=""/>' +
          '</td></tr>';
      });
      trHTML += '</tbody>' + '</table>' + '</div>';
      $("#head").append(trHTML);
    },
    error: function() {
      alert("error")
    }
  });
}

所有这些东西都附加到下一个块div:

<div id="head" class="col-sm-9 offset-sm-3 col-md-10 offset-md-2 pt-3">

接下来,我需要为该表创建一个上下文菜单。我使用以下脚本制作此菜单:

$("#dataTable").bootstrapTable({
  rowStyle: "rowStyle",
  contextMenu: '#context-menu',
  contextMenuTrigger: 'right',
  onClickRow: function(row, $el) {
    $("#dataTable").find(".success").removeClass('success');
    $el.addClass('success');
  },
  onContextMenuItem: function(row, $el) {
    if ($el.data("item") == "edit") {
      alert("Edit: " + row.itemid + ' ' + row.name + ' ' + row.price);
    } else if ($el.data("item") == "delete") {
      alert("Delete: " + row.itemid + ' ' + row.name + ' ' + row.price);
    } else if ($el.data("item") == "action1") {
      alert("Action1: " + row.itemid + ' ' + row.name + ' ' + row.price);
    } else if ($el.data("item") == "action2") {
      alert("Action2: " + row.itemid + ' ' + row.name + ' ' + row.price);
    }
  }
});

因此,此菜单不适用于单击按钮时生成的表格,但如果表格是静态的,则可以。请告诉我如何解决这个问题。我尝试通过$("#dataTable").ready(скрипт контекстного меню)它没有用。

javascript
  • 1 个回答
  • 10 Views
Martin Hope
Nick
Asked: 2020-04-10 14:13:59 +0000 UTC

JSF 与 Spring MVC 的交互

  • 0

大家下午好。对是否可以使用一堆 JSF + Spring MVC 的问题感兴趣。如果是这样,那么我对视图如何与模型相关联的问题很感兴趣,因为 JSF 和 Spring MVC 具有不同的上下文。我将不胜感激(最好带有注释)。

java
  • 1 个回答
  • 10 Views
Martin Hope
Nick
Asked: 2020-04-07 16:01:00 +0000 UTC

如何在 SpringSecurity 中将用户数据写入日志文件

  • 0

大家下午好。对他进入SpringSecurity所连接的MVC应用程序时如何将用户数据写入日志文件的问题感兴趣。对于注册页面,我将用户数据写入如下:在页面控制器中,我创建了一个记录器,并在 saveUser 方法中将用户信息写入日志文件,如下所示。

@Controller
@RequestMapping("/registration")
public class RegistrationController {

    private static final Logger logger = Logger.getLogger(RegistrationController.class.getName());

    @Autowired
    PersonService personService;

    @Autowired
    CityService cityService;

    @Autowired
    MessageSource messageSource;

    @Autowired
    RoleService roleService;

    @RequestMapping(method = RequestMethod.GET)
    public String renderRegistration(ModelMap model) {
        Persons person = new Persons();

        model.addAttribute("userForm", person);
        model.addAttribute("edit", false);
        model.addAttribute("loggedinuser", getPrincipal());
        return "registration";
    }

    @RequestMapping(value = "/newUser", method = RequestMethod.POST)
    public String saveUser(@Valid @ModelAttribute("userForm") Persons person, BindingResult result,
                           ModelMap model) {

        List<FieldError> errors = new ArrayList<>();

        if (result.hasErrors()) {
            return "errorPage";
        }

        if (person.getNickname().isEmpty()) {
            FieldError nicknameError = new FieldError("person", "nickname", messageSource.getMessage("NotEmpty.person.nickname", new String[]{person.getNickname()}, Locale.getDefault()));
            errors.add(nicknameError);
        }

        if (!personService.isPersonsNicknameUnique(person.getPersonId(), person.getNickname())) {
            FieldError nicknameUniqError = new FieldError("person", "nickname", messageSource.getMessage("non.unique.nickname", new String[]{person.getNickname()}, Locale.getDefault()));
            errors.add(nicknameUniqError);
        }


        if (person.getPassword().isEmpty()) {
            FieldError passwordError = new FieldError("person", "password", messageSource.getMessage("NotEmpty.person.password", new String[]{person.getNickname()}, Locale.getDefault()));
            errors.add(passwordError);
        }

        if (person.getFirstName().isEmpty()) {
            FieldError firstNameError = new FieldError("person", "firstName", messageSource.getMessage("NotEmpty.person.firstName", new String[]{person.getNickname()}, Locale.getDefault()));
            errors.add(firstNameError);
        }

        if (person.getLastName().isEmpty()) {
            FieldError lastNameError = new FieldError("person", "lastName", messageSource.getMessage("NotEmpty.person.lastName", new String[]{person.getNickname()}, Locale.getDefault()));
            errors.add(lastNameError);
        }

        if (person.getEmail().isEmpty()) {
            FieldError emailError = new FieldError("person", "email", messageSource.getMessage("NotEmpty.person.email", new String[]{person.getNickname()}, Locale.getDefault()));
            errors.add(emailError);
        }

        if (person.getCity().equals(null)) {
            FieldError cityError = new FieldError("person", "city", messageSource.getMessage("NotEmpty.person.city", new String[]{person.getNickname()}, Locale.getDefault()));
            errors.add(cityError);
        }
        if (!errors.isEmpty()) {

            for (FieldError error : errors) {
                result.addError(error);
            }
            return "registration";
        }
//        person.setRole(roleService.findByType("USER"));
        personService.savePerson(person);

        if (Const.DEBUG) {
            if (logger.isDebugEnabled()) {
                logger.debug("person: id-" + person.getPersonId() +
                        " Nickname-" + person.getNickname() +
                        " Password-" + person.getPassword() +
                        " Lastname-" + person.getLastName() +
                        " FirstName-" + person.getFirstName() +
                        " Email-" + person.getEmail() +
                        " City-" + person.getCity().getCityName() +
                        " MobileNumber-" + person.getMobileNumber());
            }
        }

        return "success";
    }

    @ModelAttribute("rollers")
    public List<Rollers> getRollers() { return roleService.findAll();}

    @ModelAttribute("cities")
    public List<Cities> initializeCities() {
        return cityService.getAll();
    }

    private String getPrincipal() {
        String userName = null;
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (principal instanceof UserDetails) {
            userName = ((UserDetails) principal).getUsername();
        } else {
            userName = principal.toString();
        }
        return userName;
    }
}

我需要在用户登录时做类似的操作,但是由于我连接了SpringSecurity,它处理了POST方法,最后我不明白如何将用户数据写入文件。PS:代码不要骂我,我知道不是很好)

试图这样做:

   @Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    public static final Logger logger = Logger.getLogger(CustomSuccessHandler.class.getName());

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException {
        String targetUrl = determineTargetUrl(authentication);

        if (response.isCommitted()) {
            System.out.println("Can't redirect");
            return;
        }

//        String userName;
//        Object principal = authentication.getPrincipal();
//        if (principal instanceof UserDetails) {
//            userName = ((UserDetails) principal).getUsername();
//        } else {
//            userName = principal.toString();
//        }
//        if (Const.DEBUG) {
//            if (logger.isDebugEnabled()) {
                logger.debug("person: Nickname-" + authentication.getPrincipal().toString());
                logger.debug("person: Nickname-");
//            }
//        }

        redirectStrategy.sendRedirect(request, response, targetUrl);
    }

    /*
     * This method extracts the roles of currently logged-in user and returns
     * appropriate URL according to his/her role.
     */
    protected String determineTargetUrl(Authentication authentication) {
        String url = "";

        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        // для одной роли
        GrantedAuthority auth = authorities.iterator().next();
        String role = auth.getAuthority();


        // для нескольких ролей
//        List<String> roles = new ArrayList<String>();
//        for (GrantedAuthority a : authorities) {
//            roles.add(a.getAuthority());
//        }

        switch (role) {
            case "ROLE_USER":
                url = "/user";
                break;
            case "ROLE_DRIVER":
                url = "/driver";
                break;
            case "ROLE_OWNER":
                url = "/owner";
                break;
            case "ROLE_ADMIN":
                url = "/admin";
                break;
            default:
                url = "/accessDenied";
        }
        return url;
    }



    public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
        this.redirectStrategy = redirectStrategy;
    }

    protected RedirectStrategy getRedirectStrategy() {
        return redirectStrategy;
    }
}

在安全配置中:

    @Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{

//
//    @Autowired
//    LoginSuccess loginSuccess;

    @Autowired
    CustomSuccessHandler customSuccessHandler;

    @Autowired
    @Qualifier("customUserDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/user/**").hasRole("USER")
                .antMatchers("/driver/**").hasRole("DRIVER")
                .antMatchers("/owner/**").hasRole("OWNER")
                .and().formLogin().loginPage("/login").successHandler(customSuccessHandler)
//                .successHandler(loginSuccess)
                .usernameParameter("ssoId").passwordParameter("password")
                .and().csrf()
                .and().exceptionHandling().accessDeniedPage("/Access_Denied");
//        http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
    }

    @Bean
    public AuthenticationTrustResolver getAuthenticationTrustResolver() {
        return new AuthenticationTrustResolverImpl();
    }


}

也没有帮助。也通过 onAuthenticationSuccess 尝试过 - 也没有用。

log4j 设置:

    log4j.logger.com.team.mvc.configuration.CustomSuccessHandler=INFO, CustomSuccessHandler
log4j.additivity.com.team.mvc.configuration.CustomSuccessHandler=false
log4j.appender.CustomSuccessHandler=org.apache.log4j.RollingFileAppender
log4j.appender.CustomSuccessHandler.File=E:\\LoginSuccess.out
log4j.appender.CustomSuccessHandler.layout=org.apache.log4j.PatternLayout
log4j.appender.CustomSuccessHandler.layout.ConversionPattern=[%p] %d{yyyy-MM-dd hh:mm:ss} %C:%M:%L - %m%n

而当我尝试通过过滤器时,我无法获取安全上下文,getPrincipal 方法抛出了 NullPointException。这次没有异常,但也没有任何内容写入日志。

spring-security
  • 1 个回答
  • 10 Views
Martin Hope
Nick
Asked: 2020-04-04 15:02:12 +0000 UTC

限制对 servlet 应用程序中页面的访问

  • 0

大家好。伙计们可以举例说明在 servlet 应用程序中限制对页面的访问。因此,当我以用户身份登录时,我无法使用 /admin url 转到管理页面。

这是登录 servlet 代码:

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        req.getRequestDispatcher("index.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter pw = response.getWriter();
        response.setContentType("text/html");

        String user = request.getParameter("userName");
        String pass = request.getParameter("userPassword");

        if (user.equals("admin") && pass.equals("admin")) {
            response.sendRedirect("/admin");
        }
        if (user.equals("user") && pass.equals("user")) {
            response.sendRedirect("/user");
        }
        if (user.equals("page3") && pass.equals("page3")) {
            response.sendRedirect("page3.jsp");
        }
        else
            pw.println("Login Failed...!");
        pw.close();

    }


}
servlet
  • 1 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5