Spring Web MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将web层进行职责解耦,基于请求驱动指的就是使用请求-响应模型,框架的目的就是帮助我们简化开发,Spring Web MVC也是要简化我们日常Web开发的。下面我们开始来部署一个简单的能够运行的springmvc框架
一 、从配置文件说起
在web项目中配置一个spring的servlet,并且配置spring的配置文件路径:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:main/resource/spring-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:main/resource/applicationContext.xml</param-value> </context-param>
配置文件中需要配置这一句是防止产生不同的两个spring 容器,导致后面不可发现的bug
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
springmvc的所有请求都是交给DispatcherServlet这个servlet来处理,spring 配置文件为applicationContext.xml,那我们就开始来说applicationContext.xml,这是spring的基本配置文件,先贴出配置文件代码
<?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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"> </property> <property name="url" value="jdbc:mysql://localhost:3306/studentmanager"> </property> <property name="username" value="root"></property> <property name="password" value="root"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> </props> </property> <!-- <property name="mappingLocations"> <list> <value>classpath:main/resource/hbmfile/*.hbm.xml</value> </list> </property> --> <property name="mappingResources"> <list> <value>main/resource/hbmfile/LoginUserInfo.hbm.xml</value> </list> </property> </bean> <bean id="loginUserInfoDao" class="main.java.dao.LoginUserInfoDao"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <bean id="loginUserInfoService" class="main.java.service.LoginUserInfoService"> <property name="loginUserInfoDao"> <ref bean="loginUserInfoDao" /> </property> </bean> </beans>
在配置文件中,我们定义了一个Datasource和sessionfactory这两个bean,他们是为spring继承的hibernate服务的两个bean,后面又定义了两个普通的bean
到这里,我们就配置好了web配置文件和spring的配置文件,springMVC有单独的配置文件,他的默认名称是springmvc的servlet名+“-”+servlet.xml,在这里这个配置文件就应该是spring-servlet.xml,当然在这个 servlet的属性中还可以配置springmvc配置文件的路径和文件名,先贴出spring-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:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <context:component-scan base-package="springmvc"/> --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" 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-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd "> <!-- <mvc:resources location="/html/" mapping="/html/**"/> <mvc:resources location="/js/" mapping="/js/**"/> --> <mvc:resources location="/" mapping="/**/*.html"/> <mvc:resources location="/" mapping="/**/*.js"/> <context:component-scan base-package="main.java,main.java.dao,main.java.index"> </context:component-scan> <mvc:annotation-driven/> </beans>
这段代码中,resource表示静态文件请求路径,因为springmvc会把所有请求都当做请求提交给服务器,这样配置就可以让springmvc不把这些文件请求当做请求发送到服务器,mvc:annotation-driven/>是开启注解扫描,这样配置文件就结束
二、控制器
先看一个简单的控制器代码
package main.java.index;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import main.java.bean.LoginUserInfo;
import main.java.service.LoginUserInfoService;
import main.java.util.BeanUtil;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value="/index")
public class LoginController {
private LoginUserInfoService loginUserInfoService ;
@RequestMapping(value="/login")
@ResponseBody
public JSONObject login(@RequestBody JSONObject json , HttpServletRequest req,HttpServletResponse res){
JSONObject result = new JSONObject() ;
result.put("success", "false") ;
if(checkLogin(json.getString("name") , json.getString("password"))){
Cookie cookie = new Cookie("loginName" , json.getString("name"));
cookie.setMaxAge(-1);
Cookie cookie1 = new Cookie("loginPassword" , json.getString("password"));
cookie.setMaxAge(-1);
res.addCookie(cookie1);
res.addCookie(cookie);
result.put("success", "true") ;
}
return result ;
}
public boolean checkLogin(String name , String passWord){
LoginUserInfo userInfo = getLoginUserInfoService().findLoginUserInfoByName(name);
if(userInfo != null && userInfo.getPassWord().equals(passWord)){
return true ;
}
return false ;
}
private LoginUserInfoService getLoginUserInfoService(){
if(loginUserInfoService == null ){
loginUserInfoService = (LoginUserInfoService)BeanUtil.getBeanByName("loginUserInfoService") ;
}
return loginUserInfoService ;
}
}
在这里面@Controller注解标明这是一个控制器,@RequestMapping(value="/index")表示请求url头,如果请求url是以/index开头则进这个控制器,方法前面的@RequestMapping(value="/login")表示如果请求url为/index/login则进这个方法,主:控制器中的bean不能通过注解注解进来,必须通过获取bean。在这个方法的参数中,@RequestBody会把请求中的内容封装成json,这是通过jar包jacson来实现的,所以必须引入这些jar包
三:请求与ajax
在前端可以通过表单来提交请求,吧表单内容封装成对象来传递给后台控制器,这需要在表单中添加 modelAttribute="User"属性实现,这样在控制器中的参数可以直接通过User来获取这个对象,
除此以外还可以通过ajax来提交请求,这里介绍一个通用的ajax请求提交方法
$(function(){ jQuery.extend({ smAjax : function(url, params, callback, async) { $.ajax({ type : "POST", url : url, /*headers: { "Prefer_Lang":Cookies.get('typeValGlob')?Cookies.get('typeValGlob'):"" },*/ async : async == undefined ? true:async, data : JSON.stringify(params), dataType : "json", contentType : 'application/json', success : function(data){ callback(data); } }); } }); });
在这里url表示请求的url,params是请求内容,callback是回调方法,参数很多,这里列举一些,
1.url:
要求为String类型的参数,(默认为当前页地址)发送请求的地址。
2.type:
要求为String类型的参数,请求方式(post或get)默认为get。注意其他http请求方法,例如put和delete也可以使用,但仅部分浏览器支持。
3.timeout:
要求为Number类型的参数,设置请求超时时间(毫秒)。此设置将覆盖$.ajaxSetup()方法的全局设置。
4.async:
要求为Boolean类型的参数,默认设置为true,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为false。注意,同步请求将锁住浏览器,用户其他操作必须等待请求完成才可以执行。
5.cache:
要求为Boolean类型的参数,默认为true(当dataType为script时,默认为false),设置为false将不会从浏览器缓存中加载请求信息。
6.data:
要求为Object或String类型的参数,发送到服务器的数据。如果已经不是字符串,将自动转换为字符串格式。get请求中将附加在url后。防止这种自动转换,可以查看 processData选项。对象必须为key/value格式,例如{foo1:"bar1",foo2:"bar2"}转换为&foo1=bar1&foo2=bar2。如果是数组,JQuery将自动为不同值对应同一个名称。例如{foo:["bar1","bar2"]}转换为&foo=bar1&foo=bar2。
7.dataType:
要求为String类型的参数,预期服务器返回的数据类型。如果不指定,JQuery将自动根据http包mime信息返回responseXML或responseText,并作为回调函数参数传递。可用的类型如下:
xml:返回XML文档,可用JQuery处理。
html:返回纯文本HTML信息;包含的script标签会在插入DOM时执行。
script:返回纯文本JavaScript代码。不会自动缓存结果。除非设置了cache参数。注意在远程请求时(不在同一个域下),所有post请求都将转为get请求。
json:返回JSON数据。
jsonp:JSONP格式。使用SONP形式调用函数时,例如myurl?callback=?,JQuery将自动替换后一个“?”为正确的函数名,以执行回调函数。
text:返回纯文本字符串。
8.beforeSend:
要求为Function类型的参数,发送请求前可以修改XMLHttpRequest对象的函数,例如添加自定义HTTP头。在beforeSend中如果返回false可以取消本次ajax请求。XMLHttpRequest对象是惟一的参数。
function(XMLHttpRequest){
this; //调用本次ajax请求时传递的options参数
}
9.complete:
要求为Function类型的参数,请求完成后调用的回调函数(请求成功或失败时均调用)。参数:XMLHttpRequest对象和一个描述成功请求类型的字符串。
function(XMLHttpRequest, textStatus){
this; //调用本次ajax请求时传递的options参数
}
10.success:要求为Function类型的参数,请求成功后调用的回调函数,有两个参数。
(1)由服务器返回,并根据dataType参数进行处理后的数据。
(2)描述状态的字符串。
function(data, textStatus){
//data可能是xmlDoc、jsonObj、html、text等等
this; //调用本次ajax请求时传递的options参数
}
11.error:
要求为Function类型的参数,请求失败时被调用的函数。该函数有3个参数,即XMLHttpRequest对象、错误信息、捕获的错误对象(可选)。ajax事件函数如下:
function(XMLHttpRequest, textStatus, errorThrown){
//通常情况下textStatus和errorThrown只有其中一个包含信息
this; //调用本次ajax请求时传递的options参数
}
12.contentType:
要求为String类型的参数,当发送信息至服务器时,内容编码类型默认为"application/x-www-form-urlencoded"。该默认值适合大多数应用场合。
13.dataFilter:
要求为Function类型的参数,给Ajax返回的原始数据进行预处理的函数。提供data和type两个参数。data是Ajax返回的原始数据,type是调用jQuery.ajax时提供的dataType参数。函数返回的值将由jQuery进一步处理。
function(data, type){
//返回处理后的数据
return data;
}
14.dataFilter:
要求为Function类型的参数,给Ajax返回的原始数据进行预处理的函数。提供data和type两个参数。data是Ajax返回的原始数据,type是调用jQuery.ajax时提供的dataType参数。函数返回的值将由jQuery进一步处理。
function(data, type){
//返回处理后的数据
return data;
}
15.global:
要求为Boolean类型的参数,默认为true。表示是否触发全局ajax事件。设置为false将不会触发全局ajax事件,ajaxStart或ajaxStop可用于控制各种ajax事件。
16.ifModified:
要求为Boolean类型的参数,默认为false。仅在服务器数据改变时获取新数据。服务器数据改变判断的依据是Last-Modified头信息。默认值是false,即忽略头信息。
17.jsonp:
要求为String类型的参数,在一个jsonp请求中重写回调函数的名字。该值用来替代在"callback=?"这种GET或POST请求中URL参数里的"callback"部分,例如{jsonp:'onJsonPLoad'}会导致将"onJsonPLoad=?"传给服务器。
18.username:
要求为String类型的参数,用于响应HTTP访问认证请求的用户名。
19.password:
要求为String类型的参数,用于响应HTTP访问认证请求的密码。
20.processData:
要求为Boolean类型的参数,默认为true。默认情况下,发送的数据将被转换为对象(从技术角度来讲并非字符串)以配合默认内容类型"application/x-www-form-urlencoded"。如果要发送DOM树信息或者其他不希望转换的信息,请设置为false。
21.scriptCharset:
要求为String类型的参数,只有当请求时dataType为"jsonp"或者"script",并且type是GET时才会用于强制修改字符集(charset)。通常在本地和远程的内容编码不同时使用。
四:获取spring管理的bean
获取spring管理的bean的方法有很多,spring管理的bean就是在spring配置文件中通过bean标签声明的吧ean,这里介绍一种方式
public static Object getBeanByName(String name ){
ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:main/resource/applicationContext.xml");
return ac.getBean(name);
}
参数是spring配置文件路径
Spring MVN 在controller中,可以接受参数为路径,比如我有一个controller是这样的
@Controller
@RequestMapping(value = "/test/hello")
public class testController{
}
@Controller
@RequestMapping(value = "/test/hello")
public class TestController{
@RequestMapping(method = RequestMethod.POST, value = "/{devIds}")
@ResponseBody
public void doTest(HttpServletRequest request , HttpServletResponse response , @PathVariable String devIds){
doSomething
}
}
这样就可以在路径中加入可变的参数作为路径
配置webapp路径
http://www.cnblogs.com/AloneSword/p/3998557.html