码迷,mamicode.com
首页 > 编程语言 > 详细

spring mvc 异常处理和session添加

时间:2015-05-19 12:39:40      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

在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";
    }
}

 

spring mvc 异常处理和session添加

标签:

原文地址:http://www.cnblogs.com/stono/p/4513966.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!