SpringMVC学习第三天

1.登陆页面的实现 

2.异常的处理

3.静态文件的处理



login.jsp

<%@ page language= "java" contentType ="text/html; charset=utf-8"
    pageEncoding="utf-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title> 用户列表</title >
</head>
<body>
    <form action="user/login" method="post" >
         用户名: <input type="text" name="userName" /><br/>
         密码: <input type="password" name="password" /><br />
          <input type="submit" value="登陆"/>
    </form >
</body>
</html>




UserController

package controller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import model.User;
import model.UserException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/user" )
public class UserController
{   
    private Map<String,User> users = new HashMap<String,User>();
    public UserController() {
          users.put("haha" ,new User("haha","haha" ,"哈哈" ,"sss" ));
          users.put("hehe" ,new User("hehe","hehe" ,"呵呵 " ,"sss" ));
          users.put("nimei" ,new User("nimei","nimei" ,"你妹" ,"sss" ));
          users.put("zhangquandan" ,new User("zhangquandan" ,"张全蛋" ,"哈哈" ,"sss" ));
    }
    
    /**
     * 遍历用户
     * @param model
     * @return
     */
    @RequestMapping(value= "/users",method=RequestMethod.GET)
    public String list(Model model){
          model.addAttribute("users" ,users );
          return "user/list" ;
    }
    //链接到add页面时是GET请求,会访问这段代码
//    @RequestMapping(value="/add",method=RequestMethod.GET)
//  public String add(Model model){
//       //开启modelDriven
//       model.addAttribute(new User());
//       return "user/add";
//  }
    
    /**
     * 进入添加页面
     * @param user
     * @return
     */
    @RequestMapping(value= "/add",method=RequestMethod.GET)
    public String add( @ModelAttribute("user" ) User user){
          return "user/add" ;
    }
    
    /**
     * 添加用户
     * @param user
     * @param br
     * @return
     */
    //在具体添加用户时,是post请求时,就访问以下代码
    @RequestMapping(value= "/add",method=RequestMethod.POST)
    public String add( @Validated User user,BindingResult br ){//一定要紧跟validated之后写验证结果类
          if(br .hasErrors())
         {
              //如果有错误直接返回页面
              return "user/add" ;
         }
          users.put(user .getUserName(), user);
          //UrlBasedViewResolver接口
          return "redirect:/user/users" ;
    }
    
    /**
     * 查看用户详细信息
     * @param userName
     * @param model
     * @return
     */
    @RequestMapping(value= "/{userName}",method=RequestMethod.GET)
    public String show( @PathVariable String userName,Model model )
    {
          model.addAttribute(users .get(userName));
          return "user/show" ;
    }
    
    /**
     * 进入修改页面
     * @param userName
     * @param model
     * @return
     */
    @RequestMapping(value= "/{userName}/update",method=RequestMethod.GET)
    public String update( @PathVariable String userName,Model model )
    {
          model.addAttribute(users .get(userName));
          return "user/update" ;
    }
    
    /**
     * 修改用户数据
     * @param user
     * @param userName
     * @param br
     * @return
     */
    @RequestMapping(value= "/{userName}/update",method=RequestMethod.POST)
    public String udpate( @PathVariable String userName,@Validated User user,BindingResult br)
    {
          if(br .hasErrors())
         {
              return "user/update" ;
         }
          users.put(userName ,user );
          return "redirect:/user/users" ;
    }
    @RequestMapping(value= "/{userName}/delete",method=RequestMethod.GET)
    public String delete( @PathVariable String userName)
    {
          users.remove(userName );
          return "redirect:/user/users" ;
    }
    
    @RequestMapping(value= "/login",method=RequestMethod.POST)
    public String login(String userName,String password,HttpSession session )
    {
          if(!users .containsKey(userName))
         {
              throw new UserException("用户名不存在 ");
         }
         User u = users.get(userName );
          if(!u .getPassword().equals(password))
         {
              throw new UserException("用户密码不正确");
         }
          session.setAttribute("loginUser" , u );
         
          return "redirect:/user/users" ;
    }
    
