【问题标题】:Spring MVC -JSP-How Can I Get Session Atribute I JSP?Spring MVC -JSP-如何获取会话属性JSP?
【发布时间】:2017-09-14 04:21:57
【问题描述】:

嗨,我正在使用 spring mvc 和 jsp 编写基本的个人博客管理系统。我想制作页面信息/错误通知。如果想要的博客不存在,则将错误消息添加到 httpSesion 并且错误消息将出现在 jsp 中页面。

我有 NotificationMessage 模型,NotificationService 接口和它的实现如下。

NotificationMessage 类

package com.fatih.blogproject.model;

public class NotificationMessage {


private NotificationMessageType type;
private String text;

public NotificationMessage(NotificationMessageType type, String text) {
    this.type = type;
    this.text = text;
}

public NotificationMessageType getType() {
    return type;
}

public String getText() {
    return text;
}
}

NotificationService 接口

package com.fatih.blogproject.service;

public interface NotifiacationService {
void addInfoMessage(String msg);
void addErrorMessage(String msg);
}

接口的实现

package com.fatih.blogproject.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fatih.blogproject.model.NotificationMessage;
import com.fatih.blogproject.model.NotificationMessageType;
import com.fatih.blogproject.service.NotifiacationService;

@Service
public class NotificationServiceImpl implements NotifiacationService{

//Bu servis bilgi ve error mesajlarını HTTPSession içinde uzun süre tutmaya 
göre ayarlı olacak.
//HTTPSession içinde veriler key value çifti olarak tututlurlar.

 public static final String NOTIFY_MSG_SESSION_KEY = 
 "siteNotificationMessages";

    @Autowired
    private HttpSession httpSession;



@Override
public void addInfoMessage(String msg) {
    addNotificationMessage(NotificationMessageType.INFO, msg);

}

@Override
public void addErrorMessage(String msg) {
    addNotificationMessage(NotificationMessageType.ERROR, msg);

}

private void addNotificationMessage(NotificationMessageType type , String msg){

    List<NotificationMessage> notifyMessage = (List<NotificationMessage>)httpSession.getAttribute(NOTIFY_MSG_SESSION_KEY);

    if(notifyMessage==null){
        notifyMessage=new ArrayList<NotificationMessage>();
    }
    notifyMessage.add(new NotificationMessage(type, msg));

    httpSession.setAttribute(NOTIFY_MSG_SESSION_KEY, notifyMessage);



}

}

HomeController

package com.fatih.blogproject.controller;



import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

import java.util.Date;
import com.fatih.blogproject.model.Post;
import com.fatih.blogproject.service.NotifiacationService;
import com.fatih.blogproject.service.PostService;

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


private PostService postService;
private NotifiacationService notifyService;

@Autowired
public HomeController(PostService postService , NotifiacationService notifyService) {
    this.notifyService=notifyService;
    this.postService=postService;
}




@RequestMapping(method=RequestMethod.GET)
public String home(Model model){

    List<Post> latest5Posts=postService.findLatest5();



    model.addAttribute("latest5Posts",latest5Posts);

    List<Post> latest3Posts=latest5Posts.stream()
            .limit(3)
            .collect(Collectors.toList());

    model.addAttribute("latest3Posts", latest3Posts);

    return "index";
}


@RequestMapping("/post/{id}")
public String post(@PathVariable("id") Long id  ,Model model){

    Post post=postService.findById(id);

    if(post==null){
        notifyService.addErrorMessage(id+"id li post bulunamadı");

        return "redirect:/";
    }

    DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
    String date = formatter.format(post.getDate());


    model.addAttribute("post", post);
    model.addAttribute("date",date);
    return "post";
}




}

我想访问通知消息的会话值并在 index.jsp 中查看它

我该怎么做?

我在索引页面中尝试此代码

<%=request.getSession().getAttribute("siteNotificationMessages") %>

但是这段代码在索引页面中给了我如下输出

[com.fatih.blogproject.model.NotificationMessage@1474487e]

注意:我从下面链接的教程中看到了这个项目。

tutorial-link

教程使用Thymeleaf代替jsp。教程中的thymeleaf代码如下

 <ul id="messages" th:with="notifyMessages=${session[T(blog.services
      .NotificationServiceImpl).NOTIFY_MSG_SESSION_KEY]}">
  <li th:each="msg : ${notifyMessages}" th:text="${msg.text}"
       th:class="${#strings.toLowerCase(msg.type)}">
  </li>
  <span th:if="${notifyMessages}" th:remove="all" th:text="${session.remove(
      T(blog.services.NotificationServiceImpl).NOTIFY_MSG_SESSION_KEY)}">
 </span>

</ul>

如何将此thymeleaf 代码转换为jsp?

感谢一切。

【问题讨论】:

    标签: spring jsp session model-view-controller thymeleaf


    【解决方案1】:

    NotificationMessage 实例被返回,因此在页面上调用对象的toString() 方法。您需要将返回的对象强制转换为 NotificationMessage 并使用可用的方法。

    <%=((NotificationMessage)request.getSession().getAttribute("siteNotificationMessages")).getMsg() %>
    

    <%=((NotificationMessage)request.getSession().getAttribute("siteNotificationMessages")).getType() %>
    

    取决于您真正需要展示的内容。

    【讨论】:

    • 是的。如果未设置消息,您将拥有 NPE。只需添加空检查。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    • 1970-01-01
    • 2017-11-20
    相关资源
    最近更新 更多