zoukankan      html  css  js  c++  java
  • 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";
        }
    }
  • 相关阅读:
    第一章 数据库基本操作
    Linux卸载jdk
    Jenkins Jboss的启动
    Jenkins启动脚本
    Linux SVN 创建项目
    测试工程师到底是干啥的?测试工程师转开发有多大希望?
    如何评审功能测试用例?
    Maven上传
    持续集成
    jquery获取所有checked的value
  • 原文地址:https://www.cnblogs.com/stono/p/4513966.html
Copyright © 2011-2022 走看看