springmvc程序案例1
1创建一个web工程2导入springmvc的jar文件3在web.xml中配置前端控制器 springmvcorg.springframework.web.servlet.DispatcherServletcontextConfigLocationclasspath:springmvc.xmls
·
1创建一个web工程
2导入springmvc的jar文件
3在web.xml中配置前端控制器
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
4在springmvc.xml文件中配置处理器映射器
<!-- 配置处理器映射器 -:根据自定义Bean的name属性的url去寻找执行类->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
5配置处理器适配器
<!-- 配置处理器适配器 负责执行UserController -->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
6自定义类UserController
package cn.itcast.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class UserController implements Controller{
@Override
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView mvAndView = new ModelAndView() ;
mvAndView.addObject("hello", "I love too");
//
//mvAndView.setViewName("/WEB-INF/jsps/index.jsp");
mvAndView.setViewName("index");
return mvAndView;
}
}
创建的页面
<body>
<h1>${hello}</h1>
</body>
7配置自定义UserController的bean
<!-- 配置自定义bean 这个name属性值就是url访问地址-->
<bean name="/hello.do" class="cn.itcast.controller.UserController"></bean>
8配置视图解析器:
如果controller使用逻辑视图,必须配置视图解析器
<!-- 配置视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsps/"></property>
<property name="suffix" value=".jsp"></property></bean>
9加载springmvc.xml
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
10访问 项目名+自定义controller的Bean的name属性的url
http://localhost:8080/springmvc1/hello.do
更多推荐
已为社区贡献1条内容
所有评论(0)