美文网首页
SpringMVC学习day-67:SpringMVC重定向和文

SpringMVC学习day-67:SpringMVC重定向和文

作者: 开源oo柒 | 来源:发表于2019-10-24 22:49 被阅读0次

    一、SpringMVC中的转发和重定向

    1.SpringMVC结合Ajax:

    • Springmvc结合Ajax的方式:

    方式一:使用传统方式做ajax的响应,将对象或数组转为json类型的字符串,再将json字符串发送给页面。

    • 代码示例:
      (1)ajax请求:
    <script type="text/javascript">
            $(function(){
            
                $("#inp").click(function(){
                    $.post("demo"," ",function(data){
                        alert(data.name);
                    })
                })
            })
        </script>
    

    (2)Controller:

    /***
         *
         * 使用传统方式做ajax 的响应
         *
         */
        @RequestMapping("demo")
        public void demo(String name, HttpServletResponse response) throws IOException {
            response.setContentType("text/html;charset=utf-8");
    
            User stu = new User("张三", "男", 20);
            // 响应
            String json = new Gson().toJson(stu);
            response.getWriter().print(json);
        }
    

    方式二:
    Springmvc 结合Ajax的使用 。方法的返回值可以直接是对象或者集合 ,需要在方法上添加@ResponseBody;响应给前台的数据直接是json对象。

    • 代码示例:
      (1)ajax请求:
    <script type="text/javascript">
            $(function(){
            
                $("#inp").click(function(){
                    $.post("demo2"," ",function(data){
                        alert(data.name);
                    })
                })
            })
        </script>
    

    (2)Controller:

    /**
         * Springmvc 结合Ajax的使用 注意:
         * A、方法的返回值可以直接是对象或者集合 ,需要在方法上添加@ResponseBody
         * B、响应给前台的数据直接是json对象
         *
         */
        @RequestMapping("demo2")
        @ResponseBody
        public User demo2() {
            User user = new User("李四", "女", 18);
            return user;
        }
    

    2.SpringMVC中的请求转发:

    • SpringMVC中请求转发的方式:

    请求转发方式一:
    返回值的字符串默认的就是请求转发:return "index.jsp";
    (1)代码示例:

    /**
         * 请求转发
         * 相对路径:相对于当前浏览器的地址../
         * 根路径:/--当前项目 
         * 绝对路径:不支持--最大范围就是当前的项目
         * @return
         */
        @RequestMapping("demo")
        public String demo() {
            return "/show.jsp";
        }
    

    请求转发方式二:使用ModelAndView中的setViewName方法:

    (1)代码示例:

    @RequestMapping("demo4")
        public ModelAndView demo4(){
            
            ModelAndView modelAndView = new ModelAndView();
            //转发
            modelAndView.setViewName("forward:/show.jsp");
            //转发二
            modelAndView.setView(new InternalResourceView("/show.jsp"));
            return modelAndView;
            
          }
    

    请求转发方式三:使用View接口的实现类InternalResourceView;

    (1)代码示例:

    @RequestMapping("demo3")
        public View demo3(){
            //转发
            View v = new InternalResourceView("/show.jsp");
          return v;
        }
    

    3.SpringMVC中的重定向:

    • SpringMVC中重定向实现方式:

    方式一:在返回的路径前添加redirect;

    (1)代码示例:

    /**
         * 重定向
         * 
         * return"redirect:index.jsp"
         * 相对路径:支持-相对于当前的浏览器地址
         * 根路径:/--当前项目
         * 绝对路径:http://www.baidu.com支持
         */
        @RequestMapping("demo2")
        public String demo2(){
            System.out.println("重定向!");
            return "redirect:http://www.baidu.com";
        }
    

    方式二:使用ModelAndView的setViewName方法

    (1)代码示例:

    @RequestMapping("demo4")
    public ModelAndView demo4(){
            
            ModelAndView modelAndView = new ModelAndView();
            //重定向
            modelAndView.setViewName("redirect:/show.jsp");
            //重定向二
            modelAndView.setView(new RedirectView("/springmvc03/show.jsp"));
            
            return modelAndView;
            
        }
    

    方式三:使用View接口的实现类RedirectView;

    (1)代码示例:

    @RequestMapping("demo3")
        public View demo3(){
        //重定向
        View v2 = new RedirectView("/springmvc03/show.jsp");
        return v;
        }
    

    4.SpringMVC中的自定义视图解析器

    • 为什么使用自定义视图解析器?

    我们平时的jsp文件都是放到web目录下,如果我们把jsp文件放到其它目录下,会发现没有办法访问,这样的设计的目的就是为了提高项目访问的安全性 。

    • 解决方法一:
    <!--转发到指定的页面中--!>     
    <jsp:forward page="WEB-INF/update.jsp"></jsp:forward>
    
    • 方式二:
       @RequestMapping("update")    
       public   String   demo1(){        
         return "/WEB-INF/update.jsp";    
       }
    
    • 方式三:

    自定义视图解析器:

    (1)在springmvc.xml中配置:

    <!--自定义视图解析器-->
    <bean id="view" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/"></property>
            <property name="suffix" value=".jsp"></property>
    </bean>
    

    5.SpringMVC中控制器的返回类型:

    (1)返回值类型为字符串:String(常用);
    (2)返回值类型为void:用于处理ajax请求;
    (3)返回值类型是Java对象(结合@RequestBody将java对象转换为json对象);
    (4)返回值为:View;

    (5)返回值为ModelAndView(常用);

    二、SpringMVC中的的文件上传

    1.SpringMVC中文件上传:

    • 实现简单文件的上传:
      (1)导包:

    spring-web-4.1.6.RELEASE.jar
    spring-webmvc-4.1.6.RELEASE.jar
    commons-io-2.2.jar
    commons-logging-1.1.1.jar
    aopalliance.jar
    asm-3.3.1.jar
    aspectjweaver.jar
    cglib-2.2.2.jar
    jackson-annotations-2.4.0.jar
    jackson-core-2.4.1.jar
    jackson-databind-2.4.1.jar
    javassist-3.17.1-GA.jar

    (2)在springmvc.xml中配置文件上传的对象:

    <!-- 创建上传文件的组件对象 -->
            <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    

    (3)创建save.jsp页面:

    <body>
        <%--
    
       必须注意:
         [A] 提交方式method="post"
    
         [B]enctype="multipart/form-data"  二进制流
    --%>
        <h3>文件上传</h3>
        <form action="fileUpload" enctype="multipart/form-data" method="post">
            <p>
                姓名:<input type="text" name="name" />
            </p>
            <p>
                分数:<input type="text" name="score" />
            </p>
            <p>
                年龄:<input type="text" name="age" />
            </p>
            <p>
                照片:<input type="file" name="fl" />
            </p>
            <span style="color: red;font-size: 14px">${error }</span>
            <p>
                <input type="submit" value="提交" />
            </p>
            <a href="http://localhost:8080/x_springmvc04/findAll">查询所有</a>
        </form>
    </body>
    

    (4)Controller中文件上传的代码:

    @Controller
    public class MyController {
    
    //System.out.println(fi.getName()+"---"+fi.getSize()+"---"+fi.getContentType()+"---"+fi.getOriginalFilename());
             //文件名
            String filename = fl.getOriginalFilename();
            //获取服务器的目录
            String lealPath = request.getServletContext().getRealPath("/upload");
            //创建文件的目录
            File file = new File(lealPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            //文件上传
            fl.transferTo(new File(file ,filename));
            return "index.jsp";
    }
    
    • 解决同名文件的文件覆盖:
            //相同图片名称覆盖
            String uuid = UUID.randomUUID().toString();
            String filename = uuid+substring;
    
    • 限制文件上传的大小:
      (1)方法一:
            //限制上传文件的大小
            if(fl.getSize()>40*1024){
                request.setAttribute("error", "上传文件不能超过20kb");
                return "save.jsp";
            }
    

    (2)在springmvc.xml中更改配置:

    <!-- 限制文件的大小 -->
     <property name="maxUploadSize" value="20000"></property>
    
    • 限制文件上传的类型:
            //获取文件的后缀
            String substring = fl.getOriginalFilename().substring(fl.getOriginalFilename().lastIndexOf("."));
    
            //判断文件的后缀
            if(!(".jpg".equals(substring)||".gif".equals(substring)||".png".equals(substring))){
                request.setAttribute("error", "上传文件必须是图片");
                return "save.jsp";
            }
    

    2.SpringMVC实现文件的上传:

    • 连接数据库实现文件的上传:
    (1)导包: 需要的jar包

    (2)数据库创建:

    create table student(
        id int(5) PRIMARY KEY auto_increment,
        name VARCHAR(50),
        age int(10),
        score DOUBLE(10),
        filename VARCHAR(80),
        filetype VARCHAR(50)
    )
    

    (3)实体类(生成getter和setter及构造方法):

        private int id;
        private String name;
        private int age;
        private double score;
        private String filename;
        private String filetype;
    

    (4)mapper下的接口和映射文件:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper
      PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
      "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
      <mapper namespace="com.zlw.mapper.StudentMapper">
            <insert id="save" parameterType="student">
            insert into student (name,age,score,filename,filetype) values(#{name},#{age},#{score},#{filename},#{filetype})
            </insert>
            <select id="findAll" resultType="student">
                select * from student
            </select>
      </mapper>
    

    (5)applicationContext-myBatis.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:aop="http://www.springframework.org/schema/aop"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd 
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
    
        <bean id="dataSource"
            class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
            <property name="url" value="jdbc:mysql://localhost:3306/user"></property>
            <property name="username" value="root"></property>
            <property name="password" value="root"></property>
        </bean>
    
        <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"></property>
            <property name="typeAliasesPackage" value="com.zlw.pojo"></property>
        </bean>
    
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="sqlSessionFactoryBeanName" value="factory"></property>
            <property name="basePackage" value="com.zlw.mapper"></property>
        </bean>
    
    </beans>
    

    (6)service下的接口及实现类:

    package com.zlw.service.impl;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import com.zlw.mapper.StudentMapper;
    import com.zlw.pojo.Student;
    import com.zlw.service.StudentService;
    
    @Service("studentService")
    public class StudentServiceImpl implements StudentService {
    
        @Autowired
        private StudentMapper studentMapper;
    
        @Override
        public int save(Student student) {
    
            return studentMapper.save(student);
        }
    
        @Override
        public List<Student> findAll() {
            return studentMapper.findAll();
        }
    }
    

    (7)配置文件扫Service注解包:

    <!-- 扫描注解包 -->
        <context:component-scan base-package="com.zlw.service"></context:component-scan>
    

    (8)测试:

    package com.zlw.test;
    
    import java.util.List;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import com.zlw.pojo.Student;
    import com.zlw.service.StudentService;
    
    public class Test01 {
        public static void main(String[] args) {
            ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext-*.xml");
            StudentService ss = app.getBean("studentService",StudentService.class);
            List<Student> list = ss.findAll();
            for (Student student : list) {
                System.out.println(student.getName());
            }
        }
    }
    
    • 测试结果:


      结果

    (9)web.xml文件配置:

        <!-- 解析applicationContext-*.xml -->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext-*.xml</param-value>
        </context-param>
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        
        <servlet>
            <servlet-name>mvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:springmvc.xml</param-value>
            </init-param>
        </servlet>
        <servlet-mapping>
            <servlet-name>mvc</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
        
    

    (12)jsp页面:

    • 添加
    <body>
        <h3>文件上传</h3>
        <form action="fileUpload" enctype="multipart/form-data" method="post">
            <p>
                姓名:<input type="text" name="name" />
            </p>
            <p>
                分数:<input type="text" name="score" />
            </p>
            <p>
                年龄:<input type="text" name="age" />
            </p>
            <p>
                照片:<input type="file" name="fl" />
            </p>
            <span style="color: red;font-size: 14px">${error }</span>
            <p>
                <input type="submit" value="提交" />
            </p>
            <a href="http://localhost:8080/x_springmvc04/findAll">查询所有</a>
        </form>
    </body>
    
    • 查询
      <body>
        <table border="1px" width="700px" align="center">
            <tr>
                <th>ID</th>
                <th>姓名</th>
                <th>年龄</th>
                <th>分数</th>
                <th>照片</th>
                <th>操作</th>
            </tr>
            <c:forEach items="${list }" var="stu">
                <tr>
                    <th>${stu.id }</th>
                    <th>${stu.name }</th>
                    <th>${stu.age }</th>
                    <th>${stu.score }</th>
                    <th> <img src="upload/${stu.filename }" height="60px"> </th>
                    <th><a>下载</a></th>
                </tr>
            </c:forEach>
        </table>
        <a href="http://localhost:8080/x_springmvc04/save.jsp">返回</a>
      </body>
    

    (11)Controller文件:

    package com.zlw.controller;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.List;
    import java.util.UUID;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.multipart.MultipartFile;
    
    import com.zlw.pojo.Student;
    import com.zlw.service.StudentService;
    
    @Controller
    public class MyController {
    
        @Autowired
        private StudentService studentService;
        
        //查询所有信息
        @RequestMapping("findAll")
        public String findAll(HttpServletRequest request){
            
            List<Student> list = studentService.findAll();
            request.setAttribute("list",list);
            return "index.jsp";
            
        }
        
        @RequestMapping("fileUpload")
        public String fileUpload(Student student,MultipartFile fl,HttpServletRequest request) throws IllegalStateException, IOException {
    
            // System.out.println(fl.getName()+"--"+fl.getSize()+"--"+fl.getContentType());
            //获取文件的后缀
            String substring = fl.getOriginalFilename().substring(fl.getOriginalFilename().lastIndexOf("."));
    
            //判断文件的后缀
            if(!(".jpg".equals(substring)||".gif".equals(substring)||".png".equals(substring))){
                request.setAttribute("error", "上传文件必须是图片");
                return "save.jsp";
            }
            //限制上传文件的大小
            if(fl.getSize()>40*1024){
                request.setAttribute("error", "上传文件不能超过20kb");
                return "save.jsp";
            }
            
            //相同图片名称覆盖
            String uuid = UUID.randomUUID().toString();
            
            //文件名
    //      String filename = fl.getOriginalFilename();
            String filename = uuid+substring;
            
            //获取服务器的目录
            String lealPath = request.getServletContext().getRealPath("/upload");
            
            //创建文件的目录
            File file = new File(lealPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            //文件上传
            fl.transferTo(new File(file ,filename));
            
            student.setFilename(filename);
            student.setFiletype(fl.getContentType());
            int n = studentService.save(student);
            if(n>0){
                return "findAll";
            }else{
                request.setAttribute("error", "添加失败!");
                return "forward:/save.jsp";
            }
        }
    }
    

    (12)在springmvc.xml中配置文件:

    <context:component-scan base-package="com.zlw.controller"></context:component-scan>
            <!-- @RequestMapping -->
            <mvc:annotation-driven></mvc:annotation-driven>
            
            <!-- 静态资源放行 -->
            <mvc:resources location="/upload/" mapping="/upload/**"></mvc:resources>
    
            <!-- 创建上传文件的组件对象 -->
            <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
                <!-- 上传文件,文件名的中文乱码问题 -->
                <property name="defaultEncoding" value="utf-8"></property>
                <!-- 限制文件的大小 -->
                <!--  <property name="maxUploadSize" value="20000"></property>
                        -->
            </bean>
            <!-- 自定义异常解析器 -->
            <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
                <property name="exceptionMappings">
                    <props>
                        <!-- 异常的全路径,注意是Spring抛出的异常 -->
                        <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error.jsp</prop>
                    </props>
                </property>
            </bean>
    

    • 实现效果:


      上传操作
      所有信息

    相关文章

      网友评论

          本文标题:SpringMVC学习day-67:SpringMVC重定向和文

          本文链接:https://www.haomeiwen.com/subject/slxjvctx.html