• spring mvc 异常处理和session添加


    在controller中进行设置

    package com.stone.controller;
    
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.validation.Valid;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.validation.BindingResult;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    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.ResponseBody;
    import org.springframework.web.bind.annotation.SessionAttributes;
    import org.springframework.web.servlet.view.InternalResourceViewResolver;
    
    import com.stone.model.User;
    
    @Controller
    @RequestMapping("/user")
    @SessionAttributes("loginUser")//需要处理的session
    public class UserController {
    
        private final static Map<String, User> users = new HashMap<String, User>();
    
        public UserController() {
            users.put("ldh", new User("ldh", "刘德华", "123", "123@123.com"));
            users.put("zxy", new User("zxy", "张学友", "123", "123@123.com"));
            users.put("gfc", new User("gfc", "郭富城", "123", "123@123.com"));
            users.put("lm", new User("lm", "黎明", "123", "123@123.com"));
        }
    
        @RequestMapping("/users")
        public String list(Model model) {
            model.addAttribute("users", users);
            return "user/list";
        }
    
        
        @RequestMapping(value = "/login", method = RequestMethod.GET)
        public String login() {
            return "user/login";
        }
    
        @RequestMapping(value = "/login", method = RequestMethod.POST)
        public String login(String username, String password, Model model) {
            if (!users.containsKey(username)) {
                throw new RuntimeException("用户名不存在!");
            }
            if (!password.equals(users.get(username).getPassword())) {
                throw new RuntimeException("用户密码不正确");
            }
            // 进行session的设置
            model.addAttribute("loginUser", users.get(username));
            return "redirect:/user/users/";
        }
            //进行异常处理
        @ExceptionHandler(value = { RuntimeException.class })
        public String handlerException(Exception ex, HttpServletRequest req) {
            req.setAttribute("ex", ex);
            return "error";
        }
    }
  • 相关阅读:
    Oracle序列更新
    ssh服务器终端乱码
    iTerm2常用的快捷键
    原来 Set 集合也可以排序
    Java 单例
    java后台技术
    网易考拉规则引擎平台架构设计与实践
    HBase最佳实践(好文推荐)
    如何通俗的解释云
    写的不错的一篇云数据库的文章
  • 原文地址:https://www.cnblogs.com/stono/p/4513966.html
Copyright © 2020-2023  润新知