spring mvc 入门配置
1. 把所需jar拷贝到工程目录下WEB-INF/lib
2. 配置WEB.xml,配置前端控制器 org.springframework.web.servlet.DispatcherServlet
<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:spring_config/applicationContext-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
3. 创建spring mvc控制核心配置:applicationContext-mvc.xml
配置控制器
<bean id="login" name="/login.do" class="com.beifeng.controller.LoginController"></bean>
配置试图解析器
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/jsp/"></property>
<!-- 后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
4.编写控制器类 LoginController 必须继承AbstractController 重写handleRequestInternal
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse arg1) throws Exception {
// TODO Auto-generated method stub
String userName = request.getParameter("userName");
String userPw = request.getParameter("userPw");
System.out.println("------我是springMVC的控制器---------");
System.out.println("账号:"+userName);
System.out.println("账号:"+userPw);
ModelAndView mav = new ModelAndView("index");
//模拟调用Model
if("admin".equals(userName) && "123".equals(userPw)){
mav.addObject("message", "用户登录成功!");
}else{
mav.addObject("message", "账号或密码错误!");
}
return mav;
}
返回数据和试图 ModelAndView mav = new ModelAndView("index");
5. 编写JSP页面 显示数据
在jsp 界面中使用{$message}即可以显示message变量