这篇文章给大家分享的是有关SpringMVC框架如何实现Handler处理器的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
一、SpringMVC中的处理器
配置完SpringMVC的处理器映射器,处理适配器,视图解析器后,需要手动写处理器。关于处理器的写法有三种,无论怎么写,执行流程都是①处理映射器通过@Controller注解找到处理器,继而②通过@RequestMapping注解找到用户输入的url。下面分别介绍这三种方式。
package com.gql.springmvc;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* 类说明:
* 处理器的三种写法
* @guoqianliang1998.
*/
@Controller
public class UserController {
//1.SpringMVC开发方式
@RequestMapping("/hello")
public ModelAndView hello(){
ModelAndView mv = new ModelAndView();
mv.addObject("msg","hello world!");
mv.setViewName("index.jsp");
return mv;
}
//2.原生Servlet开发方式
@RequestMapping("xx")
public void xx(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
request.setAttribute("msg", "周冬雨");
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
//3.开发中常用
@RequestMapping("yy")
public String yy(Model model){
model.addAttribute("msg", "双笙");
return "forward:/index.jsp";//forward写不写都是转发,redirect代表重定向.
}
}
1.SpringMVC开发方式
@RequestMapping("/hello")
public ModelAndView hello(){
ModelAndView mv = new ModelAndView();
mv.addObject("msg","hello world!");
mv.setViewName("index.jsp");
return mv;
}
2.Servlet原生开发方式
@RequestMapping("xx")
public void xx(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
request.setAttribute("msg", "周冬雨");
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
3.开发中常用的方式
在return的字符串中,forward写不写都是代表转发,redirect则代表重定向。
@RequestMapping("yy")
public String yy(Model model){
model.addAttribute("msg", "双笙");
return "forward:/index.jsp";
}
感谢各位的阅读!关于“SpringMVC框架如何实现Handler处理器”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。