我想在Spring MVC中重写servlet控制流,这是我的
Servlet中的doGet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");

        String path = request.getParameter("path");

        if (path != null && path.equals("register")) {
            RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/views/system/registeruser.jsp");
            view.forward(request, response);
        } else if (path != null && path.equals("usermang")) {
            RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/views/system/manageuser.jsp");
            view.forward(request, response);
        }

    else {
            PrintWriter out = response.getWriter();
            out.print("Served at: " + request.getContextPath());
            RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/views/system/index.jsp");
            view.forward(request, response);
        }
    }


我想使用模型和视图将上面的doGET转换为Spring RequestMapping


@RequestMapping(value ="/grcon" ,method = RequestMethod.GET)
    public ModelAndView getGrcon()

        ModelAndView modegeron = new ModelAndView("index");

if (path != null && path.equals("register")) {
      view = request.getRequestDispatcher("/WEB-INF/views/system/registeruser.jsp");

        return modegeron;

    }
}

最佳答案

您正在使其变得复杂,请使用spring的力量为您处理复杂性。

对于初学者,将InternalResourceViewResolver添加到您的配置中,这将处理视图到资源的转换。

<bean id="viewResolver" class="InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/system/" />
    <property name="suffix" value=".jsp" />
</bean>


接下来,在您的params中添加@RequestMapping元素,以进一步指定映射。

@RequestMapping(value ="/grcon", method = RequestMethod.GET, params="path=register")
public String register() {
    return "registeruser";
}

@RequestMapping(value ="/grcon", method = RequestMethod.GET, params="path= usermang")
public String manageUser() {
    return "manageuser";
}

@RequestMapping(value ="/grcon", method = RequestMethod.GET)
public String index() {
    return "index";
}


或使用具有@RequestParam的方法并返回适当的视图。进行String比较时的小技巧将静态值放在第一位,为您节省了null检查。

@RequestMapping(value ="/grcon", method = RequestMethod.GET)
public String register(@RequestParam(value="path", required=false) String path) {
    if ("register".equals(path) ) {
        return "registeruser";
    } else if ("usermang".equals(path)) {
        return "manageuser";
    }
    return "index";
}


但是,通常您还希望对Model做一些准备,因此第一个可能更适用。

09-10 08:18
查看更多