您的位置:首页 > 编程语言 > Java开发

基于注解的 Spring MVC 简单入门

2010-08-21 10:00 477 查看
web.xml

配置:

源码
打印


<
servlet
>

<
servlet-name
>
dispatcher
</
servlet-name
>

<
servlet-class
>
org.springframework.web.servlet.DispatcherServlet
</
servlet-class
>

<
init-param
>

<
description
>
加载/WEB-INF/spring-mvc/目录下的所有XML作为Spring MVC
的配置文件
</
description
>

<
param-name
>
contextConfigLocation
</
param-name
>

<
param-value
>
/WEB-INF/spring-mvc/*.xml
</
param-value
>

</
init-param
>

<
load-on-startup
>
1
</
load-on-startup
>

</
servlet
>

<
servlet-mapping
>

<
servlet-name
>
dispatcher
</
servlet-name
>

<
url-pattern
>
*.htm
</
url-pattern
>

</
servlet-mapping
>

<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<description>加载/WEB-INF/spring-mvc/目录下的所有XML作为Spring MVC的配置文件</description>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc/*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>


这样,所有的
.htm
的请求,都会被
DispatcherServlet
处理;

初始化 DispatcherServlet 时,该框架在 web 应用程序WEB-INF
目录中寻找一个名为[servlet-名称]
-
servlet.xml
的文件,并在那里定义相关的
Beans
,重写在全局中定义的任何
Beans
,像上面的
web.xml
中的代码,对应的是dispatcher
-servlet.xml
;当然也可以使用
<init-param>
元素,手动指定配置文件的路径;

dispatcher
-servlet.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"

xmlns:mvc
=
"http://www.springframework.org/schema/mvc"

xmlns:p
=
"http://www.springframework.org/schema/p"

xmlns:context
=
"http://www.springframework.org/schema/context"

xmlns:aop
=
"http://www.springframework.org/schema/aop"

xmlns:tx
=
"http://www.springframework.org/schema/tx"

xsi:schemaLocation
="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!--

使Spring支持自动检测组件,如注解的Controller

-->

<
context:component-scan

base-package
=
"com.minx.crm.web.controller"
/>

<
bean

id
=
"viewResolver"

class
=
"org.springframework.web.servlet.view.InternalResourceViewResolver"

p:prefix
=
"/WEB-INF/jsp/"

p:suffix
=
".jsp"

/>

</
beans
>

<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!--
使Spring支持自动检测组件,如注解的Controller
-->
<context:component-scan base-package="com.minx.crm.web.controller"/>

<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
</beans>


第一个
Controller


源码
打印


package
com.minx.crm.web.controller;

import
org.springframework.stereotype.Controller;

import
org.springframework.web.bind.annotation.RequestMapping;

@Controller

public

class
IndexController {

@RequestMapping
(
"/index"
)

public
String index() {

return

"index"
;

}

}

package com.minx.crm.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping("/index")
public String index() {
return "index";
}
}

@Controller
注解标识一个控制器,
@RequestMapping
注解标记一个访问的路径(
/index.htm
),
return "index"
标记返回视图(
index.jsp
);

注:如果
@RequestMapping
注解在类级别上,则表示一相对路径,在方法级别上,则标记访问的路径;


@RequestMapping
注解标记的访问路径中获取参数:


Spring MVC

支持
RESTful
风格的
URL
参数,如:

源码
打印


@Controller

public

class
IndexController {

@RequestMapping
(
"/index/{username}"
)

public
String index(
@PathVariable
(
"username"
) String username) {

System.out.print(username);

return

"index"
;

}

}

@Controller
public class IndexController {

@RequestMapping("/index/{username}")
public String index(@PathVariable("username") String username) {
System.out.print(username);
return "index";
}
}


@RequestMapping
中定义访问页面的
URL
模版,使用
{}
传入页面参数,使用
@PathVariable

获取传入参数,即可通过地址: http://localhost:8080/crm/index/tanqimin.htm
访问;

根据不同的
Web
请求方法,映射到不同的处理方法:


使用登陆页面作示例,定义两个方法分辨对使用
GET
请求和使用
POST
请求访问
login.htm
时的响应。
可以使用处理
GET
请求的方法显示视图,
使用
POST
请求的方法处理业务逻辑


源码
打印


@Controller

public

class
LoginController {

@RequestMapping
(value =
"/login"
, method = RequestMethod.GET)

public
String login() {

return

"login"
;

}

@RequestMapping
(value =
"/login"
, method = RequestMethod.POST)

public
String login2(HttpServletRequest request) {

String username = request.getParameter("username"
).trim();

System.out.println(username);

return

"login2"
;

}

}

@Controller
public class LoginController {
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login() {
return "login";
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login2(HttpServletRequest request) {
String username = request.getParameter("username").trim();
System.out.println(username);
return "login2";
}
}

在视图页面,通过地址栏访问
login.htm
,是通过
GET
请求访问页面,因此,返回登陆表单视图
login.jsp
;当在登陆表单中使用
POST
请求提交数据时,则访问
login2
方法,处理登陆业务逻辑;

防止重复提交数据,可
以使用重定向视图:

源码
打印


return

"redirect:/login2"

return "redirect:/login2"

可以传入方法的参数类型:

源码
打印


<strong>
@RequestMapping
(value =
"login"
, method = RequestMethod.POST)

public
String testParam(HttpServletRequest request, HttpServletResponse response, HttpSession session) {

String username = request.getParameter("username"
);

System.out.println(username);

return

null
;

}</strong>

@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
String username = request.getParameter("username");
System.out.println(username);
return null;
}


可以传入
HttpServletRequest

HttpServletResponse

HttpSession
,值得注意的是,如果第一次访问页面,
HttpSession
没被创建,可能会出错;

其中,String username = request.getParameter("username");

以转换为传入的参数:

源码
打印


@RequestMapping
(value =
"login"
, method = RequestMethod.POST)

public
String testParam(HttpServletRequest request, HttpServletResponse response, HttpSession session,
@RequestParam
(
"username"
) String username) {

String username = request.getParameter("username"
);

System.out.println(username);

return

null
;

}

@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(HttpServletRequest request, HttpServletResponse response, HttpSession session,@RequestParam("username") String username) {
String username = request.getParameter("username");
System.out.println(username);
return null;
}


使用
@RequestParam

注解获取
GET
请求或
POST
请求提交的参数;

获取
Cookie
的值:使用
@CookieValue




获取
PrintWriter


可以直接在
Controller
的方法中传入
PrintWriter
对象,就可以在方法中使用:

源码
打印


@RequestMapping
(value =
"login"
, method = RequestMethod.POST)

public
String testParam(PrintWriter out,
@RequestParam
(
"username"
) String username) {

out.println(username);

return

null
;

}

@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(PrintWriter out, @RequestParam("username") String username) {
out.println(username);
return null;
}


获取表单中提交的值,并封装

POJO
中,传入
Controller
的方法里:


POJO
如下(
User.java
):

源码
打印


public

class
User{

private

long
id;

private
String username;

private
String password;

…此处省略
getter,setter...

}

public class User{
private long id;
private String username;
private String password;

…此处省略getter,setter...
}


通过表单提交,直接可以把表单值封装到
User
对象中:

源码
打印


@RequestMapping
(value =
"login"
, method = RequestMethod.POST)

public
String testParam(PrintWriter out, User user) {

out.println(user.getUsername());

return

null
;

}

@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(PrintWriter out, User user) {
out.println(user.getUsername());
return null;
}


可以把对象,
put

入获取的
Map
对象中,传到对应的视图:




源码
打印


<strong>
@RequestMapping
(value =
"login"
, method = RequestMethod.POST)

public
String testParam(User user, Map model) {

model.put("user"
,user);

return

"view"
;

}</strong>

@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(User user, Map model) {
model.put("user",user);
return "view";
}


在返回的
view.jsp
中,就可以根据
key
来获取
user
的值(通过
EL
表达式,
${user }
即可);

Controller
中方法的返回值:


void
:多数用于使用
PrintWriter
输出响应数据;

String

类型
:返回该
String
对应的
View Name


任意类型对象:
返回
ModelAndView


自定义视图(
JstlView

ExcelView
):


拦截器(
Inteceptors
):




源码
打印


<strong>
public

class
MyInteceptor
implements
HandlerInterceptor {

public

boolean
preHandle(HttpServletRequest request, HttpServletResponse response, Object o)

throws
Exception {

return

false
;

}

public

void
postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView mav)

throws
Exception {

}

public

void
afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception excptn)

throws
Exception {

}

}</strong>

public class MyInteceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o)
throws Exception {
return false;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView mav)
throws Exception {
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception excptn)
throws Exception {
}
}


拦截器需要实现
HandleInterceptor
接口,并实现其三个方法:

preHandle:拦截器的前端,执行控制器之前所要处理的方法,通常用于权限控制、日志,其中,
Object o
表示下一个拦截器;

postHandle
:控制器的方法已经执行完毕,转换成视图之前的处
理;

afterCompletion
:视图已处理完后执行的方法,通常用于
释放资源;


MVC
的配置文件中,配置拦截器与需要拦截的
URL


源码
打印


<
mvc:interceptors
>

<
mvc:interceptor
>

<
mvc:mapping

path
=
"/index.htm"

/>

<
bean

class
=
"com.minx.crm.web.interceptor.MyInterceptor"

/>

</
mvc:interceptor
>

</
mvc:interceptors
>

<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/index.htm" />
<bean class="com.minx.crm.web.interceptor.MyInterceptor" />
</mvc:interceptor>
</mvc:interceptors>


国际化:


MVC
配置文件中,配置国际化属性文件:

源码
打印


<
bean

id
=
"messageSource"

class
=
"org.springframework.context.support.ResourceBundleMessageSource"

p:basename
=
"message"
>

</
bean
>

<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource"
p:basename="message">
</bean>


那么,
Spring
就会在项目中搜索相关的国际化属性文件,如:
message.properties

message_zh_CN.properties


VIEW
中,
引入
Spring

签:<%@taglib uri=" http://www.springframework.org/tags
" prefix="spring" %>,使用
<spring:message
code="key" />
调用,即可;

如果一种语言,有多个语言文件,可以更改
MVC
配置文件为:

源码
打印


<
bean

id
=
"messageSource"

class
=
"org.springframework.context.support.ResourceBundleMessageSource"
>

<
property

name
=
"basenames"
>

<
list
>

<
value
>
message01
</
value
>

<
value
>
message02
</
value
>

<
value
>
message03
</
value
>

</
list
>

</
property
>

</
bean
>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息