6、springMVC:結(jié)果跳轉(zhuǎn)方式
6.1生均、ModelAndView
設(shè)置ModelAndView對象 , 根據(jù)view的名稱 , 和視圖解析器跳到指定的頁面 .
頁面 : {視圖解析器前綴} + viewName +{視圖解析器后綴}
<!-- 視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前綴 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后綴 -->
<property name="suffix" value=".jsp" />
</bean>
對應(yīng)的controller類
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws Exception {
//返回一個模型視圖對象
ModelAndView mv = new ModelAndView();
mv.addObject("msg","ControllerTest1");
mv.setViewName("test");
return mv;
}
}
ServletAPI
通過設(shè)置ServletAPI , 不需要視圖解析器 .
1、通過HttpServletResponse進行輸出
2、通過HttpServletResponse實現(xiàn)重定向
3、通過HttpServletResponse實現(xiàn)轉(zhuǎn)發(fā)
@Controller
public class ResultGo {
@RequestMapping("/result/t1")
public void test1(HttpServletRequest req, HttpServletResponse rsp) throwsIOException {
rsp.getWriter().println("Hello,Spring BY servlet API");
}
@RequestMapping("/result/t2")
public void test2(HttpServletRequest req, HttpServletResponse rsp) throwsIOException {
rsp.sendRedirect("/index.jsp");
}
@RequestMapping("/result/t3")
public void test3(HttpServletRequest req, HttpServletResponse rsp) throwsException {
//轉(zhuǎn)發(fā)
req.setAttribute("msg","/result/t3");
req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,rsp);
}
}
SpringMVC(重點)
通過SpringMVC來實現(xiàn)轉(zhuǎn)發(fā)和重定向 - 無需視圖解析器秧荆;
測試前,需要將視圖解析器注釋掉
@Controller
public class ResultSpringMVC {
@RequestMapping("/rsm/t1")
public String test1(){
//轉(zhuǎn)發(fā)
return "/index.jsp";
}
@RequestMapping("/rsm/t2")
public String test2(){
//轉(zhuǎn)發(fā)二
return "forward:/index.jsp";
}
@RequestMapping("/rsm/t3")
public String test3(){
//重定向
return "redirect:/index.jsp";
}
}
通過SpringMVC來實現(xiàn)轉(zhuǎn)發(fā)和重定向 - 有視圖解析器埃仪;
重定向 , 不需要視圖解析器 , 本質(zhì)就是重新請求一個新地方嘛 , 所以注意路徑問題.
可以重定向到另外一個請求實現(xiàn) .
@Controller
public class ResultSpringMVC2 {
@RequestMapping("/rsm2/t1")
public String test1(){
//轉(zhuǎn)發(fā)
return "test";
}
@RequestMapping("/rsm2/t2")
public String test2(){
//重定向
return "redirect:/index.jsp";
//return "redirect:hello.do"; //hello.do為另一個請求/
}
}
7乙濒、數(shù)據(jù)處理
處理提交數(shù)據(jù)
1、提交的域名稱和處理方法的參數(shù)名一致
提交數(shù)據(jù) : http://localhost:8080/springmvc_04_controller_war_exploded/hello?name=liusen
處理方法 :
@RequestMapping("/hello")
public String hello(String name){
System.out.println(name);
return "hello";
}
后臺輸出 : liusen
2卵蛉、提交的域名稱和處理方法的參數(shù)名不一致
提交數(shù)據(jù) : http://localhost:8080/springmvc_04_controller_war_exploded/hello?name=liusen
處理方法 :
//@RequestParam("username") : username提交的域的名稱 .
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name){
System.out.println(name);
return "hello";
}
后臺輸出 : liusen
3颁股、提交的是一個對象
要求提交的表單域和對象的屬性名一致 , 參數(shù)使用對象即可
1、實體類
public class User {
private int id;
private String name;
private int age;
//構(gòu)造
//get/set
//tostring()
}
2傻丝、提交數(shù)據(jù) : http://localhost:8080/mvc04/user?name=kuangshen&id=1&age=15
3甘有、處理方法 :
@RequestMapping("/user")
public String user(User user){
System.out.println(user);
return "hello";
}
后臺輸出 : User { id=1, name='kuangshen', age=15 }
說明:如果使用對象的話,前端傳遞的參數(shù)名和對象名必須一致葡缰,否則就是null亏掀。
數(shù)據(jù)顯示到前端
第一種 : 通過ModelAndView
我們前面一直都是如此 . 就不過多解釋
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws Exception {
//返回一個模型視圖對象
ModelAndView mv = new ModelAndView();
mv.addObject("msg","ControllerTest1");
mv.setViewName("test");
return mv;
}
}
第二種 : 通過ModelMap
ModelMap
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name, ModelMap model){
//封裝要顯示到視圖中的數(shù)據(jù)
//相當于req.setAttribute("name",name);
model.addAttribute("name",name);
System.out.println(name);
return "hello";
}
第三種 : 通過Model
Model
@RequestMapping("/ct2/hello")
public String hello(@RequestParam("username") String name, Model model){
//封裝要顯示到視圖中的數(shù)據(jù)
//相當于req.setAttribute("name",name);
model.addAttribute("msg",name);
System.out.println(name);
return "test";
}
對比
就對于新手而言簡單來說使用區(qū)別就是:
Model 只有寥寥幾個方法只適合用于儲存數(shù)據(jù),簡化了新手對于Model對象的操作和理解泛释;
ModelMap 繼承了 LinkedMap 滤愕,除了實現(xiàn)了自身的一些方法,同樣的繼承 LinkedMap 的方法和特性怜校;
ModelAndView 可以在儲存數(shù)據(jù)的同時间影,可以進行設(shè)置返回的邏輯視圖,進行控制展示層的跳轉(zhuǎn)茄茁。
當然更多的以后開發(fā)考慮的更多的是性能和優(yōu)化魂贬,就不能單單僅限于此的了解。
請使用80%的時間打好扎實的基礎(chǔ)裙顽,剩下18%的時間研究框架付燥,2%的時間去學點英文,框架的官方文檔永遠是最好的教程锦庸。
8机蔗、亂碼問題
測試步驟:
1蒲祈、我們可以在首頁編寫一個提交的表單
<form action="/e/t" method="post">
<input type="text" name="name">
<input type="submit">
</form>
2甘萧、后臺編寫對應(yīng)的處理類
@Controller
public class Encoding {
@RequestMapping("/e/t")
public String test(Model model,String name){
model.addAttribute("msg",name); //獲取表單提交的值
return "test"; //跳轉(zhuǎn)到test頁面顯示輸入的值
}
}
3萝嘁、輸入中文測試,發(fā)現(xiàn)亂碼
不得不說扬卷,亂碼問題是在我們開發(fā)中十分常見的問題牙言,也是讓我們程序猿比較頭大的問題!
以前亂碼問題通過過濾器解決 , 而SpringMVC給我們提供了一個過濾器 , 可以在web.xml中配置 .
修改了xml文件需要重啟服務(wù)器怪得!
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
但是我們發(fā)現(xiàn) , 有些極端情況下.這個過濾器對get的支持不好 .
處理方法 :
1咱枉、修改tomcat配置文件 :設(shè)置編碼!
<Connector URIEncoding="utf-8" port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
2徒恋、自定義過濾器
package com.kuang.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
/**
* 解決get和post請求 全部亂碼的過濾器
*/
public class GenericEncodingFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChainchain) throws IOException, ServletException {
//處理response的字符編碼
HttpServletResponse myResponse=(HttpServletResponse) response;
myResponse.setContentType("text/html;charset=UTF-8");
// 轉(zhuǎn)型為與協(xié)議相關(guān)對象
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
// 對request包裝增強
HttpServletRequest myrequest = new MyRequest(httpServletRequest);
chain.doFilter(myrequest, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
//自定義request對象蚕断,HttpServletRequest的包裝類
class MyRequest extends HttpServletRequestWrapper {
private HttpServletRequest request;
//是否編碼的標記
private boolean hasEncode;
//定義一個可以傳入HttpServletRequest對象的構(gòu)造函數(shù),以便對其進行裝飾
public MyRequest(HttpServletRequest request) {
super(request);// super必須寫
this.request = request;
}
// 對需要增強方法 進行覆蓋
@Override
public Map getParameterMap() {
// 先獲得請求方式
String method = request.getMethod();
if (method.equalsIgnoreCase("post")) {
// post請求
try {
// 處理post亂碼
request.setCharacterEncoding("utf-8");
return request.getParameterMap();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else if (method.equalsIgnoreCase("get")) {
// get請求
Map<String, String[]> parameterMap = request.getParameterMap();
if (!hasEncode) { // 確保get手動編碼邏輯只運行一次
for (String parameterName : parameterMap.keySet()) {
String[] values = parameterMap.get(parameterName);
if (values != null) {
for (int i = 0; i < values.length; i++) {
try {
// 處理get亂碼
values[i] = new String(values[i]
.getBytes("ISO-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}
hasEncode = true;
}
return parameterMap;
}
return super.getParameterMap();
}
//取一個值
@Override
public String getParameter(String name) {
Map<String, String[]> parameterMap = getParameterMap();
String[] values = parameterMap.get(name);
if (values == null) {
return null;
}
return values[0]; // 取回參數(shù)的第一個值
}
//取所有值
@Override
public String[] getParameterValues(String name) {
Map<String, String[]> parameterMap = getParameterMap();
String[] values = parameterMap.get(name);
return values;
}
}
這個也是我在網(wǎng)上找的一些大神寫的入挣,一般情況下亿乳,SpringMVC默認的亂碼處理就已經(jīng)能夠很好的解決了!
然后在web.xml中配置這個過濾器即可径筏!
亂碼問題葛假,需要平時多注意,在盡可能能設(shè)置編碼的地方滋恬,都設(shè)置為統(tǒng)一編碼 UTF-8聊训!