SpringMVC框架整合(搭建框架——测试——上传图像) 2

简介: SpringMVC框架整合(搭建框架——测试——上传图像)

带参数传值的四种方法

向前端页面跳转需要Model(数据)和View(页面)

1.ModelAndView方式传值
@RequestMapping("/hello02")
    public ModelAndView hello02(ModelAndView modelAndView){
        modelAndView.setViewName("hello01.jsp");
        modelAndView.addObject("username","pp");
        return modelAndView;
    }
2.Model方式传值
@RequestMapping("/hello03")
    public String hello03(Model model){
        model.addAttribute("username","ppp");
        return "hello01.jsp";
    }
3.HttpServletRequest方式传值
@RequestMapping("/hello04")
    public String hello04(HttpServletRequest request){
        request.setAttribute("username","pppp");
        return "hello01.jsp";
    }
4.Map方式传值
@RequestMapping("/hello05")
    public String hello05(Map map){
        map.put("username","ppppp");
        return "hello01.jsp";
    }

其实四种传值方式本质上都是转发,比较常用的是Model方式。

重定项

重定项在SpringMVC中非常的简单就是在return后面添加redirect:

    @RequestMapping("/hello05")
    public String hello05(Map map){
        map.put("username","ppppp");
        return "redirect:/login.jsp";
    }

前端向后端传值

前端传值一般使用表单提交

前端传值页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
<form action="/hello/hello03" method="post">
    用户名:<input type="text" name="username">
    密码:<input type="text" name="pwd">
    <br>
    <input type="submit" value="提交">
</form>
</body>
</html>

后端接收

