springMVC(二)—— 简单的springmvc的demo
简单的springmvc的demo
1、引入springmvc相关的jar包
2、配置DispatcherServlet 在web.xml
<servlet> <servlet-name>springMVCConfig-servlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springMVCConfig-servlet.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springMVCConfig-servlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
3、 配置springmvc的配置文件
创建一个springmvc.xml文件,并配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 配置一个HandlerMapping ,如果自己不配置HandlerMapping,会默认有一个HandlerMapping --> <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"></bean> <!-- 注册自己的Controller类 -->
<!--根据controller类的名字找到对应的Controller类,类中除了Controller首字母大写,其他的全部小写-->
<bean class="com.zhiyou100.zjc.controller.ExampleController"></bean> <!-- 配置试图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/view/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
4、书写Controller
public class ExampleController extends AbstractController{ @Override protected ModelAndView handleRequestInternal(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("index"); mav.addObject("info", "Hello SpringMVC"); return mav; } }
5、创建jsp文件看,接收信息
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> ${info } </body> </html>
6、网页中输出结果
输入http://localhost:8080/day090202/exampleController.do