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

web.xml文件配置css

spring文件配置web

spring mvc Ajax两种实现方式spring

spring mvc 传值方式数据库

spring注解标签express

spring 自动注入机制json

ibatis 学习spring-mvc

jstl 的简单使用服务器

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

         其实就是spring mvc 做为一个拦截器,首先它须要拦截全部的请求,不管是动态的仍是静态的资源,所以全部的第一步都须要在web.xml文件中去配置一个拦截器,不一样的框架由不一样的拦截器,固然通常都会定义一些规则,能够选择性的拦截。(这些框架都是基于Servlet的,struts2 也是如此)app

         那么如何设置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()中设为:” redirectname”

 

接下来要将到的是@Controller

咱们来看一个类:

@Controller

@RequestMapping( "user")

public class UserController {

     //

}

那么这个类就会处理URL中这样格式的请求:

/svc/user/*      

 (其中 svc 为咱们在web.xml中定义的拦截规则 user 类上的@RequestMapping ,url中剩余部分则须要则类中的方法上进行匹配 )

 

  接下来我讲一下 spring mvcAjax的实现方式(我的的理解)

  1. 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,对于咱们使用框架来讲,应该充分利用它的功能,所以不推荐使用;

 

  1. 使用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中传值问题了:

  1. 经过@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");
    }

  2. @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()
}

 

  1. 直接用HttpServletRequest获取

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

  2. 用注解@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的部分,见下一篇博客

相关文章
相关标签/搜索