可以直接把name值写在方法参数里面(不推荐使用

@RequestMapping("/hello03")
    public String hello03(String username,String pwd,Model model){
        System.out.println("用户名:"+username+"密码:"+pwd);
        model.addAttribute("username","ppp");
        return "hello01.jsp";
    }

也可以创建个实体类接收,前提实体类里要有这些属性(推荐使用

@RequestMapping("/hello03")
    public String hello03(User user,Model model){
        System.out.println("用户名:"+user.getUsername()+"密码:"+user.getPwd());
        model.addAttribute("username","ppp");
        return "hello01.jsp";
    }

网页报错跳转

应用场景,网页的404页面或者500页面

网页中只要有错误就会跳转到你设置的那个错误页面

这个是在本类里面的错误跳转,RuntimeException表示运行时的错误,可以改变

@ExceptionHandler(RuntimeException.class)
    public String error(Exception e){
        System.out.println(e.getMessage());
        return "error.jsp";
    }

写在SpringMVC配置文件表示这个项目中的错误都跳转,RuntimeException表示运行时的错误,可以改变

<!--有错误时跳转的页面-->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.RuntimeException">error.jsp</prop>
            </props>
        </property>
    </bean>

Ajax方式

发起Ajax请求

发起Ajax请求只需要在方法上面添加@ResponseBody注解就可以实现

这样return返回的就不再是页面而是数据,前端发起Ajax请求就能获取到

    @RequestMapping("/hello06")
    @ResponseBody
    public String hello06(){
        User user=new User();
        user.setUsername("牛牛");
        user.setPwd("123");
        String result= JSON.toJSONString(user);
        return result;
    }

发起Ajax请求直接赋值

 @RequestMapping(value = "/hello07/{username}/{pwd}",produces = {"text/html;charset=utf-8"})
    @ResponseBody
    public String hello07(@PathVariable("username") String username,
                          @PathVariable("pwd") String pwd){
        return username+pwd;
    }

效果:

虽然这种方式很方便,但是不安全,用户也不会在这里直接输入,(目前不常用

上传图片

前端页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>上传页面</title>
</head>
<body>
    <form action="/hello/upload" method="post" enctype="multipart/form-data">
        <input type="text" name="username">
        <br>
        <input type="file" name="photo">
        <br>
        <input type="submit" value="提交">
    </form>
</body>
</html>

后端代码

@RequestMapping("/upload")
    public String upload(String username,MultipartFile photo,HttpServletRequest request){
        String fileType=photo.getOriginalFilename();//获取文件名
        int index=fileType.lastIndexOf(".");//获取文件后缀有几位
        fileType=fileType.substring(index);截取后缀
        String path=request.getSession().getServletContext().getRealPath("static"+ File.separator+"uploadfiles");//拼接地址
        long filename=System.currentTimeMillis();//获取当前时间时间戳
        File file=new File(path+"\\"+filename+fileType);//上传的地址
        System.out.println(path+"\\"+filename+fileType);//打印地址
        try {
            photo.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传成功";
    }

获取时间戳,将图片名称改为时间戳传入tomcat容器

输出:

可以通过此地址在网页里查询到刚刚上传的图片


拦截器

SpringMVC中写入拦截器

<mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/hello/**"/>
            <mvc:exclude-mapping path="/hello/hello04"/>
            <bean class="com.interceptor.LoginInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

解释:


<mvc:mapping path="/hello/**"/>拦截的地址

<mvc:exclude-mapping path="/hello/hello04"/>规定不拦截的地址

<bean class="com.interceptor.LoginInterceptor"></bean>调用拦截的类

拦截器类方法编写

package com.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
        String username= request.getParameter("username");
        //判断是否有username
        if (null==username||"".equals(username)){
            response.sendRedirect("/index.jsp");
            return false;
        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("afterCompletion:页面没加载之前");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion:全部执行完毕后执行");
    }
}

应用场景:一般在登录页面

(完)

相关文章
|
1天前
|
存储 Web App开发 Java
《手把手教你》系列基础篇(九十五)-java+ selenium自动化测试-框架之设计篇-java实现自定义日志输出(详解教程)
【7月更文挑战第13天】这篇文章介绍了如何在Java中创建一个简单的自定义日志系统,以替代Log4j或logback。
11 5
|
1天前
|
敏捷开发 测试技术 持续交付
探索自动化测试框架的演进与实践
【7月更文挑战第14天】自动化测试框架在软件开发生命周期中扮演着越来越重要的角色。本文旨在探讨自动化测试框架从简单的脚本到复杂的系统级解决方案的演变过程,并分析其在不同阶段解决的关键问题。通过案例研究,我们将深入了解如何选择合适的自动化测试工具以及设计有效的测试策略,以提升软件质量保障的效率和效果。
|
2天前
|
敏捷开发 存储 数据管理
自动化测试框架设计:从理论到实践
【7月更文挑战第13天】本文将深入探讨自动化测试框架的设计原理与实现方法。通过分析自动化测试的必要性和框架设计的基本原则,结合具体案例,展示如何从零开始构建一个高效、可维护的自动化测试系统。文章不仅涵盖框架的结构设计,还包括最佳实践和常见问题的解决策略,为读者提供一套完整的解决方案和实操指南。
|
2天前
|
设计模式 Java 测试技术
《手把手教你》系列基础篇(九十四)-java+ selenium自动化测试-框架设计基础-POM设计模式实现-下篇(详解教程)
【7月更文挑战第12天】在本文中,作者宏哥介绍了如何在不使用PageFactory的情况下,用Java和Selenium实现Page Object Model (POM)。文章通过一个百度首页登录的实战例子来说明。首先,创建了一个名为`BaiduHomePage1`的页面对象类,其中包含了页面元素的定位和相关操作方法。接着,创建了测试类`TestWithPOM1`,在测试类中初始化WebDriver,设置驱动路径,最大化窗口,并调用页面对象类的方法进行登录操作。这样,测试脚本保持简洁,遵循了POM模式的高可读性和可维护性原则。
11 2
|
3天前
|
设计模式 Java 测试技术
《手把手教你》系列基础篇(九十三)-java+ selenium自动化测试-框架设计基础-POM设计模式实现-上篇(详解教程)
【7月更文挑战第11天】页面对象模型(POM)通过Page Factory在Java Selenium测试中被应用,简化了代码维护。在POM中,每个网页对应一个Page Class,其中包含页面元素和相关操作。对比之下,非POM实现直接在测试脚本中处理元素定位和交互,代码可读性和可维护性较低。
|
14天前
|
JSON JavaScript 测试技术
Postman接口测试工具详解
Postman接口测试工具详解
25 1
|
3天前
|
XML JSON 测试技术
Postman接口测试工具详解
📚 Postman全攻略:API测试神器!📚 发送HTTP请求,管理集合,写测试脚本,集成CI/CD。从安装配置到环境变量、断言、数据驱动测试,一步步教你如何高效测试RESTful API。实战案例包含GET、POST、PUT、DELETE请求。用Newman在命令行跑集合,自动化测试不发愁!👉 [洛秋小站](https://www.luoqiu.site/) 学更多!🚀
13 1
|
11天前
|
数据采集 测试技术
常见测试测量接口的比较:PXI、PXIe、PCI、VXI、GPIB、USB
常见测试测量接口的比较:PXI、PXIe、PCI、VXI、GPIB、USB
14 2
|
19天前
|
存储 JSON 测试技术
软件测试之 接口测试 Postman使用(下)
软件测试之 接口测试 Postman使用(下)
24 2
|
19天前
|
测试技术 数据格式
软件测试之 接口测试 Postman使用(上)
软件测试之 接口测试 Postman使用(上)
22 1