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:全部执行完毕后执行");
    }
}

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

(完)

相关文章
|
2月前
|
Web App开发 人工智能 JavaScript
主流自动化测试框架的技术解析与实战指南
本内容深入解析主流测试框架Playwright、Selenium与Cypress的核心架构与适用场景,对比其在SPA测试、CI/CD、跨浏览器兼容性等方面的表现。同时探讨Playwright在AI增强测试、录制回放、企业部署等领域的实战优势,以及Selenium在老旧系统和IE兼容性中的坚守场景。结合六大典型场景,提供技术选型决策指南,并展望AI赋能下的未来测试体系。
|
5天前
|
安全 Linux 网络安全
Metasploit Pro 4.22.8-2025091701 (Linux, Windows) - 专业渗透测试框架
Metasploit Pro 4.22.8-2025091701 (Linux, Windows) - 专业渗透测试框架
83 2
Metasploit Pro 4.22.8-2025091701 (Linux, Windows) - 专业渗透测试框架
|
5天前
|
Linux 网络安全 iOS开发
Metasploit Framework 6.4.90 (macOS, Linux, Windows) - 开源渗透测试框架
Metasploit Framework 6.4.90 (macOS, Linux, Windows) - 开源渗透测试框架
100 1
Metasploit Framework 6.4.90 (macOS, Linux, Windows) - 开源渗透测试框架
|
15天前
|
安全 Linux 网络安全
Metasploit Framework 6.4.88 (macOS, Linux, Windows) - 开源渗透测试框架
Metasploit Framework 6.4.88 (macOS, Linux, Windows) - 开源渗透测试框架
260 0
|
23天前
|
缓存 安全 Linux
Metasploit Pro 4.22.8-2025082101 (Linux, Windows) - 专业渗透测试框架
Metasploit Pro 4.22.8-2025082101 (Linux, Windows) - 专业渗透测试框架
83 0
|
4月前
|
Java 测试技术 容器
Jmeter工具使用:HTTP接口性能测试实战
希望这篇文章能够帮助你初步理解如何使用JMeter进行HTTP接口性能测试,有兴趣的话,你可以研究更多关于JMeter的内容。记住,只有理解并掌握了这些工具,你才能充分利用它们发挥其应有的价值。+
747 23
|
9月前
|
数据可视化 前端开发 测试技术
接口测试新选择:Postman替代方案全解析
在软件开发中,接口测试工具至关重要。Postman长期占据主导地位,但随着国产工具的崛起,越来越多开发者转向更适合中国市场的替代方案——Apifox。它不仅支持中英文切换、完全免费不限人数,还具备强大的可视化操作、自动生成文档和API调试功能,极大简化了开发流程。
|
6月前
|
SQL 安全 测试技术
2025接口测试全攻略:高并发、安全防护与六大工具实战指南
本文探讨高并发稳定性验证、安全防护实战及六大工具(Postman、RunnerGo、Apipost、JMeter、SoapUI、Fiddler)选型指南,助力构建未来接口测试体系。接口测试旨在验证数据传输、参数合法性、错误处理能力及性能安全性,其重要性体现在早期发现问题、保障系统稳定和支撑持续集成。常用方法包括功能、性能、安全性及兼容性测试,典型场景涵盖前后端分离开发、第三方服务集成与数据一致性检查。选择合适的工具需综合考虑需求与团队协作等因素。
706 24
|
6月前
|
SQL 测试技术
除了postman还有什么接口测试工具
最好还是使用国内的接口测试软件,其实国内替换postman的软件有很多,这里我推荐使用yunedit-post这款接口测试工具来代替postman,因为它除了接口测试功能外,在动态参数的支持、后置处理执行sql语句等支持方面做得比较好。而且还有接口分享功能,可以生成接口文档给团队在线浏览。
241 2
|
8月前
|
JSON 前端开发 测试技术
大前端之前端开发接口测试工具postman的使用方法-简单get接口请求测试的使用方法-简单教学一看就会-以实际例子来说明-优雅草卓伊凡
大前端之前端开发接口测试工具postman的使用方法-简单get接口请求测试的使用方法-简单教学一看就会-以实际例子来说明-优雅草卓伊凡
345 10
大前端之前端开发接口测试工具postman的使用方法-简单get接口请求测试的使用方法-简单教学一看就会-以实际例子来说明-优雅草卓伊凡

热门文章

最新文章