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

Spring mvc ,spring ,ibatis 学习记录(1)

2016-09-20 18:50 369 查看
摘要: Spring mvc ,spring ,ibatis 三大框架的集成与具体配置介绍

web.xml文件配置

spring文件配置

spring mvc Ajax两种实现方式

spring mvc 传值方式

spring注解标签

spring 自动注入机制

ibatis 学习

jstl 的简单使用

Spring mvc 主要作用于UI层,接受URL请求,返回页面。

其实就是spring mvc 作为一个拦截器,首先它需要拦截所有的请求,不论是动态的还是静态的资源,因此所有的第一步都需要在web.xml文件中去配置一个拦截器,不同的框架由不同的拦截器,当然一般都会定义一些规则,可以选择性的拦截。(这些框架都是基于Servlet的,struts2 也是如此)

那么如何设置spring mvc的拦截器呢:

<servlet>
<servlet-name>svcEngine</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/rest-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>svcEngine</servlet-name>
<url-pattern>/svc/*</url-pattern>
</servlet-mapping>
如何理解这段内容呢?

从<url-pattern> 开始,如果请求的URL中存在 /svc/ 这样的形式,那么这个URL请求就交给 类:

org.springframework.web.servlet.DispatcherServlet 去处理(至于它是怎么做的,如果不是为了自己写框架,不需要关心)

说一下contextConfigLocation 的作用吧:

在spring中,如果不指定 contextConfigLocation ,那么默认会加载 WEB-INF/applicationContext.xml这个文件,如果指定了这个,就会加载<param-value>中的文件,多个文件以逗号隔开,默认为根目录,即你的项目那一级目录.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/conf/*.xml</param-value>
</context-param>
自定义如要在容器启动时加载的文件

注意,如果设置contextConfigLocation,需要配置:

<listen>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listen>

<load-on-startup> 多个文件表示的是Servlet的加载顺序,我们在web.xml中定义了一个<servlet>,但是什么时候去初始化这个Servlet呢,就可以再 <load-on-startup>中定义,只能是一个数字,不小于0表示在容器启动时就去初始化 加载这个servlet,小于0则只会在使用时加载。

接下来说的是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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
">
<!-- annotation -->
<context:component-scan base-package="*" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository" />
</context:component-scan>
<!—spring mvc对静态资源的过滤,即如果是定义的URL视为静态资源,不经过拦截器-->
<mvc:resources location="/scripts/" mapping="/scripts/css/**"/>
<!—与spring mvc为@Controller的分发请求有关系 -->
<mvc:annotation-driven >
<mvc:message-converters>
<ref bean="jsonConverter"/>
<!—以json的形式发送数据 -->
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes" value="*/*" />
</bean>
<!-- view Resolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>

当客户端发送一个URL请求,如果和spring mvc 设置的URL匹配规则相符合,则接下来的处理交给spring mvc处理。

<context:component-scan base-package="*" use-default-filters="false">
定义扫描规则,base-package 则是要扫描的包,如果在这些包下面的类打上了 @Component,@Controller,@Service,@Repository 这些注解,那么就在这些类里面查找对应的处理方法

<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
表示 @Controller 注解的 接受处理
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
表示@Service 注解的类 不接受处理。 如果设置 exclude 或者 include,则需要设置 use-default-filters
(Indicates whether automatic detection of classes annotated with @Component, @Repository, @Service, or @Controller should be enabled. Default is "true". 这是官方的解释)。 意思就是:将use-default-filters 设置为false,那么就不会自动检测打上这些标注的类,而是将规则交给 <context:exclude-filter> 和<context:include-filter>处理。

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
定义返回的规则,举例来说:
@RequestMapping(value="login",
method={RequestMethod.POST,RequestMethod.GET})
public ModelAndView login(@ModelAttribute Login pojo)
{
System.out.println(pojo.getUid()+":"+pojo.getPwd());
ModelAndView mv=new ModelAndView();
if(_userManager.login(pojo))
{
mv.addObject("info",pojo.getUid());
}else{
mv.addObject("info","error");
}
mv.setViewName("user/index");
return mv;
}
}
ModeAndView 顾名思义 就是 数据和视图,将要返回的页面和数据绑定到一块
返回一个 ModeAndView,设置一个viewName,如: user/index ,那么根据bean里面定义的规则,返回的页面就是: views/user/index.jsp ,自动为每一个返回视图添加一个前缀 views 和一个文件名.jsp.
有时候我们需要在一个ModeAndView 中跳转到另外一个ModeAndView中,那么可以再setViewName()中设为:” redirect:name”

接下来要将到的是@Controller
我们来看一个类:
@Controller
@RequestMapping( "user")
public class UserController {
//
}
那么这个类就会处理URL中这样格式的请求:
/svc/user/*
(其中 svc 为我们在web.xml中定义的拦截规则 ,user为 类上的@RequestMapping ,url中剩余部分则需要则类中的方法上进行匹配 )

接下来我讲一下 spring mvc中Ajax的实现方式(个人的理解)

Servlet方式,

@RequestMapping(value="validate_userName",method=RequestMethod.GET)
public ModelAndView validateUserName(@RequestParam("userName") String userName ,HttpServletRequest request,HttpServletResponse response)
{
PrintWriter writer=null;
try {
writer = response.getWriter();
} catch (IOException e) {
e.printStackTrace();
}
if(userBizImp.isExist(userName))
{ writer.write("exist");
}else{
writer.write("ok");
}
writer.flush();
writer.close();
return null;
}
直接调用 PrintWriter 去打印,然会返回null,不要返回一个ModeAndView.
这种方式感觉就像避开了spring mvc,对于我们使用框架来说,应该充分利用它的功能,因此不推荐使用;

使用spring mvc 的@ResponseBody

@RequestMapping("getall")
public @ResponseBody List<User> getAll( ) {
List<User> lst = _userManager.getall();
return lst;
}
这种方式直接就可以讲内容以json的形式返回 ,你可以返回 String,对象,列表等。当然你可能需要配置一下它,使它对于返回的格式做一些处理。可以参考这个:
<mvc:annotation-driven >
<mvc:message-converters>
<ref bean="jsonConverter"/>
<!—以json的形式发送数据 -->
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes" value="*/*" />
</bean>

这里说的两种都是后台的实现方式,前台就是直接 Ajax 请求就行。(Ajax的含义就是异步请求,你在一个页面请求服务器资源,正常情况是一个请求到服务器,服务器通过应用程序处理你的请求,返回相应的页面,因此一个请求就代表一个页面,但是有时我们不希望页面刷新,只希望返回我们需要的数据,这时就需要异步的方式了)

接下来说的是就是spring mvc中传值问题了:

通过@PathVariabl注解获取路径中传递参数@RequestMapping(value = "/{id}/{str}")
public ModelAndView index(@PathVariable String id, @PathVariable String str) {
System.out.println(id);
System.out.println(str);
return new ModelAndView("/index");
}

用@ModelAttribute注解获取POST请求的FORM表单数据

@RequestMapping(value=”index”,method = RequestMethod.POST)
public ModeAndView index(@ModelAttribute("user") User user) {
return new ModeAndView("welcome");
}

public class User{
private String name;
private int pwd;
setter()
getter()
}

直接用HttpServletRequest获取@RequestMapping(method = RequestMethod.GET)
public ModeAndView get(HttpServletRequest request, HttpServletResponse response) {
System.out.println(request.getParameter("a"));
return new ModeAndView(“welcome”);
}

用注解@RequestParam绑定请求参数a到变量a

当请求参数a不存在时会有异常发生,可以通过设置属性required=false解决,
例如: @RequestParam(value="a", required=false)
@RequestMapping(value = "/index", method = RequestMethod.GET)
public ModeAndView index(@RequestParam("a") String a) {
System.out.println(a);
return new ModeAndView(“inded”);
}

Spring 注解标签
@Component ,@Repository , @Service , @Controller
@Component 相当于是其它三个的父类, 其它三个职责更加明确了。
@Repository 标注的是数据库持久层
@Service 标注的是业务逻辑层
@Controller 标注的则是控制层
我们为一个类添加了这些注解标签之后,组件的自动扫描机制就会在类路径底下寻找到它,实例一个对象添加到spring容器中,默认是以单例的形式,当然我们可以通过 @Scope(”prototype”)来改变。getBean的默认名称是 类名(首字母小写),可以自定义 ,如:@Service(”name”)
Spring存在一种自动注入的机制,你不需要显示的通过context.getBean(“name”) 去获取对象实例,而是可以通过一些标签即可做到。下面以一个例子来讲解:

@Service(“userService”)
public class UserService{
public void show(){
System.out.println(“hello “);

}

@Controller
Public class UserController{
@Resource(name=”userService”)
UserService _userService;
@RequestMapping(“login”)
public ModeAndView login(){
_userService.show(); //直接就可以使用 _userService
}
}
@Autowired 按byType 方式自动注入,默认要求依赖的而对象必须存在,当然也可以指定注入bean的名称,通过 @Qualifier 来指定
@Resource 默认按byName自动注入 。

因为字数限制问题,关于iBATIS的部分,见下一篇博客
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring mvc ibatis