    /**
     * 局部异常处理,仅仅只能处理这个控制器的中的异常
     *
     */ /*
    @ExceptionHandler(value={UserException.class})
    public String handlerException(UserException e,HttpServletRequest request)
    {
         request.setAttribute("e", e);
         return "user/error";
    }*/
}




UserException

package model;
public class UserException extends RuntimeException
{
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    public UserException() {
          super();
          // TODO Auto-generated constructor stub
    }
    public UserException(String message, Throwable cause,
              boolean enableSuppression , boolean writableStackTrace) {
          super(message , cause , enableSuppression , writableStackTrace);
          // TODO Auto-generated constructor stub
    }
    public UserException(String message , Throwable cause) {
          super(message , cause );
          // TODO Auto-generated constructor stub
    }
    public UserException(String message) {
          super(message );
          // TODO Auto-generated constructor stub
    }
    public UserException(Throwable cause) {
          super(cause );
          // TODO Auto-generated constructor stub
    }
    
}




User

package model;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
public class User
{
    private String userName;
    private String password;
    private String nickName;
    private String email;
    @NotEmpty(message= "用户名不能为空" )
    public String getUserName() {
          return userName ;
    }
    public void setUserName(String userName ) {
          this.userName = userName;
    }
    @Size(min=1,max=10,message= "密码的长度应该在1和10之间" )
    public String getPassword() {
          return password ;
    }
    public void setPassword(String password ) {
          this.password = password;
    }
    public String getNickName() {
          return nickName ;
    }
    public void setNickName(String nickName ) {
          this.nickName = nickName;
    }
    @Email(message= "邮箱的格式不正确" )
    public String getEmail() {
          return email ;
    }
    public void setEmail(String email ) {
          this.email = email;
    }
    public User() {
    }
    public User(String userName, String password , String nickName, String email ) {
          this.userName = userName;
          this.password = password;
          this.nickName = nickName;
          this.email = email;
    }
    
}



error.jsp

<%@ page language= "java" contentType ="text/html; charset=utf-8"
    pageEncoding="utf-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></ title>
</head>
<body>
    <h1 >${e.message }</ h1>
</body>
</html>




error1.jsp

<%@ page language= "java" contentType ="text/html; charset=utf-8"
    pageEncoding="utf-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></ title>
</head>
<body>
    <h1 >${exception }</ h1>
</body>
</html>



list.jsp

<%@ page language= "java" contentType ="text/html; charset=utf-8"
    pageEncoding="utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title> 用户列表</title >
<link rel="stylesheet" href=" <%=request.getContextPath() %>/resources/css/main.css" type="text/css" >
</head>
<body>
<a href="add" >添加</ a>-->${loginUser.userName }
<br/>
    <c:forEach var="user" items=" ${users }">
         ${user.value.userName }  --
         ${user.value.password } --
          <a href=" ${user.value.userName }">${user.value.nickName } </a> --
         ${user.value.email }
          <a href=" ${user.value.userName }/update">修改 </a>
          <a href=" ${user.value.userName }/delete">删除 </a>
          <br/>
    </c:forEach >
</body>
</html>



main.css

*{
     font-size:15px ;
    color:red;
}




spring-servlet.xml

<?xml version="1.0" encoding= "UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <context:component-scan base-package="controller" />
    <mvc:annotation-driven />
    <!-- 将静态文件指定到某个特殊文件夹中统一处理 -->
    <mvc:resources location= "/resources/" mapping="/resources/**" ></mvc:resources>
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
    </bean >
    
    <!-- 全局异常处理 -->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" >
          <property name="exceptionMappings" >
              <props>
                  <prop key="model.UserException" >user/error1</ prop>
              </props>
          </property>
    </bean >
</beans>


源码:http://pan.baidu.com/s/1jGHuIRc

你可能感兴趣的:(SpringMVC学习第三天)