• springmvc学习日志三


    一、文件的上传

    1.首先在lib中添加相应的jar包

     2.建立jsp页面,表单必须是post提交,编码必须是multipart/form-data,文件上传文本框必须起名

    <body>
        <!-- 文件上传是上传到本地服务器下 而数据库中存放的是 图片的路径-->
        <form action="upload" method="post" enctype="multipart/form-data">
            请选择上传的文件:<input type="file" name="myfile"><br>
            <input type="submit" value="上传"/>
        </form>
    </body>

     3.在springmvc的配置文件中必须配置文件上传解析器

        <!-- 配置文件上传解析器 -->    
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
                <!-- 设置文件上传的大小  字节 -->
                <property name="maxUploadSize" value="9999999"></property>
        </bean>
        

    4.在UploadController处理代码,接受页面传过来的文件

    @Controller
    public class UploadController {
        
        @RequestMapping("upload")  //HttpServletRequest:作用是为获取上传文件的路径
        public String upload(MultipartFile myfile,HttpServletRequest request) { //把你上传的文件封装到MultipartFile中
            //1.获取文件上传真实保存的路径
            //一般情况下上传到服务器的目录下,获取网站根目录
            String path=request.getServletContext().getRealPath("/upload");
            System.out.println(path);
            //2.创建一个文件对象
            File file=new File(path);
            if(!file.exists()) { //该路径不存在
                file.mkdirs();
            }
            //3.获取文件名
            String name=System.currentTimeMillis()+myfile.getOriginalFilename();
            
            File targetFile=new File(path+"/"+name);
            
            try {
                //把文件写入到指定的目录下
                FileUtils.writeByteArrayToFile(targetFile, myfile.getBytes());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return "redirect:/index.jsp";
        }
    }

     二、springmvc的拦截器设置(拦截的都是控制层的地址)

    1.先创建一个Controller类

    @Controller
    @RequestMapping("user") 
    @SessionAttributes(names= {"name","password","registername","registerpass"}) //键名叫:name保存的作用域为session
    public class UserController {
        @RequestMapping("tologin") 
        public ModelAndView tologin() { 
            ModelAndView mv=new ModelAndView();
            mv.setViewName("login");
            return mv;
        }
        @RequestMapping("login") 
        public String login(String name,String password,Model model,HttpSession session) {
            System.out.println("登录");
            
            if(session.getAttribute("registername").equals(name)&&"123456".equals(password)) {
                model.addAttribute("name", name);
                model.addAttribute("password", password);
                return "forward:list";
            }else {
                return "login";
            }
            
        }
        
        @RequestMapping("toregister") 
        public ModelAndView toregister() {
            ModelAndView mv=new ModelAndView();
            mv.setViewName("register");
            return mv;
        }
        @RequestMapping("register") 
        public String register(String name,String password,Model model) {
            if(name!=null&&password!=null) {
                model.addAttribute("registername", name);
                model.addAttribute("registerpass", password);
                return "login";
            }else {
                return "register";
            }
        }
        @RequestMapping("list")
        public ModelAndView list() {
            ModelAndView mv=new ModelAndView("list");
            User user1=new User("张三","123456",20);
            User user2=new User("李四","123456",20);
            User user3=new User("王五","123456",20);
            
            List<User> list=new ArrayList<>();
            list.add(user1);
            list.add(user2);
            list.add(user3);
            mv.addObject("list",list);
            return mv;
        }
        @RequestMapping("delete") 
        public String delete(HttpServletRequest request) {
            
            return "redirect:/index.jsp";
        }
    }

    2.创建一个类实现接口HandlerInterceptor,并重写接口中的方法

    public class MyInterceptor implements HandlerInterceptor {
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3)
                throws Exception {
            System.out.println("请求处理后执行该方法");
    
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3)
                throws Exception {
            System.out.println("==============");
    
        }
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
            System.out.println("处理请求等价于doFilter方法");
            Object name=request.getSession().getAttribute("name");
            if(name!=null) {
                return true;//如果返回true表示允许通过
            }else {
                response.sendRedirect("../login.jsp");
                return false;
            }
        }
    
    }

    3.把创建的类配置到springmvc的配置文件中

    <!-- 配置拦截器 -->
        <mvc:interceptors>
            <!-- 可配置多个拦截器 -->
            <mvc:interceptor>
                <!-- **表示user下所有的子目录以及请求地址,哪些请求路径经过拦截器 -->
                <mvc:mapping path="/user/**"/>
                <!-- 不包括要拦截的请求路径 -->
                <mvc:exclude-mapping path="/user/login"/>
                <mvc:exclude-mapping path="/user/tologin"/>
                <mvc:exclude-mapping path="/user/register"/>
                <mvc:exclude-mapping path="/user/toregister"/>
                <bean class="com.zhiyou100.xz.interceptor.MyInterceptor"></bean>
            </mvc:interceptor>
        </mvc:interceptors>

     三、数据校验(后台校验 hibernate validate)

    1.引入相应的jar包

     2.在相应的实体类中加入注解

    public class User {
          @NotEmpty(message="用户名不能为空") //提示的错误信息
          private String name;
          @Length(min=6,max=12,message="密码的长度在【6~12】之间")
          private String password;
          @Pattern(regexp="^(?:[1-9][0-9]?|1[01][0-9]|120)$")
          private int age;
          @Pattern(regexp="^1[3456789]\d{9}$",message="手机格式不正确")
          private String phone;
    //要写get和set }

    3.在控制层接受参数时

    @RequestMapping("uregister")  
        public String uregister(@Valid User user,BindingResult br,Model model) { //validate在验证第一个失败后仍会继续验证
            //BindingResult br 把验证的所有的错误信息封装到BindingResult类中
            if(br.hasErrors()) { //判断有没有错误信息
                List<FieldError> fieldErrors=br.getFieldErrors();
                Map<String, Object> errorMsg=new HashMap<String, Object>();
                for(FieldError f:fieldErrors) {
                    //System.out.println(f.getField()+"---"+f.getDefaultMessage());
                    errorMsg.put(f.getField(), f.getDefaultMessage());
                }
                model.addAttribute("errorMsg", errorMsg);
                return "forward:../uregister.jsp";
            }
            return "list";
        }

    4.建立jsp页面,并进行输入验证

    <body>
           <form action="uregister" method="post" enctype="multipart/form-data">
            姓名:<input type="text" name="name" />${errorMsg.name }<br>
            密码:<input type="text" name="password" />${errorMsg.password }<br>
            手机号:<input type="text" name="phone" />${errorMsg.phone }<br>
            <input type="submit" value="注册"/>
        </form>
    </body>
  • 相关阅读:
    模拟电梯运行
    用户需求调研报告
    NABC需求分析
    大道至简---读书随笔3
    二维环形数组求最大子数组和
    结对开发之求最大数组溢出问题
    结对开发之环形数组
    结对开发之电梯调度
    我看“微软拼音”
    团队开发项目之典型用户和用户场景
  • 原文地址:https://www.cnblogs.com/sitian2050/p/11458898.html
Copyright © 2020-2023  润新知