当前位置:   article > 正文

springboot 整合springmvc_springboot整合springmvc

springboot整合springmvc

项目结构

 

引入web启动器 

 pom.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>cn.itcast.user</groupId>
  7. <artifactId>itcast-user</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <parent>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-starter-parent</artifactId>
  12. <version>2.0.6.RELEASE</version>
  13. </parent>
  14. <dependencies>
  15. <dependency>
  16. <groupId>org.springframework.boot</groupId>
  17. <artifactId>spring-boot-starter-web</artifactId>
  18. </dependency>
  19. </dependencies>
  20. </project>

编写引导类

  1. @SpringBootApplication
  2. public class UserApplication {
  3. public static void main(String[] args) {
  4. SpringApplication.run(UserApplication.class);
  5. }
  6. }

 编写UserController

  1. @RestController
  2. @RequestMapping("user")
  3. public class UserController {
  4. @GetMapping("hello")
  5. public String test(){
  6. return "hello ssm";
  7. }
  8. }

修改端口(修改默认配置)

1.application.yml中配置

  1. # 开发环境配置
  2. server:
  3. # 服务器的HTTP端口,默认为8080
  4. port: 6100

访问静态资源

1.默认的静态资源路径为:

  • classpath:/META-INF/resources/

  • classpath:/resources/

  • classpath:/static/(一般放置在这个文件夹下)

  • classpath:/public/

只要静态资源放在这些目录中任何一个,SpringMVC都会帮我们处理

添加拦截器

1.拦截器不是一个普通属性,而是一个类,所以就要用到java配置方式

2.通过WebMvcConfigurer并添加@Configuration注解来实现自定义部分SpringMvc配置

 1.定义拦截器

  1. package com.ruoyi.framework.interceptor;
  2. import java.lang.reflect.Method;
  3. import javax.servlet.http.HttpServletRequest;
  4. import javax.servlet.http.HttpServletResponse;
  5. import org.springframework.stereotype.Component;
  6. import org.springframework.web.method.HandlerMethod;
  7. import org.springframework.web.servlet.HandlerInterceptor;
  8. import com.alibaba.fastjson.JSONObject;
  9. import com.ruoyi.common.annotation.RepeatSubmit;
  10. import com.ruoyi.common.core.domain.AjaxResult;
  11. import com.ruoyi.common.utils.ServletUtils;
  12. /**
  13. * 防止重复提交拦截器
  14. *
  15. * @author ruoyi
  16. */
  17. @Component
  18. public abstract class RepeatSubmitInterceptor implements HandlerInterceptor
  19. {
  20. @Override
  21. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
  22. {
  23. if (handler instanceof HandlerMethod)
  24. {
  25. HandlerMethod handlerMethod = (HandlerMethod) handler;
  26. Method method = handlerMethod.getMethod();
  27. RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
  28. if (annotation != null)
  29. {
  30. if (this.isRepeatSubmit(request, annotation))
  31. {
  32. AjaxResult ajaxResult = AjaxResult.error(annotation.message());
  33. ServletUtils.renderString(response, JSONObject.toJSONString(ajaxResult));
  34. return false;
  35. }
  36. }
  37. return true;
  38. }
  39. else
  40. {
  41. return true;
  42. }
  43. }
  44. /**
  45. * 验证是否重复提交由子类实现具体的防重复提交的规则
  46. *
  47. * @param request
  48. * @return
  49. * @throws Exception
  50. */
  51. public abstract boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation);
  52. }

 2.WebMvcConfigurer配置类,注册拦截器

  1. package com.ruoyi.framework.config;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.web.cors.CorsConfiguration;
  6. import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
  7. import org.springframework.web.filter.CorsFilter;
  8. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
  9. import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
  10. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  11. import com.ruoyi.common.config.RuoYiConfig;
  12. import com.ruoyi.common.constant.Constants;
  13. import com.ruoyi.framework.interceptor.RepeatSubmitInterceptor;
  14. /**
  15. * 通用配置
  16. *
  17. * @author ruoyi
  18. */
  19. @Configuration
  20. public class ResourcesConfig implements WebMvcConfigurer
  21. {
  22. @Autowired
  23. private RepeatSubmitInterceptor repeatSubmitInterceptor;
  24. /**
  25. *定义资源拦截器,请求为/profile的资源会映射到访问本地资源,这样就可以让别人访问服务器的本地文件了
  26. * @param registry
  27. */
  28. @Override
  29. public void addResourceHandlers(ResourceHandlerRegistry registry)
  30. {
  31. /** 本地文件上传路径 */
  32. registry.addResourceHandler('/profile' + "/**")
  33. .addResourceLocations("file:" +'D:/ruoyi/uploadPath/');
  34. /** swagger配置 */
  35. registry.addResourceHandler("/swagger-ui/**")
  36. .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
  37. }
  38. /**
  39. * 自定义拦截规则
  40. */
  41. @Override
  42. public void addInterceptors(InterceptorRegistry registry)
  43. {
  44. registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**");
  45. }
  46. /**
  47. * 跨域配置
  48. */
  49. @Bean
  50. public CorsFilter corsFilter()
  51. {
  52. CorsConfiguration config = new CorsConfiguration();
  53. config.setAllowCredentials(true);
  54. // 设置访问源地址
  55. config.addAllowedOrigin("*");
  56. // 设置访问源请求头
  57. config.addAllowedHeader("*");
  58. // 设置访问源请求方法
  59. config.addAllowedMethod("*");
  60. // 有效期 1800
  61. config.setMaxAge(1800L);
  62. // 添加映射路径,拦截一切请求
  63. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  64. source.registerCorsConfiguration("/**", config);
  65. // 返回新的CorsFilter
  66. return new CorsFilter(source);
  67. }
  68. }

