一个简单的入门实例教程
一、创建项目:
简单注解配置的实例:
1、使用MyEclipse创建一个web项目
2、为项目命名为:TestSpringMvc
3、使用MyEclipse添加Spring相应的jar包
二、配置文件:
1、首先在web.xml中配置一个DispatcherServlet,并通过<servlet-mapping>指定需要拦截的url。 下面xml中配置一个任意的url。
先配置一个servlet 然后 加载SpringMVC的xml文件到Spring的上下文中。然后配置servlet-mapping,servlet-name为刚刚的servlet中的配置的name,然后指定要拦截的url为/。
2、配置Spring的上下文监听器,并且指定Spring的xml配置文件的路径。
最终web.xml文件内容:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- 监听spring上下文容器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 加载spring的xml配置文件到 spring的上下文容器中 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 配置Spring MVC DispatcherServlet --> <servlet> <servlet-name>MVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 初始化参数 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:applicationContext.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- 配置DispatcherServlet所需要拦截的url --> <servlet-mapping> <servlet-name>MVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
3、创建SpringMVC所需要的xml文件和applicationContext的xml文件,这里由于第一步中配置的servlet中init-param所需要加载的格式为:classpath:applicationContext.xml
4、配置applicationContext.xml:
通过component-scan标签扫描指定包名,让该包下的所有java类的spring注解生效
然后配置SpringMVC的视图渲染解析器,让其前缀为/page/ 后缀为.jsp 这样能够SpringMVC 所需要渲染的路径能够在/page/返回值.jsp中寻找。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 通过component-scan 让Spring扫描org.swinglife.controller下的所有的类,让Spring的代码注解生效 --> <context:component-scan base-package="com.kd.controller"></context:component-scan> <!-- 配置SpringMVC的视图渲染器, 让其前缀为:/ 后缀为.jsp 将视图渲染到/page/<method返回值>.jsp中 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/page/" p:suffix=".jsp"> </bean> </beans>
三、编写Controller
1、创建com.kd.controller的package,用来存放Controller类,接着新建HomeController.java,用来编写首页的Controller
2、使用注解 @Controller将HomeController类定义为一个Controller,并且在方法中通过 @RequestMapping(“value”)来指定所需要访问的路径或者方法名。 SpringMVC可以通过一个@Controller注解将一个POJO转化为处理请求的控制器,通过@RequestMapping为控制器指定哪些需要的请求。
package com.kd.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HomeController {
/***
* 首页 返回至/page/home.jsp页面
* @return
*/
@RequestMapping("index")
public ModelAndView index(){
//创建模型跟视图,用于渲染页面。并且指定要返回的页面为home页面
ModelAndView mav = new ModelAndView("home");
return mav;
}
}
方法中定义了ModelAndView对象,通过该对象指定所需要渲染的视图为home最后返回ModelAndView 将页面渲染到home.jsp中。
3、最后在WebContent目录中 创建/page/home.jsp使SpringMVC能够寻找并渲染该页面视图。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'home.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h2>spring mvc 实例</h2>
<form action="login" method="post">
username:<input type="text" name="username" />
<p/>
password:<input type="password" name="password"/>
<p/>
<input type="submit" value="submit" />
</form>
<h2>对象传递参数</h2>
<form action="login2" method="post">
用户名:<input type="text" name="username" /><br/>
密 码:<input type="password" name="password" />
<input type="submit" value="提交" />
</form>
<a href="other">other page</a>
</body>
</html>
现在一个完整的SpringMVC的模式已经搭建完成了,可以运行项目来进行测试。
四、编写参数的提交与传递:
1、编写一个新的UserController类来假定用户登录,将username,password提交到Controller中进行处理,并且登陆成功后将username,password传递到成功的页面。
创建UserController.java
创建/page/succ.jsp页面 作为用户成功登陆页面
UserController中的代码:
package com.kd.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.kd.model.User;
/***
* 用户控制器
*
* @author swinglife
*
*/
@Controller
public class UserController {
/***
* 用户登陆
* <p>
* 注解配置,只允许POST提交到该方法
*
* @param username
* @param password
* @return
*/
@RequestMapping(value = "login", method = RequestMethod.POST)
public ModelAndView login(String username, String password) {
// 验证传递过来的参数是否正确,否则返回到登陆页面。
if (this.checkParams(new String[] { username, password })) {
// 指定要返回的页面为succ.jsp
ModelAndView mav = new ModelAndView("succ");
// 将参数返回给页面
mav.addObject("username", username);
mav.addObject("password", password);
return mav;
}
return new ModelAndView("home");
}
@RequestMapping(value = "login2", method = RequestMethod.POST)
public ModelAndView login(@ModelAttribute("user")User user) { //对象传参数
//如果传过来的对象不为空,则跳转成功页面
if (user != null) {
ModelAndView mav = new ModelAndView("succ");
System.out.println(user.getUsername() + "\t" + user.getPassword());
mav.addObject("user", user);
return mav;
}
return new ModelAndView("home");
}
// /***
// * 另一种参数传递的形式
// * 通过request来处理请求过来的参数。
// * @param username
// * @param password
// * @param request
// * @return
// */
// @RequestMapping(value="login",method=RequestMethod.POST)
// public ModelAndView login(String username,String
// password,HttpServletRequest request){
// request.setAttribute("username", username);
// request.setAttribute("password", password);
// return new ModelAndView("succ");
// }
/***
* 验证参数
*
* @param params
* @return
*/
private boolean checkParams(String[] params) {
for (String param : params) {
if (param == "" || param == null || param.isEmpty()) {
return false;
}
}
return true;
}
}
首先指定@Controller,然后指定@RequestMapping为login方法;
需要注意的是这次@RequestMapping中指定了页面方法模式必须为POST模式否则将无法访问。其次value参数指定访问路径。
并且在login方法中设定带参,参数为表单中的name属性。
然后通过ModelAndView的 addObject方法将参数加入到request中,这样则能够在返回的页面中显示这些参数。
在此之外还有其他将参数传递到页面中的方式为:
/***
* 另一种参数传递的形式
* 通过request来处理请求过来的参数。
* @param username
* @param password
* @param request
* @return
*/
@RequestMapping(value="login",method=RequestMethod.POST)
public ModelAndView login(String username,String
password,HttpServletRequest request){
request.setAttribute("username", username);
request.setAttribute("password", password);
return new ModelAndView("succ");
}
以上这种方式则是直接通过将参数加入到request中来使用。
2、编写succ.jsp页面跟表单页面:
succ.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'succ.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h2>登陆</h2>
username:${username }<br/>
password:${password }<br/>
<h2>对象传值登录</h2>
用户名:${user.username }
密 码:${user.password }
</body>
</html>
3、最后运行项目来进行测试:
附件中有源代码,包要自己导入。