spring框架学习方法?

&re: Spring MVC框架学习笔记 之 View技术&&&&
阅读排行榜
评论排行榜Spring 注解学习手札(一) 构建简单Web应用 - Snowolf的意境空间! - ITeye技术网站
博客分类:
近来工作发生了一些变化,有必要学习一下Spring注解了!
网上找了一些个例子,总的说来比较土,大多数是转载摘抄,按照提示弄下来根本都运行不了,索性自己趟一遍这浑水,在这里留下些个印记。
这次,先来构建一个极为简单的web应用,从controller到dao。不考虑具体实现,只是先对整体架构有一个清晰的了解。日后在分层细述每一层的细节。
相关参考:
我们将用到如下jar包:
引用
aopalliance-1.0.jar
commons-logging-1.1.1.jar
log4j-1.2.15.jar
spring-beans-2.5.6.jar
spring-context-2.5.6.jar
spring-context-support-2.5.6.jar
spring-core-2.5.6.jar
spring-tx-2.5.6.jar
spring-web-2.5.6.jar
spring-webmvc-2.5.6.jar
先看web.xml
&?xml version="1.0" encoding="UTF-8"?&
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="/xml/ns/javaee"
xmlns:web="/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="/xml/ns/javaee /xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID"
version="2.5"&
&display-name&spring&/display-name&
&!-- 应用路径 --&
&context-param&
&param-name&webAppRootKey&/param-name&
&param-value&spring.webapp.root&/param-value&
&/context-param&
&!-- Log4J 配置
&context-param&
&param-name&log4jConfigLocation&/param-name&
&param-value&classpath:log4j.xml&/param-value&
&/context-param&
&context-param&
&param-name&log4jRefreshInterval&/param-name&
&param-value&60000&/param-value&
&/context-param&
&!--Spring上下文 配置
&context-param&
&param-name&contextConfigLocation&/param-name&
&param-value&/WEB-INF/applicationContext.xml&/param-value&
&/context-param&
&!-- 字符集 过滤器
&filter-name&CharacterEncodingFilter&/filter-name&
&filter-class&org.springframework.web.filter.CharacterEncodingFilter&/filter-class&
&init-param&
&param-name&encoding&/param-name&
&param-value&UTF-8&/param-value&
&/init-param&
&init-param&
&param-name&forceEncoding&/param-name&
&param-value&true&/param-value&
&/init-param&
&filter-mapping&
&filter-name&CharacterEncodingFilter&/filter-name&
&url-pattern&/*&/url-pattern&
&/filter-mapping&
&!-- Spring 监听器 --&
&listener&
&listener-class&org.springframework.web.context.ContextLoaderListener&/listener-class&
&/listener&
&listener&
&listener-class&org.springframework.web.util.Log4jConfigListener&/listener-class&
&/listener&
&!-- Spring 分发器 --&
&servlet-name&spring&/servlet-name&
&servlet-class&org.springframework.web.servlet.DispatcherServlet&/servlet-class&
&init-param&
&param-name&contextConfigLocation&/param-name&
&param-value&/WEB-INF/servlet.xml&/param-value&
&/init-param&
&/servlet&
&servlet-mapping&
&servlet-name&spring&/servlet-name&
&url-pattern&*.do&/url-pattern&
&/servlet-mapping&
&welcome-file-list&
&welcome-file&index.html&/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&
&/web-app&
有不少人问我,这段代码是什么:
&!-- 应用路径 --&
&context-param&
&param-name&webAppRootKey&/param-name&
&param-value&spring.webapp.root&/param-value&
&/context-param&
这是当前应用的路径变量,也就是说你可以在其他代码中使用${spring.webapp.root}指代当前应用路径。我经常用它来设置log的输出目录。
为什么要设置参数log4jConfigLocation?
&!-- Log4J 配置
&context-param&
&param-name&log4jConfigLocation&/param-name&
&param-value&classpath:log4j.xml&/param-value&
&/context-param&
&context-param&
&param-name&log4jRefreshInterval&/param-name&
&param-value&60000&/param-value&
&/context-param&
这是一种基本配置,spring中很多代码使用了不同的日志接口,既有log4j也有commons-logging,这里只是强制转换为log4j!并且,log4j的配置文件只能放在classpath根路径。同时,需要通过commons-logging配置将日志控制权转交给log4j。同时commons-logging.properties必须放置在classpath根路径。
commons-logging内容:
mons.logging.Log=mons.logging.impl.Log4JLogger
最后,记得配置log4j的监听器:
&listener&
&listener-class&org.springframework.web.util.Log4jConfigListener&/listener-class&
&/listener&
接下来,我们需要配置两套配置文件,applicationContext.xml和servlet.xml。
applicationContext.xml用于对应用层面做整体控制。按照分层思想,统领service层和dao层。servlet.xml则单纯控制controller层。
&?xml version="1.0" encoding="UTF-8"?&
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"&
resource="service.xml" /&
resource="dao.xml" /&
applicationContext.xml什么都不干,它只管涉及到整体需要的配置,并且集中管理。
这里引入了两个配置文件service.xml和dao.xml分别用于业务、数据处理。
service.xml
&?xml version="1.0" encoding="UTF-8"?&
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"&
&context:component-scan
base-package="org.zlex.spring.service" /&
注意,这里通过&context:component-scan /&标签指定了业务层的基础包路径——“org.zlex.spring.service”。也就是说,业务层相关实现均在这一层。这是有必要的分层之一。
dao.xml
&?xml version="1.0" encoding="UTF-8"?&
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:tx="http://www.springframework.org/schema/tx"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd"&
&context:component-scan
base-package="org.zlex.spring.dao" /&
dao层如法炮制,包路径是"org.zlex.spring.dao"。从这个角度看,注解还是很方便的!
最后,我们看看servlet.xml
&?xml version="1.0" encoding="UTF-8"?&
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"&
&context:component-scan
base-package="org.zlex.spring.controller" /&
id="urlMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /&
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /&
包路径配置就不细说了,都是一个概念。最重要的时候后面两个配置,这将使得注解生效!
“org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping”是默认实现,可以不写,Spring容器默认会默认使用该类。
“org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter”直接关系到多动作控制器配置是否可用!
简单看一下代码结构,如图:
Account类是来存储账户信息,属于域对象,极为简单,代码如下所示:
Account.java
package org.zlex.spring.
import java.io.S
* @author &a href="mailto:zlex."&梁栋&/a&
* @version 1.0
* @since 1.0
public class Account implements Serializable {
private static final long serialVersionUID = -372178L;
* @param username
* @param password
public Account(String username, String password) {
this.username =
this.password =
* @return the username
public String getUsername() {
* @param username the username to set
public void setUsername(String username) {
this.username =
* @return the password
public String getPassword() {
* @param password the password to set
public void setPassword(String password) {
this.password =
通常,在构建域对象时,需要考虑该对象可能需要进行网络传输,本地缓存,因此建议实现序列化接口Serializable&
我们再来看看控制器,这就稍微复杂了一点代码如下所示:
AccountController .java
package org.zlex.spring.
import javax.servlet.http.HttpServletR
import javax.servlet.http.HttpServletR
import org.springframework.beans.factory.annotation.A
import org.springframework.stereotype.C
import org.springframework.web.bind.ServletRequestU
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.RequestM
import org.zlex.spring.service.AccountS
* @author &a href="mailto:zlex."&梁栋&/a&
* @version 1.0
* @since 1.0
@Controller
@RequestMapping("/account.do")
public class AccountController {
@Autowired
private AccountService accountS
@RequestMapping(method = RequestMethod.GET)
public void hello(HttpServletRequest request, HttpServletResponse response)
throws Exception {
String username = ServletRequestUtils.getRequiredStringParameter(
request, "username");
String password = ServletRequestUtils.getRequiredStringParameter(
request, "password");
System.out.println(accountService.verify(username, password));
分段详述:
@Controller
@RequestMapping("/account.do")
这两行注解,@Controller是告诉Spring容器,这是一个控制器类,@RequestMapping("/account.do")是来定义该控制器对应的请求路径(/account.do)
@Autowired
private AccountService accountS
这是用来自动织入业务层实现AccountService,有了这个注解,我们就可以不用写setAccountService()方法了!
同时,JSR-250标准注解,推荐使用@Resource来代替Spring专有的@Autowired注解。
引用Spring 不但支持自己定义的@Autowired注解,还支持几个由JSR-250规范定义的注解,它们分别是@Resource、@PostConstruct以及@PreDestroy。
  @Resource的作用相当于@Autowired,只不过@Autowired按byType自动注入,而@Resource默认按 byName自动注入罢了。@Resource有两个属性是比较重要的,分别是name和type,Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不指定name也不指定type属性,这时将通过反射机制使用byName自动注入策略。
  @Resource装配顺序
  1. 如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常
  2. 如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常
  3. 如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常
  4. 如果既没有指定name,又没有指定type,则自动按照byName方式进行装配(见2);如果没有匹配,则回退为一个原始类型(UserDao)进行匹配,如果匹配则自动装配;
  1.6. @PostConstruct(JSR-250)
在方法上加上注解@PostConstruct,这个方法就会在Bean初始化之后被Spring容器执行(注:Bean初始化包括,实例化Bean,并装配Bean的属性(依赖注入))。
这有点像ORM最终被JPA一统天下的意思! 大家知道就可以了,具体使用何种标准由项目说了算!
最后,来看看核心方法:
@RequestMapping(method = RequestMethod.GET)
public void hello(HttpServletRequest request, HttpServletResponse response)
throws Exception {
String username = ServletRequestUtils.getRequiredStringParameter(
request, "username");
String password = ServletRequestUtils.getRequiredStringParameter(
request, "password");
System.out.println(accountService.verify(username, password));
注解@RequestMapping(method = RequestMethod.GET)指定了访问方法类型。
注意,如果没有用这个注解标识方法,Spring容器将不知道那个方法可以用于处理get请求!
对于方法名,我们可以随意定!方法中的参数,类似于“HttpServletRequest request, HttpServletResponse response”,只要你需要方法可以是有参也可以是无参!
解析来看Service层,分为接口和实现:
AccountService.java
package org.zlex.spring.
* @author &a href="mailto:zlex."&梁栋&/a&
* @version 1.0
* @since 1.0
public interface AccountService {
* 验证用户身份
* @param username
* @param password
boolean verify(String username, String password);
接口不需要任何Spring注解相关的东西,它就是一个简单的接口!
重要的部分在于实现层,如下所示:
AccountServiceImpl.java
package org.zlex.spring.service.
import org.springframework.beans.factory.annotation.A
import org.springframework.stereotype.S
import org.springframework.transaction.annotation.T
import org.zlex.spring.dao.AccountD
import org.zlex.spring.domain.A
import org.zlex.spring.service.AccountS
* @author &a href="mailto:zlex."&梁栋&/a&
* @version 1.0
* @since 1.0
@Transactional
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountD
* (non-Javadoc)
* @see org.zlex.spring.service.AccountService#verify(java.lang.String,
* java.lang.String)
public boolean verify(String username, String password) {
Account account = accountDao.read(username);
if (password.equals(account.getPassword())) {
注意以下内容:
@Transactional
注解@Service用于标识这是一个Service层实现,@Transactional用于控制事务,将事务定位在业务层,这是非常务实的做法!
接下来,我们来看持久层:AccountDao和AccountDaoImpl类
AccountDao.java
package org.zlex.spring.
import org.zlex.spring.domain.A
* @author &a href="mailto:zlex."&梁栋&/a&
* @version 1.0
* @since 1.0
public interface AccountDao {
* 读取用户信息
* @param username
Account read(String username);
这个接口就是简单的数据提取,无需任何Spring注解有关的东西!
再看其实现类:
AccountDaoImpl.java
package org.zlex.spring.dao.
import org.springframework.stereotype.R
import org.zlex.spring.dao.AccountD
import org.zlex.spring.domain.A
* @author &a href="mailto:zlex."&梁栋&/a&
* @version 1.0
* @since 1.0
@Repository
public class AccountDaoImpl implements AccountDao {
/* (non-Javadoc)
* @see org.zlex.spring.dao.AccountDao#read(java.lang.String)
public Account read(String username) {
return new Account(username,"wolf");
这里只需要注意注解:
@Repository
意为持久层,Dao实现这层我没有过于细致的介绍通过注解调用ORM或是JDBC来完成实现,这些内容后续细述!
这里我们没有提到注解@Component,共有4种“组件”式注解:
引用&
@Component:可装载组件&
@Repository:持久层组件&
@Service:服务层组件&
@Controller:控制层组件
这样spring容器就完成了控制层、业务层和持久层的构建。
启动应用,访问
观察控制台,如果得到包含“true”的输出,本次构建就成功了!
代码见附件!
顺便说一句:在Spring之前的XML配置中,如果你想在一个类中获得文件可以通过在xml配置这个类的某个属性。在注解的方式(Spring3.0)中,你可以使用@Value来指定这个文件。
例如,我们想要在一个类中获得一个文件,可以这样写:
@Value("/WEB-INF/database.properties")
private File databaseC
如果这个properties文件已经正常在容器中加载,可以直接这样写:
@Value("${jdbc.url}")
private S
获得这个url参数!&
容器中加载这个Properties文件:
&util:properties id="jdbc" location="/WEB-INF/database.properties"/&
这样,我们就能通过注解@Value获得/WEB-INF/database.properties这个文件!
如果我们想要获得注入在xml中的某个类,例如dataSource(&bean id ="dataSource"&)可以在注解的类中这么写:
@Resource(name = "dataSource")
private BasicDataSource dataS
如果只有这么一个类使用该配置文件:
@ImportResource("/WEB-INF/database.properties")
public class AccountDaoImpl extends AccountDao {
就这么简单!
相关参考:
下载次数: 2607
浏览 67228
@Autowired& &&& private AccountService accountS这个@Autowired 没有在Spring 容器中声明,为什么也能使用呢?各位指下,我找了半天没看到这个类应该是在org.zlex.spring.service包中,在service.xml中已经扫描了service包中的所有类在AccountService接口处虽未有相关声明,但在AccountServiceImpl实现类有@Service注解,故可以直接引用到其实现类
& 上一页 1
浏览: 3213508 次
来自: 北京
谢谢分享!
我一般忘记密码,也是直接停掉服务,然后拷贝一份知道密码的mys ...
垃圾代码垃圾代码
报告楼主,根本就没加密啊代码@Test
public voi ...史上最全的SpringMVC学习笔记
史上最全的SpringMVC学习笔记
一、SpringMVC基础入门,创建一个HelloWorld程序
1.首先,导入SpringMVC需要的jar包。
2.添加Web.xml配置文件中关于SpringMVC的配置
&!--configure the setting of springmvcDispatcherServlet and configure the mapping--&
&servlet-name&springmvc&/servlet-name&
&servlet-class&org.springframework.web.servlet.DispatcherServlet&/servlet-class&
&init-param&
&param-name&contextConfigLocation&/param-name&
&param-value&classpath:springmvc-servlet.xml&/param-value&
&/init-param&
&!-- &load-on-startup&1&/load-on-startup& --&
&/servlet&
&servlet-mapping&
&servlet-name&springmvc&/servlet-name&
&url-pattern&/&/url-pattern&
&/servlet-mapping&
3.在src下添加springmvc-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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"&
&!-- scan the package and the sub package --&
&context:component-scan base-package="test.SpringMVC"/&
&!-- don't handle the static resource --&
&mvc:default-servlet-handler /&
&!-- if you use annotation you must configure following setting --&
&mvc:annotation-driven /&
&!-- configure the InternalResourceViewResolver --&
&bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver"&
&!-- 前缀 --&
&property name="prefix" value="/WEB-INF/jsp/" /&
&!-- 后缀 --&
&property name="suffix" value=".jsp" /&
4.在WEB-INF文件夹下创建名为jsp的文件夹,用来存放jsp视图。创建一个hello.jsp,在body中添加“Hello World”。
5.建立包及Controller,如下所示
6.编写Controller代码
@Controller
@RequestMapping("/mvc")
public class mvcController {
@RequestMapping("/hello")
public String hello(){
return "hello";
7.启动服务器,键入 http://localhost:8080/项目名/mvc/hello
二、配置解析
1.Dispatcherservlet
DispatcherServlet是前置控制器,配置在web.xml文件中的。拦截匹配的请求,Servlet拦截匹配规则要自已定义,把拦截下来的请求,依据相应的规则分发到目标Controller来处理,是配置spring MVC的第一步。
2.InternalResourceViewResolver
视图名称解析器
3.以上出现的注解
@Controller 负责注册一个bean 到spring 上下文中
@RequestMapping 注解为控制器指定可以处理哪些 URL 请求.
三、SpringMVC常用注解
@Controller
负责注册一个bean 到spring 上下文中。
@RequestMapping
注解为控制器指定可以处理哪些 URL 请求。
@RequestBody
该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上 ,再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。
@ResponseBody
该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。
@ModelAttribute  
在方法定义上使用 @ModelAttribute 注解:Spring MVC 在调用目标处理方法前,会先逐个调用在方法级上标注了@ModelAttribute 的方法。
在方法的入参前使用 @ModelAttribute 注解:可以从隐含对象中获取隐含的模型数据中获取对象,再将请求参数–绑定到对象中,再传入入参将方法入参对象添加到模型中。
@RequestParam 
在处理方法入参处使用 @RequestParam 可以把请求参 数传递给请求方法。
@PathVariable
绑定 URL 占位符到入参。
@ExceptionHandler
注解到方法上,出现异常时会执行该方法。
@ControllerAdvice
使一个Contoller成为全局的异常处理类,类中用@ExceptionHandler方法注解的方法可以处理所有Controller发生的异常。
四、自动匹配参数
//match automatically
@RequestMapping("/person")
public String toPerson(String name,double age){
System.out.println(name+" "+age);
return "hello";
五、自动装箱
1.编写一个Person实体类
package test.SpringMVC.
public class Person {
public String getName() {
public void setName(String name) {
this.name =
public int getAge() {
public void setAge(int age) {
this.age =
2.在Controller里编写方法
//boxing automatically
@RequestMapping("/person1")
public String toPerson(Person p){
System.out.println(p.getName()+" "+p.getAge());
return "hello";
六、使用InitBinder来处理Date类型的参数
//the parameter was converted in initBinder
@RequestMapping("/date")
public String date(Date date){
System.out.println(date);
return "hello";
//At the time of initialization,convert the type "String" to type "date"
@InitBinder
public void initBinder(ServletRequestDataBinder binder){
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),
七、向前台传递参数
//pass the parameters to front-end
@RequestMapping("/show")
public String showPerson(Map&String,Object& map){
Person p =new Person();
map.put("p", p);
p.setAge(20);
p.setName("jayjay");
return "show";
前台可在Request域中取到&p&
八、使用Ajax调用
//pass the parameters to front-end using ajax
@RequestMapping("/getPerson")
public void getPerson(String name,PrintWriter pw){
pw.write("hello,"+name);
@RequestMapping("/name")
public String sayHello(){
return "name";
前台用下面的Jquery代码调用:
$(function(){
$("#btn").click(function(){
$.post("mvc/getPerson",{name:$("#name").val()},function(data){
alert(data);
九、在Controller中使用redirect方式处理请求
//redirect
@RequestMapping("/redirect")
public String redirect(){
return "redirect:hello";
十、文件上传
1.需要导入两个jar包
2.在SpringMVC配置文件中加入
&!-- upload settings --&
&bean id="multipartResolver"
class="org.springframework.monsMultipartResolver"&
&property name="maxUploadSize" value=""&&/property&
3.方法代码:
@RequestMapping(value="/upload",method=RequestMethod.POST)
public String upload(HttpServletRequest req) throws Exception{
MultipartHttpServletRequest mreq = (MultipartHttpServletRequest)
MultipartFile file = mreq.getFile("file");
String fileName = file.getOriginalFilename();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
FileOutputStream fos = new FileOutputStream(req.getSession().getServletContext().getRealPath("/")+
"upload/"+sdf.format(new Date())+fileName.substring(fileName.lastIndexOf('.')));
fos.write(file.getBytes());
fos.flush();
fos.close();
return "hello";
4.前台form表单
&form action="mvc/upload" method="post" enctype="multipart/form-data"&
&input type="file" name="file"&&br&
&input type="submit" value="submit"&
十一、使用@RequestParam注解指定参数的name
@Controller
@RequestMapping("/test")
public class mvcController1 {
@RequestMapping(value="/param")
public String testRequestParam(@RequestParam(value="id") Integer id,
@RequestParam(value="name")String name){
System.out.println(id+" "+name);
return "/hello";
十二、RESTFul风格的SringMVC
1.RestController
@Controller
@RequestMapping("/rest")
public class RestController {
@RequestMapping(value="/user/{id}",method=RequestMethod.GET)
public String get(@PathVariable("id") Integer id){
System.out.println("get"+id);
return "/hello";
@RequestMapping(value="/user/{id}",method=RequestMethod.POST)
public String post(@PathVariable("id") Integer id){
System.out.println("post"+id);
return "/hello";
@RequestMapping(value="/user/{id}",method=RequestMethod.PUT)
public String put(@PathVariable("id") Integer id){
System.out.println("put"+id);
return "/hello";
@RequestMapping(value="/user/{id}",method=RequestMethod.DELETE)
public String delete(@PathVariable("id") Integer id){
System.out.println("delete"+id);
return "/hello";
2.form表单发送put和delete请求
在web.xml中配置
&!-- configure the HiddenHttpMethodFilter,convert the post method to put or delete --&
&filter-name&HiddenHttpMethodFilter&/filter-name&
&filter-class&org.springframework.web.filter.HiddenHttpMethodFilter&/filter-class&
&filter-mapping&
&filter-name&HiddenHttpMethodFilter&/filter-name&
&url-pattern&/*&/url-pattern&
&/filter-mapping&
在前台可以用以下代码产生请求
&form action="rest/user/1" method="post"&
&input type="hidden" name="_method" value="PUT"&
&input type="submit" value="put"&
&form action="rest/user/1" method="post"&
&input type="submit" value="post"&
&form action="rest/user/1" method="get"&
&input type="submit" value="get"&
&form action="rest/user/1" method="post"&
&input type="hidden" name="_method" value="DELETE"&
&input type="submit" value="delete"&
十三、返回json格式的字符串
1.导入以下jar包
2.方法代码
@Controller
@RequestMapping("/json")
public class jsonController {
@ResponseBody
@RequestMapping("/user")
User get(){
User u = new User();
u.setId(1);
u.setName("jayjay");
u.setBirth(new Date());
十四、异常的处理
1.处理局部异常(Controller内)
@ExceptionHandler
public ModelAndView exceptionHandler(Exception ex){
ModelAndView mv = new ModelAndView("error");
mv.addObject("exception", ex);
System.out.println("in testExceptionHandler");
@RequestMapping("/error")
public String error(){
int i = 5/0;
return "hello";
2.处理全局异常(所有Controller)
@ControllerAdvice
public class testControllerAdvice {
@ExceptionHandler
public ModelAndView exceptionHandler(Exception ex){
ModelAndView mv = new ModelAndView("error");
mv.addObject("exception", ex);
System.out.println("in testControllerAdvice");
3.另一种处理全局异常的方法
在SpringMVC配置文件中配置
&!-- configure SimpleMappingExceptionResolver --&
&bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"&
&property name="exceptionMappings"&
&prop key="java.lang.ArithmeticException"&error&/prop&
&/property&
error是出错页面.
十五、设置一个自定义拦截器
1.创建一个MyInterceptor类,并实现HandlerInterceptor接口
public class MyInterceptor implements HandlerInterceptor {
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
System.out.println("afterCompletion");
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
System.out.println("postHandle");
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2) throws Exception {
System.out.println("preHandle");
2.在SpringMVC的配置文件中配置
&!-- interceptor setting --&
&mvc:interceptors&
&mvc:interceptor&
&mvc:mapping path="/mvc/**"/&
&bean class="test.SpringMVC.Interceptor.MyInterceptor"&&/bean&
&/mvc:interceptor&
&/mvc:interceptors&
3.拦截器执行顺序
十六、表单的验证(使用Hibernate-validate)及国际化
1.导入Hibernate-validate需要的jar包
(未选中不用导入)
2.编写实体类User并加上验证注解
public class User {
public int getId() {
public void setId(int id) {
public String getName() {
public void setName(String name) {
this.name =
public Date getBirth() {
public void setBirth(Date birth) {
this.birth =
public String toString() {
return "User [id=" + id + ", name=" + name + ", birth=" + birth + "]";
@DateTimeFormat(pattern="yyyy-MM-dd")
ps:@Past表示时间必须是一个过去值
3.在jsp中使用SpringMVC的form表单
&form:form action="form/add" method="post" modelAttribute="user"&
id:&form:input path="id"/&&form:errors path="id"/&&br&
name:&form:input path="name"/&&form:errors path="name"/&&br&
birth:&form:input path="birth"/&&form:errors path="birth"/&
&input type="submit" value="submit"&
&/form:form&
ps:path对应name
4.Controller中代码
@Controller
@RequestMapping("/form")
public class formController {
@RequestMapping(value="/add",method=RequestMethod.POST)
public String add(@Valid User u,BindingResult br){
if(br.getErrorCount()&0){
return "addUser";
return "showUser";
@RequestMapping(value="/add",method=RequestMethod.GET)
public String add(Map&String,Object& map){
map.put("user",new User());
return "addUser";
  1.因为jsp中使用了modelAttribute属性,所以必须在request域中有一个&user&.
  2.@Valid 表示按照在实体上标记的注解验证参数
  3.返回到原页面错误信息回回显,表单也会回显
5.错误信息自定义
在src目录下添加locale.properties
NotEmpty.user.name=name can't not be empty
Past.user.birth=birth should be a past value
DateTimeFormat.user.birth=the format of input is wrong
typeMismatch.user.birth=the format of input is wrong
typeMismatch.user.id=the format of input is wrong
在SpringMVC配置文件中配置
&!-- configure the locale resource --&
&bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"&
&property name="basename" value="locale"&&/property&
6.国际化显示
在src下添加locale_zh_CN.properties
username=账号
password=密码
locale.properties中添加
username=user name
password=password
创建一个locale.jsp
&fmt:message key="username"&&/fmt:message&
&fmt:message key="password"&&/fmt:message&
在SpringMVC中配置
&!-- make the jsp page can be visited --&
&mvc:view-controller path="/locale" view-name="locale"/&
让locale.jsp在WEB-INF下也能直接访问
最后,访问locale.jsp,切换浏览器语言,能看到账号和密码的语言也切换了。
十七、压轴大戏--整合SpringIOC和SpringMVC
1.创建一个test.SpringMVC.integrate的包用来演示整合,并创建各类。
2.User实体类
public class User {
public int getId() {
public void setId(int id) {
public String getName() {
public void setName(String name) {
this.name =
public Date getBirth() {
public void setBirth(Date birth) {
this.birth =
public String toString() {
return "User [id=" + id + ", name=" + name + ", birth=" + birth + "]";
@DateTimeFormat(pattern="yyyy-MM-dd")
3.UserService类
@Component
public class UserService {
public UserService(){
System.out.println("UserService Constructor...\n\n\n\n\n\n");
public void save(){
System.out.println("save");
4.UserController
@Controller
@RequestMapping("/integrate")
public class UserController {
@Autowired
private UserService userS
@RequestMapping("/user")
public String saveUser(@RequestBody @ModelAttribute User u){
System.out.println(u);
userService.save();
return "hello";
5.Spring配置文件
在src目录下创建SpringIOC的配置文件applicationContext.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
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
xmlns:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
&context:component-scan base-package="test.SpringMVC.integrate"&
&context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/&
&context:exclude-filter type="annotation"
expression="org.springframework.web.bind.annotation.ControllerAdvice"/&
&/context:component-scan&
在Web.xml中添加配置
&!-- configure the springIOC --&
&listener&
&listener-class&org.springframework.web.context.ContextLoaderListener&/listener-class&
&/listener&
&context-param&
&param-name&contextConfigLocation&/param-name&
&param-value&classpath:applicationContext.xml&/param-value&
&/context-param&
6.在SpringMVC中进行一些配置,防止SpringMVC和SpringIOC对同一个对象的管理重合。
&!-- scan the package and the sub package --&
&context:component-scan base-package="test.SpringMVC.integrate"&
&context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller"/&
&context:include-filter type="annotation"
expression="org.springframework.web.bind.annotation.ControllerAdvice"/&
&/context:component-scan&
十八、SpringMVC详细运行流程图
十九、SpringMVC运行原理
客户端请求提交到DispatcherServlet;
由DispatcherServlet控制器查询一个或多个HandlerMapping,找到处理请求的Controller;
DispatcherServlet将请求提交到Controller;
Controller调用业务逻辑处理后,返回ModelAndView;
DispatcherServlet查询一个或多个ViewResoler视图解析器,找到ModelAndView指定的视图;
视图负责将结果显示到客户端。
二十、SpringMVC与struts2的区别
1、springmvc基于方法开发的,struts2基于类开发的。springmvc将url和controller里的方法映射。映射成功后springmvc生成一个Handler对象,对象中只包括了一个method。方法执行结束,形参数据销毁。springmvc的controller开发类似web service开发。
2、springmvc可以进行单例开发,并且建议使用单例开发,struts2通过类的成员变量接收参数,无法使用单例,只能使用多例。
3、经过实际测试,struts2速度慢,在于使用struts标签,如果使用struts建议使用jstl。
作者:Sunnier
文章源自:
分享即可 +1积分
请登录后,发表评论
评论(Enter+Ctrl)
评论加载中...
评论加载中...
Web前端工程师
汇聚、分享优秀的IT技术资讯、文章。欢迎关注!^_^
作者的热门手记
Copyright (C)
All Rights Reserved | 京ICP备 号-2}

我要回帖

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信