/** * 是void * 請求轉發一次請求,不用編寫項目的名稱 */ @RequestMapping("/testVoid") public void testVoid(HttpServletRequest request, HttpServletResponse response) throws Exception { System.out.println("testVoid方法執行了..."); // 編寫請求轉發的程序 // request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response); // 重定向 不能跳轉到pages裏邊的代碼 // response.sendRedirect(request.getContextPath()+"/index.jsp"); // 設置中文亂碼 response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); // 直接會進行響應 response.getWriter().print("你好"); return;//必須得加return 不然404 }
/** * 返回ModelAndView * @return */ @RequestMapping("/testModelAndView") public ModelAndView testModelAndView(){ // 建立ModelAndView對象 ModelAndView mv = new ModelAndView(); System.out.println("testModelAndView方法執行了..."); // 模擬從數據庫中查詢出User對象 User user = new User(); user.setUsername("小鳳"); user.setPassword("456"); user.setAge(30); // 把user對象存儲到mv對象中,也會把user對象存入到request對象 mv.addObject("user",user); // 跳轉到哪一個頁面 mv.setViewName("success"); return mv; }
/** * 使用關鍵字的方式進行轉發或者重定向 * 用不了視圖解析器 * @return */ @RequestMapping("/testForwardOrRedirect") public String testForwardOrRedirect(){ System.out.println("testForwardOrRedirect方法執行了..."); // 請求的轉發 // return "forward:/WEB-INF/pages/success.jsp"; // 重定向 return "redirect:/index.jsp"; }
springmvc.xml <!--前端控制器,哪些靜態資源不攔截--> <mvc:resources location="/css/" mapping="/css/**"/> <mvc:resources location="/images/" mapping="/images/**"/> <mvc:resources location="/js/" mapping="/js/**"/>
response.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2018/5/1
Time: 1:16
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>css
<title>Title</title> <script src="js/jquery.min.js"></script> <script> // 頁面加載,綁定單擊事件 $(function(){ $("#btn").click(function(){ // alert("hello btn"); // 發送ajax請求 $.ajax({ // 編寫json格式,設置屬性和值 url:"user/testAjax", contentType:"application/json;charset=UTF-8", data:'{"username":"hehe","password":"123","age":30}', dataType:"json", type:"post", success:function(data){ // data服務器端響應的json的數據,進行解析 alert(data); alert(data.username); alert(data.password); alert(data.age); } }); }); }); </script>
</head>
<body>html
<a href="user/testString" >testString</a> <br/> <a href="user/testVoid" >testVoid</a> <br/> <a href="user/testModelAndView" >testModelAndView</a> <br/> <a href="user/testForwardOrRedirect" >testForwardOrRedirect</a> <br/> <button id="btn">發送ajax的請求</button>
</body>
</html>前端
/** * 模擬異步請求響應 */ @RequestMapping("/testAjax") public @ResponseBody User testAjax(@RequestBody User user){ System.out.println("testAjax方法執行了..."); // 客戶端發送ajax的請求,傳的是json字符串,後端把json字符串封裝到user對象中 System.out.println(user); // 作響應,模擬查詢數據庫 user.setUsername("haha"); user.setAge(40); // 作響應 return user; }
防止聯網要下載不少東西
這樣的話能夠跳過聯網下載的過程
藉助第三方組件上傳
傳統的這種方式不能配置文件解析器java
/** * 文件上傳 * @return */ @RequestMapping("/fileupload1") public String fileuoload1(HttpServletRequest request) throws Exception { System.out.println("文件上傳..."); // 使用fileupload組件完成文件上傳 // 上傳的位置 String path = request.getSession().getServletContext().getRealPath("/uploads/"); // 判斷,該路徑是否存在 File file = new File(path); if(!file.exists()){ // 建立該文件夾 file.mkdirs(); } // 解析request對象,獲取上傳文件項 DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // 解析request List<FileItem> items = upload.parseRequest(request); // 遍歷 for(FileItem item:items){ // 進行判斷,當前item對象是不是上傳文件項 if(item.isFormField()){ // 說明普通表單向 }else{ // 說明上傳文件項 // 獲取上傳文件的名稱 String filename = item.getName(); // 把文件的名稱設置惟一值,uuid String uuid = UUID.randomUUID().toString().replace("-", ""); filename = uuid+"_"+filename; // 完成文件上傳 item.write(new File(path,filename)); // 刪除臨時文件 item.delete(); } } return "success"; }
index.jsp的修改jquery
<form action="/user/fileupload1" method="post" enctype="multipart/form-data"> 選擇文件:<input type="file" name="upload" /><br/> <input type="submit" value="上傳" /> </form>
文件解析器返回對象綁定到上傳方法的upload對象上去
這個文件解析器的id不能改變
方法web
/** * 文件上傳 * @return */ @RequestMapping("/fileupload1") public String fileuoload1(HttpServletRequest request) throws Exception { System.out.println("文件上傳..."); // 使用fileupload組件完成文件上傳 // 上傳的位置 String path = request.getSession().getServletContext().getRealPath("/uploads/"); // 判斷,該路徑是否存在 File file = new File(path); if(!file.exists()){ // 建立該文件夾 file.mkdirs(); } // 解析request對象,獲取上傳文件項 DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // 解析request List<FileItem> items = upload.parseRequest(request); // 遍歷 for(FileItem item:items){ // 進行判斷,當前item對象是不是上傳文件項 if(item.isFormField()){ // 說明普通表單向 }else{ // 說明上傳文件項 // 獲取上傳文件的名稱 String filename = item.getName(); // 把文件的名稱設置惟一值,uuid String uuid = UUID.randomUUID().toString().replace("-", ""); filename = uuid+"_"+filename; // 完成文件上傳 item.write(new File(path,filename)); // 刪除臨時文件 item.delete(); } } return "success"; }
須要跑兩個tomcat服務器
ajax
方法的代碼spring
/** * 跨服務器文件上傳 * @return */ @RequestMapping("/fileupload3") public String fileuoload3(MultipartFile upload) throws Exception { System.out.println("跨服務器文件上傳..."); // 定義上傳文件服務器路徑 String path = "http://localhost:9090/uploads/"; // 說明上傳文件項 // 獲取上傳文件的名稱 String filename = upload.getOriginalFilename(); // 把文件的名稱設置惟一值,uuid String uuid = UUID.randomUUID().toString().replace("-", ""); filename = uuid+"_"+filename; // 建立客戶端的對象 Client client = Client.create(); // 和圖片服務器進行鏈接 WebResource webResource = client.resource(path + filename); // 上傳文件 webResource.put(upload.getBytes()); return "success"; }
jsp中的代碼數據庫
<h3>跨服務器文件上傳</h3> <form action="/user/fileupload3" method="post" enctype="multipart/form-data"> 選擇文件:<input type="file" name="upload" /><br/> <input type="submit" value="上傳" /> </form>
須要下邊的jar包
json
<dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-core</artifactId> <version>1.18.1</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-client</artifactId> <version>1.18.1</version> </dependency>
啓動兩個服務器
跨服務器上傳遇到的錯誤409表示必須在建立存在上傳文件的uploads文件夾
403沒權限表示tomcat沒有寫入的權限
在tomcat的conf的web.xml中加入
<init-param>
<param-name>readonly</param-name> <param-value>false</param-value>
</init-param>
且文件服務器的wepapp下建立uploads文件夾
練習目錄
UserController.java
package cn.itcast.controller;
import cn.itcast.exception.SysException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/testException") public String testException() throws SysException{ System.out.println("testException執行了..."); try { // 模擬異常 int a = 10/0; } catch (Exception e) { // 打印異常信息 e.printStackTrace(); // 拋出自定義異常信息 throw new SysException("查詢全部用戶出現錯誤了..."); } return "success"; }
}
SysException.java
package cn.itcast.exception;
/**
*/
public class SysException extends Exception{
// 存儲提示信息的 private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public SysException(String message) { this.message = message; }
}
package cn.itcast.exception;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*/
public class SysExceptionResolver implements HandlerExceptionResolver{
/** * 處理異常業務邏輯 * @param request * @param response * @param handler * @param ex * @return */ public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { // 獲取到異常對象 SysException e = null; if(ex instanceof SysException){ e = (SysException)ex; }else{ e = new SysException("系統正在維護...."); } // 建立ModelAndView對象 ModelAndView mv = new ModelAndView(); mv.addObject("errorMsg",e.getMessage()); mv.setViewName("error"); return mv; }
}
springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 開啓註解掃描 --> <context:component-scan base-package="cn.itcast"/> <!-- 視圖解析器對象 --> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean> <!--前端控制器,哪些靜態資源不攔截--> <mvc:resources location="/css/" mapping="/css/**"/> <mvc:resources location="/images/" mapping="/images/**"/> <mvc:resources location="/js/" mapping="/js/**"/> <!--配置異常處理器--> <bean id="sysExceptionResolver" class="cn.itcast.exception.SysExceptionResolver"/> <!-- 開啓SpringMVC框架註解的支持 --> <mvc:annotation-driven />
</beans>
webapp/pages/error.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2018/5/5
Time: 22:28
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${errorMsg}
</body>
</html>
sprigmvc配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 開啓註解掃描 --> <context:component-scan base-package="cn.itcast"/> <!-- 視圖解析器對象 --> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean> <!--前端控制器,哪些靜態資源不攔截--> <mvc:resources location="/css/" mapping="/css/**"/> <mvc:resources location="/images/" mapping="/images/**"/> <mvc:resources location="/js/" mapping="/js/**"/> <!--配置攔截器--> <mvc:interceptors> <!--配置攔截器--> <mvc:interceptor> <!--要攔截的具體的方法--> <mvc:mapping path="/user/*"/> <!--不要攔截的方法 <mvc:exclude-mapping path=""/> --> <!--配置攔截器對象--> <bean class="cn.itcast.controller.cn.itcast.interceptor.MyInterceptor1" /> </mvc:interceptor> <!--配置第二個攔截器--> <mvc:interceptor> <!--要攔截的具體的方法--> <mvc:mapping path="/**"/> <!--不要攔截的方法 <mvc:exclude-mapping path=""/> --> <!--配置攔截器對象--> <bean class="cn.itcast.controller.cn.itcast.interceptor.MyInterceptor2" /> </mvc:interceptor> </mvc:interceptors> <!-- 開啓SpringMVC框架註解的支持 --> <mvc:annotation-driven />
</beans>
攔截器類1
MyInterceptor1.java
package cn.itcast.controller.cn.itcast.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 MyInterceptor1 implements HandlerInterceptor{
/** * 預處理,controller方法執行前 * return true 放行,執行下一個攔截器,若是沒有,執行controller中的方法 * return false不放行 * @param request * @param response * @param handler * @return * @throws Exception */ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("MyInterceptor1執行了...前1111"); // request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response); //return false;跳轉頁面 return true; } /** * 後處理方法,controller方法執行後,success.jsp執行以前 * @param request * @param response * @param handler * @param modelAndView * @throws Exception */ public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("MyInterceptor1執行了...後1111"); // request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response); //return false;跳轉頁面 } /** * success.jsp頁面執行後,該方法會執行 * @param request * @param response * @param handler * @param ex * @throws Exception */ public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("MyInterceptor1執行了...最後1111"); }
}
攔截器類2
package cn.itcast.controller.cn.itcast.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 MyInterceptor2 implements HandlerInterceptor{
/** * 預處理,controller方法執行前 * return true 放行,執行下一個攔截器,若是沒有,執行controller中的方法 * return false不放行 * @param request * @param response * @param handler * @return * @throws Exception */ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("MyInterceptor1執行了...前2222"); // request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response); return true; } /** * 後處理方法,controller方法執行後,success.jsp執行以前 * @param request * @param response * @param handler * @param modelAndView * @throws Exception */ public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("MyInterceptor1執行了...後2222"); // request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response); } /** * success.jsp頁面執行後,該方法會執行 * @param request * @param response * @param handler * @param ex * @throws Exception */ public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("MyInterceptor1執行了...最後2222"); }
}
success.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2018/5/5
Time: 22:11
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>執行成功</h3> <% System.out.println("success.jsp執行了..."); %>
</body>
</html>
UserController.java
package cn.itcast.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/testInterceptor") public String testInterceptor(){ System.out.println("testInterceptor執行了..."); return "success"; }
}
結果
若是有兩個攔截器的狀況下