Spring MVC:控制器类名称处理映射

控制器类名称处理映射的好好处是:

如果项目是hello,WelcomeController是控制器,那么访问地址是:

http://localhost:8080/hello/welcome

http://localhost:8080/hello/welcome.html

http://localhost:8080/hello/welcomeaaa.html

http://localhost:8080/hello/welcome([a-zA-Z*]).html 这样的无限配置

需要引入相应的类

<bean        class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" /> 

然后接着添加想要访问的控制器类bean如:

<bean class="chapter2.web.controller.HelloController" />
<bean class="chapter2.web.controller.WelcomeController" />

  

来看实例:

WelcomeController.java

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

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

public class WelcomeController extends AbstractController {

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		ModelAndView mv = new ModelAndView("welcome");
		mv.addObject("message", "welcome spring mvc!");
		return mv;
	}

} 

在xxx-servlet.xml中添加支持的spring类

<!-- 控制器类名称处理映射 -->     
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />  
<bean class="chapter2.web.controller.WelcomeController"/>

welcome.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"  pageEncoding="utf-8"%>
<%@ page isELIgnored="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>welcome</title>
</head>
<body>


<h2>welcome</h2>
${message}

</body>
</html>

  

运行项目:

http://localhost:8080/hello/welcome

http://localhost:8080/hello/welcome.html

http://localhost:8080/hello/welcomeaaa.html

  

猜你喜欢

转载自www.cnblogs.com/achengmu/p/8930259.html
今日推荐