SpringMVC学习第四天

1.文件上传

UserController


package controller;
import java.io.File;
import java.io.IOException;
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.apache.commons.io.FileUtils;
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;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.sun.org.glassfish.gmbal.ParameterNames;
@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
     * @throws IOException
     */ /* Zxcvb同,ASDFGHK/    //在具体添加用户时,是post请求时,就访问以下代码
    @RequestMapping(value="/add",method=RequestMethod.POST)
    public String add(@Validated User user,BindingResult br,MultipartFile image,HttpServletRequest request) throws IOException{//一定要紧跟validated之后写验证结果类
         if(br.hasErrors())
         {
             //如果有错误直接返回页面
             return "user/add";
         }
         String realPath = request.getSession().getServletContext().getRealPath("/resources/upload");
         System.out.println(realPath);
         File file = new File(realPath+"/"+image.getOriginalFilename());
        FileUtils.copyInputStreamToFile(image.getInputStream(), file);
        System.out.println(image.getName()+","+image.getOriginalFilename()+","+image.getContentType());
         users.put(user.getUserName(), user);
         //UrlBasedViewResolver接口
         return "redirect:/user/users";
    }*/
    
    
    /**
     * 添加用户  上传多个文件
     * @param user
     * @param br
     * @return
     * @throws IOException
     */
    //在具体添加用户时,是post请求时,就访问以下代码
    @RequestMapping(value= "/add",method=RequestMethod.POST)
    public String add( @Validated User user,BindingResult br ,@RequestParam ("images" ) MultipartFile[] images,HttpServletRequest request ) throws IOException{//一定要紧跟validated之后写验证结果类
          if(br .hasErrors())
         {
              //如果有错误直接返回页面
              return "user/add" ;
         }
         String realPath = request.getSession().getServletContext().getRealPath("/resources/upload");
         System. out.println(realPath );
          for(MultipartFile image : images)
         {
              if(image .isEmpty())
             {
                  continue;
             }
             File file = new File(realPath+"/" +image .getOriginalFilename());
             FileUtils. copyInputStreamToFile(image.getInputStream(), file);
         }
          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";
    }*/
}



add.jsp

<%@ page language= "java" contentType ="text/html; charset=utf-8"
    pageEncoding="utf-8" %>
<!-- the form tag -->
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!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>
    <!-- 此时没有写action,直接提交会提交给/add -->
    <form:form method="post" modelAttribute="user" enctype="multipart/form-data" >
         用户名: <form:input path="userName" /><form:errors path="userName" ></form:errors>< br/>
         密码: <form:password path="password" /><form:errors path="password" ></form:errors>< br/>
         真实姓名: <form:input path="nickName" /><br/>
         Email: <form:input path="email" /><form:errors path="email" ></form:errors>< br/>
<!--单个文件上传     image<input type="file" name="image"/><br/> -->
         image <input type="file" name="images" /><br/>
         image <input type="file" name="images" /><br/>
          <input type="submit" value="添加用户">
    </form:form >
</body>
</html>



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>
    
    <!-- 设置multipartResolver才能完成文件上传 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
          <property name="maxUploadSize" value="5000000" ></property>
    </bean >
    <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/1gdw2fvX

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