1.跳转不经过视图解析器
return "forward:/main.jsp";//使用转发跳转到指定路径,无需经过视图解析器
return "redirect:/main.jsp";//使用重定向跳转到指定路径,无需经过视图解析器
2.controller保存数据
request session Model
1. public String register(User user, HttpServletRequest request){System.out.println(user);request.setAttribute("user",user);return "index";return "forward:/main.jsp";//使用转发跳转到指定路径,无需经过视图解析器return "redirect:/main.jsp";//使用重定向跳转到指定路径,无需经过视图解析器 }
2. @RequestMapping("/register") public String register( HttpSession session){List<String> list=new ArrayList<>();list.add("张三");session.setAttribute("user",list);return "index"; }
3. @RequestMapping("/login") public String register(User user, Model model){List<String> list=new ArrayList<>();list.add("张三");model.addAttribute("user",list);return "index"; }
3.controller层返回json数据
[1] jackson依赖
<!-- jackson --> <dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.18.1</version> </dependency>[2] 方法上添加@ResponseBody 把该方法返回的对象转换为json格式。等价于out.print();
4.拦截器
拦截器只拦截controller层API接口
true表示放行,false不放行
例:1.
java">public class MyInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {HttpSession session=request.getSession();Object userinfo = session.getAttribute("userinfo");if(userinfo==null){response.sendRedirect("/login.jsp");return false;//true表示放行,false不放行}return true;}
}
2.在springmvc配置文件里面 注册拦截器及拦截规则
<!-- 注册自定义的拦截器的拦截规则--><mvc:interceptors><mvc:interceptor>
<!-- path拦截路径 /** 表示多层路径--><mvc:mapping path="/**"/>
<!-- 排除路径放行路径 --><mvc:exclude-mapping path="/user/login"/><mvc:exclude-mapping path="/user/logout"/>
<!-- 放置自定义的拦截器类--><bean class="com.ghx.interceptor.MyInterceptor"></bean></mvc:interceptor></mvc:interceptors>
5.全局异常处理
全局异常处理类,要保证springmvc包扫描 可以扫描到该异常处理类
java">@ControllerAdvice
public class MyGlobalException {//发生Exception类型的异常会执行该方法,并异常对象传递给该方法的参数@ExceptionHandler(Exception.class)@ResponseBodypublic String handlerException(Exception e){System.out.println(e.getMessage());return "error";}@ExceptionHandler(ArithmeticException.class)public String handlerArithmeticException(Exception e){return "error";}
}
6.文件上传
1.引入文件上传依赖
<!-- 文件上传依赖--> <dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.5</version> </dependency>
若使用阿里oss还需加上
<!--在commons-fileupload基础上阿里oss--> <dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.17.4</version> </dependency>
2.配置文件上传解析器 springmvc里面配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 最大上传大小 单位byte 5M=5*1024*1024--><property name="maxUploadSize" value="5242880"/> <!-- 设置上传编码--><property name="defaultEncoding" value="utf-8"/></bean>
3.上传页面
文件上传的表单提交方式必须为post,而且需要设置表单提交的编码格式。enctype="multipart/form-data" 该类型表示既能上传文本又能上传文件。
<form action="/emp/insert" method="post" enctype="multipart/form-data">员工姓名:<input type="text" name="empName" id="empName"><br>岗位:<input type="text" name="empJob" id="empJob"><br>薪资:<input type="text" name="empSalary" id="empSalary"><br>头像:<input type="file" name="myfile" id="myfile"><br>部门:<input type="number" id="did" name="did" /><br><input type="submit" value="添加">
</form>
4.1上传本地
api
java"> @RequestMapping("/insert")public String insert(MultipartFile myfile, HttpServletRequest request,Emp emp)throws Exception{String update = UploadUtil.update(myfile, request);emp.setEmpImg(update);empMapper.insertSelective(emp);sqlSession.commit();return "index";}
文件上传工具类
java">public static String update(MultipartFile myfile, HttpServletRequest request){try {//获取保存文件的路径String realPath=request.getSession().getServletContext().getRealPath("/images");System.out.println(realPath);//根据上面的路径创建文件对象File file=new File(realPath);//判断文件夹是否存在if(!file.exists()){file.mkdirs();}//上传的文件名String fileName= UUID.randomUUID().toString().replace("-","")+myfile.getOriginalFilename();//把上传的文件保存到指定路径下File file1=new File(realPath+"/"+fileName);myfile.transferTo(file1);return "/images/"+fileName;} catch (IOException e) {throw new RuntimeException(e);}}
4.2上传到阿里oss
api
java"> @RequestMapping("/upload")public String upload(MultipartFile myfile,Emp emp){String s = UploadUtil.uploadOss(myfile);emp.setEmpImg(s);empMapper.insertSelective(emp);sqlSession.commit();return "index";}
java">//阿里osspublic static String uploadOss(MultipartFile myfile) {// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。String endpoint = "oss-cn-beijing.aliyuncs.com";// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。DefaultCredentialProvider defaultCredentialProvider = CredentialsProviderFactory.newDefaultCredentialProvider("密钥", "密钥");// 填写Bucket名称,例如examplebucket。String bucketName = "jyw";// 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。String objectName = UUID.randomUUID().toString().replace("-","")+myfile.getOriginalFilename() ;// 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。// 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。//String filePath = "E:\\qsl.jpg";// 填写Bucket所在地域。以华东1(杭州)为例,Region填写为cn-hangzhou。String region = "cn-beijing";// 创建OSSClient实例。ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);OSS ossClient = OSSClientBuilder.create().endpoint(endpoint).credentialsProvider(defaultCredentialProvider).clientConfiguration(clientBuilderConfiguration).region(region).build();try {InputStream inputStream = myfile.getInputStream();// 创建PutObjectRequest对象。PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);// 创建PutObject请求。PutObjectResult result = ossClient.putObject(putObjectRequest);
// https://jyw.oss-cn-beijing.aliyuncs.com/qsl.jpgString path="https://"+bucketName+"."+endpoint+"/"+objectName;return path;} catch (Exception e) {throw new RuntimeException(e);} finally {if (ossClient != null) {ossClient.shutdown();}}}