@RequestParam 接收表单

1.@RequestParam接收的参数是来自requestHeader中,即请求头通常用于GET请求。

2.比如常见的url:http://localhost:8081/spring-boot-study/novel/findByAuthorAndType?author=唐家三少&type=已完结

3.@RequestParam(value="username", required=true, defaultValue="zhang") String username) 表示 入参的请求参数名字,前端必须和这个名称一样  ,默认值是true,必传,默认值是zhang

4.@RequestParam加上这个参数,表示必传项,去掉表示可传可不传

  1. @RequestMapping("/login")
  2. ​​​​ public AjaxResult login2(@RequestParam String username, @RequestParam String password) {
  3. AjaxResult ajax = AjaxResult.success();
  4. // 生成令牌
  5. String token = loginService.login2(username, password);
  6. System.out.println(token);
  7. ajax.put(Constants.TOKEN, token);
  8. return ajax;
  9. }
  10. //------------------------------------
  11. /**
  12. * get携带参数请求(单个接收)
  13. * 请求方式:http://localhost:8080/axiostest/get8?name=123
  14. *
  15. * @param name 可以省略@RequestParam("name"),接收单个参数,前端参数名必须为name
  16. * @return
  17. */
  18. @RequestMapping(path = "/get8", method = RequestMethod.GET)
  19. @ResponseBody
  20. public Object getid(String name
  21. ) {
  22. return "接收到是参数为:" + name;
  23. }
  24. //--------------------------------------------
  25. //接收多个参数,用map接收
  26. /**
  27. * get携带参数请求,接收一个对象
  28. *
  29. * @RequestParam Map 只能用在get 请求当中,接收id=123&&name="张三"中的全部参数
  30. *
  31. * axios.get('http://localhost:8080/axiostest/getparams', {
  32. * params: {
  33. * id: 789,
  34. * name:"张三"
  35. * }
  36. * }).then(function(ret){
  37. * console.log(ret.data)
  38. * })
  39. * @param
  40. * @return
  41. */
  42. @RequestMapping(path = "/getparams", method = RequestMethod.GET)
  43. @ResponseBody
  44. public Object getParam(@RequestParam Map<String, Object> params
  45. ) {
  46. return "接收到是参数为:" + params;
  47. }

5.@RequestParam 注解如果是个map类型,那么mvc适配器就将参数封装到map中

请求地址:localhost:8080/test?name=testname&pwd=123456

  1. @RequestMapping("/test")
  2. public Object hello2(@RequestParam Map query) {
  3. String name = (String) query.get("name");
  4. String pwd = (String) query.get("pwd");
  5. System.out.println(name);
  6. System.out.println(pwd);
  7. return query;
  8. }

6.将@RequestParam绑定到对象中 ,从对象中取值

  1. @GetMapping
  2. List<Product> searchProducts(ProductCriteria productCriteria) {
  3. return productRepository.search(productCriteria);
  4. }

 @RequestBody 接收JSON数据

1.接收的参数是来自requestBody中,即请求体,即 Content-Type:为application/jsonapplication/xml等类型的数据

2.就application/json类型的数据而言,使用注解@RequestBody可以将body里面所有的json数据传到后端

  1. // -----------------------------------
  2. $.ajax({
  3. url: "user/testJson",
  4. contentType: "application/json;charset=UTF-8",
  5. data: ' {
  6. "addressName": "aa",
  7. "addressNum": 100
  8. }
  9. ',
  10. dataType: "json",
  11. type: "post",
  12. success: function(data) {
  13. alert(data);
  14. alert(data.addressName);
  15. }
  16. });
  17. //---------------------------------------
  18. /*** 获取请求体的数据 * @param body */
  19. @RequestMapping("/testJson")
  20. public void testJson(@RequestBody Address address) {
  21. System.out.println(address);
  22. }

 @PathVariable 接收路径中的参数

