初学spring mvc3,跟着视频搭建了一个简单的spring mvc3项目,记录一下。
总体来说,分为几个步骤
进入正题
1、添加spring mvc必须的jar包,如图
01.png2、编写部署描述符 web.xml,如下代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0">
<display-name>springmvc01</display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 配置spring mvc dispatcherServlet -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<!-- 配置spring mvc的配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
3、编写spring mvc的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans
xsi:schemaLocation="
<!-- spring mvc注解驱动 -->
<mvc:annotation-driven />
<!-- 扫描器 -->
<context:component-scan base-package="com"/>
<!-- 试图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/view/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
4、编写controller类
package com.lizhihui.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping(value="/hello.do")
public String helloword(String username, Model model) {
model.addAttribute("helloWord", "hello:" + username);
return "index";
}
}
5、编写前台页面 index.jsp和login.jsp,如下
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
${helloWord }
</body>
</html>
login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="hello.do" method="post">
hello:<input name="username" type="text"/>
<input name="submit" type="submit" value="submit"/>
</form>
</body>
</html>