一、在使用ssm框架的时候,从前端发送get请求到后端处理数据的完整流程是:
@WebServlet(name = "getAll", value = "/getAll")
public class AddServelet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//设置请求编码格式req.setCharacterEncoding("utf-8");
//设置相应编码格式resp.setCharacterEncoding("utf-8");resp.setContentType("text/html;charset=utf-8");//创建业务层对象StudentService studentService = new StudentServiceImpl()();//获取请求数据: 请求数据需要自己单独编写代码获取,并且编写相关类型转换的代码!Integer pageIndex = 1;Integer pageNum = 3 ;String page = request.getParameter("pageIndex");if (page!=null){pageIndex = Integer.valueOf(page);}String stuName = request.getParameter("stuName");//处理请求PageInfo all = studentService .getAll(pageIndex, pageNum, stuName);//响应结果//直接响应//请求转发//重定向request.setAttribute("info",all);request.getRequestDispatcher("/index.jsp").forward(request,response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
}
1)自己创建一个自定义的getAllServelet 去继承原有的HttpServlet.
getAllServelet接收到get请求首先调用service方法,根据请求的方法参数,具体是调用doGet()或者是doPost()方法或者是其他对应的方法。
所以首先需要重写service方法或者是doGet()方法。
②)重写doGet()方法5步实现业务逻辑。
1)
设置请求编码格式
设置相应编码格式
2)创建业务层对象
3)获取请求数据: 请求数据需要自己单独编写代码获取,并且编写相关类型转换的代码!
4)处理请求
5)响应结果:
直接响应
请求转发
重定向
二、只使用spring框架
跟ssm框架步骤一样,只不过这个时候不在通过new关键字来创建对象
而是使用spring框架的容器获取bean对象
这时需要手动获取spring容器对象。
这里重写service方法,和重写doGet()方法其实一样
public class BookServlet extends HttpServlet {//声明业务层属性private BookService bookService;//重写init方法:init,完成Spring容器中相关资源和Servlet的初始化!!@Overridepublic void init() throws ServletException {//创建Spring容器对象ApplicationContext ac= WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());//获取业务层beanbookService= (BookService) ac.getBean("bookServiceImpl");}//重写service方法@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//设置请求编码格式req.setCharacterEncoding("utf-8");//设置相应编码格式resp.setCharacterEncoding("utf-8");resp.setContentType("text/html;charset=utf-8");//创建业务层对象BookService bookService = new BookServiceImpl();// 获取请求数据: 请求数据需要自己单独编写代码获取,并且编写相关类型转换的代码!String aa = req.getParameter("aa");//处理请求List<Book> books = bookService.selectAllBookService();System.out.println("今天天气不错,适合学习!!");//响应结果//直接响应resp.getWriter().write(books.toString());//请求转发//重定向} }
三、使用spring框架和springmvc框架
还是ssm框架的两大步5小步。不过这时候只需要转心处理5小步中的业务处理和响应结果。其他的事情统统由spring框架和springmvc框架搞定了。
1)所有对象都不需要手动创建了
spring.xml和springmvc.xml实际上在运行时被解析成了两个对象,把它们叫做spring容器和springmvc容器。
实质上这两个对象就是两个map键值对集合。
并且通过扫描包路径将所有对象全部放在集合中。
2)servelet也不需要手动创建
spring相关包提供了一个DispatcherServlet类,在web.xml中配置该类对象,并且设置servelet拦截的话,所有请求就都有该类来处理。
这里面的<init-param>标签实质上是将springmvc容器注入给dispatcherServlet对象.
并且请求参数的获取也由该对象实现了.
3)doGet()跑去哪了?
这个时候引入了Controller类,也就是路由和调用对应方法.实质上代替了ssm框架的
doGet()方法.最后由dispatcherServlet对象拦截url和调用Controller中对应url的方法.
四 、图解: