Spring 之 示例(Java之负基础实战)

  接 Spring 之 配置 里面的代码。

  现在要进行Controller的开发。

1.引用类

import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

 2.实现Controller

public class IndexAction implements Controller {

    @Override
    public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

}

   该实体就是要返回一个ModelAndView,用于展示结果。

3.具体实现

3.1.声明对应的view

特别注意的是,这里的view ,对应的是Spring 之 配置里面的view,名称要一样的。

    <bean id="IndexAction" class="com.myweb.IndexAction">
        <property name="view">
            <value>index</value>
        </property>
    </bean>

<property name = "view"> 里面的 view,一定要和下面声明的名称是一样的。

    public String view;

    public String getView() {
        return view;
    }

    public void setView(String view) {
        this.view = view;
    }

  用工具自动实现。

 3.2.实现

package com.myweb;

import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class IndexAction implements Controller {
    
    public String view;

    public String getView() {
        return view;
    }

    public void setView(String view) {
        this.view = view;
    }



    @Override
    public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {

        ModelAndView mv = new ModelAndView(view);
        return mv;
    }

}
返回ModelAndView

里面的ModelAndView mv = new ModelAndView(view); 可以替换成ModelAndView mv = new ModelAndView(“index”);

3.3.配置classes路径

  如果不配置,tomcat会找不到刚才生成的class,路径为myweb/webapp/WEB-INF/classes。这个是固定位置的固定名称,就是在WEB-INF下面,叫做classes。

原文地址:https://www.cnblogs.com/SimonGao/p/4913059.html