1.拥有绑定url中的占位符的。例如:url中有/delete/{id}{id}就是占位符

  1. /**
  2. * get携带参数请求2
  3. * 请求方式:http://localhost:8080/axiostest/get/123
  4. *
  5. * @param id
  6. * @return
  7. */
  8. @RequestMapping(path = "/get/{id}", method = RequestMethod.GET)
  9. @ResponseBody
  10. public Object getPath(@PathVariable("id") String id
  11. ) {
  12. return "接收到是参数PathVariable为:" + id;
  13. }

返回字符串 

  1. /*** 请求参数的绑定 */
  2. @RequestMapping(value = "/initUpdate")
  3. public String initUpdate(Model model) {
  4. // 模拟从数据库中查询的数据
  5. User user = new User();
  6. user.setUsername("张三");
  7. user.setPassword("123");
  8. user.setMoney(100d);
  9. user.setBirthday(new Date());
  10. model.addAttribute("user", user);
  11. return "update";
  12. }

@ResponseBody  响应JSON字符串

1.加上 @ResponseBody

2.前端接收到前端字符串后,需要转换成json对象使用

  1. /**
  2. * 2.返回Json串儿的封装
  3. *
  4. * @param id
  5. * @return
  6. */
  7. @RequestMapping("/success")
  8. @ResponseBody
  9. public AjaxResult delete(String id) {
  10. List<String> ll = new ArrayList<>();
  11. ll.add("111");
  12. ll.add("2222");
  13. if (id.equals("1")) {
  14. return success("请求成功2", ll);
  15. } else {
  16. return error("数据错误");
  17. }
  18. }

返回值为void 

返回值是ModelAndView对象  

提供的转发和重定向  

1.forward请求转发

1.1controller方法返回String类型,想进行请求转发也可以编写成

  1. /*** 使用forward关键字进行请求转发 * "forward:转发的JSP路径",不走视图解析器了,所以需要编写完整的路径 * @return * @throws Exception */
  2. @RequestMapping("/delete")
  3. public String delete() throws Exception {
  4. System.out.println("delete方法执行了...");
  5. // return "forward:/WEB-INF/pages/success.jsp";
  6. return "forward:/user/findAll";
  7. }

2.redirect重定向

2.1controller方法返回String类型,想进行重定向也可以编写成

  1. /*** 重定向 * @return * @throws Exception */
  2. @RequestMapping("/count")
  3. public String count() throws Exception {
  4. System.out.println("count方法执行了...");
  5. return "redirect:/add.jsp";
  6. // return "redirect:/user/findAll"; }
  7. }

 接收表单数据和图片组(文件上传)

  1. StringBuffer b;
  2. List<String> ccList = new ArrayList<String>();
  3. String images;
  4. @RequestMapping("/upload")
  5. public AjaxResult upload(@RequestParam("file") MultipartFile[] multipartfiles,
  6. Weixiu weixiu) throws IOException {
  7. b = new StringBuffer();
  8. ccList.clear();
  9. b.setLength(0);
  10. System.out.println(multipartfiles.length);
  11. String defaultBaseDir = RuoYiConfig.getProfile();
  12. System.out.println(defaultBaseDir);
  13. String savePath = defaultBaseDir + "/";
  14. if (null != multipartfiles && multipartfiles.length > 0) {
  15. //遍历并保存文件
  16. for (MultipartFile file : multipartfiles) {
  17. File dest = new File(savePath + file.getOriginalFilename());
  18. if (!dest.getParentFile().exists()) {
  19. dest.getParentFile().mkdirs();
  20. }
  21. file.transferTo(dest);
  22. ccList.add(file.getOriginalFilename());
  23. }
  24. for (int i = 0; i < ccList.size(); i++) {
  25. b.append(ccList.get(i));
  26. b.append(",");
  27. }
  28. images = b.substring(0, b.length() - 1);
  29. }
  30. Date day = new Date();
  31. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  32. weixiu.setChecktime(sdf.format(day).toString());
  33. weixiu.setCheckimage(images);
  34. weixiuService.insertWeixiu(weixiu);
  35. AjaxResult ajax = AjaxResult.success();
  36. return ajax;
  37. }

SpringMVC的异常处理

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/435311
推荐阅读
相关标签