Day69 Spring MVC 概念及其配置方式、Springmvc单元方法获取请求数据

springmvc的概念介绍

SpringMVC的概念介绍:
    问题:
        当前:Servlet+Spring+mybatis+jsp
        Servlet的缺点:
            必须由程序员自己进行业务分配流转代码编写。
            发现使用Servlet进行请求处理时,必须手动获取请求参数。
        Servlet使用流程
            //获取操作符
            //判断执行方法
            //获取请求数据
            //处理请求数据
            //响应处理结果
    解决:
        Spring MVC
    使用:
        Spring MVC和Spring的关系
            SpringMVC是Spring的子容器。
            注意:SpringMVC和Spring在使用时,需要各自声明配置文件。 
        SpringMVC的使用
            配置方式一:
            配置方式二:
            SpringMVC获取请求数据:            
            SpringMVC的响应:
            SpringMVC实现上传下载:
            SpringMVC的拦截器:
            SpringMVC的运行原理:

SpringMVC配置方式

配置方式一:
    1 导入jar包
        Spring和Mybatis的所有Jar包
        SpringMVC.Jar包
    2 配置SpringMVC封装的Servlet
        <servlet>
            <servlet-name>springmvc123</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>springmvc123</servlet-name>
            <url-pattern>*.do</url-pattern>
        </servlet-mapping>
        注意:
            此种配置方式Servlet一旦被加载,默认会到WEB-INF下找配置文件。并且配置文件名默认为:
            <servlet-name>-servlet.xml
    3 在web-INF下配置springmvc的配置文件 
            创建:springmvc123-servlet.xml
            配置:
                加载Schema
                配置注解扫描
                配置mvc驱动解析器
    4 在SRC下创建包(com.bjsxt.controller)
        在包下创建普通java类(控制器)
            在类中声明方法(单元方法)
                在方法上使用@RequestMapping("值"),声明方法别名,便于DispatcherServlet查找。
配置方式二:
    1 导入jar包
        Spring和Mybatis的所有Jar包
        SpringMVC.Jar包
    2 配置SpringMVC封装的Servlet
        <!-- 配置SpringMVC的Servlet -->
        <servlet>
            <servlet-name>springmvc123</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <!--配置springmvc的配置文件路径  -->
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:springmvc.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>springmvc123</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
        注意:
            /代表拦截除jsp请求以外的所有请求。
                需要对静态资源进行放行。
                <!--配置静态资源方式  -->
          <mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
        <mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
        <mvc:resources location="/image/" mapping="/image/**"></mvc:resources>
            /*会拦截所有的请求包括jsp请求
    3 在web-INF下配置springmvc的配置文件 
            创建:springmvc123-servlet.xml
            配置:
                加载Schema
                配置注解扫描
                配置mvc驱动解析器
    4 在SRC下创建包(com.bjsxt.controller)
        在包下创建普通java类(控制器)
            在类中声明方法(单元方法)
                在方法上使用@RequestMapping("值"),声明方法别名,便于DispatcherServlet查找。
------------------------------------------------------------------------------------------------------------------------------------------------------------
    基本访问流程:
        请求发送
                  ------------>DispatcherServlet
                根据请求的URI信息查找对应的单元方法
                获取请求数据
                调用单元方法执行
                接收单元方法的返回值
                根据返回值进行请求转发或者重定向
                ----------------------->controller
                        声明的单元方法
                        处理请求
                            调用业务层
                        返回处理结果





Springmvc单元方法获取请求数据

Springmvc单元方法中获取请求数据:
    创建基础运行环境
        导入jar包
            SpringIOC
            SpringAOP
            Spring TX   
            Spring 整合mybatis
            mybatis的jar
            Springmvc的jar
             jackSon的jar
            数据库jar
        配置web.xml
            配置Springmvc提供的servlet
        在src下创建配置文件
            springmvc.xml
                加载Schema
                配置注解扫描
                配置解析器驱动
                配置静态资源放行
        在src下创建控制器
        在控制器中完成请求处理
-----------------------------------------------------------------------------
获取请求数据:
    紧藕方式:
        使用原生的request对象进行获取数据。
        在单元控制方法上直接声明request形参即可。
    解耦方式:
        基本变量方式
        对象方式
        同名不同值数据
        restful
        ajax请求





Spring接收参数的例子


@Controller
public class TestCon {
    /**
     * 紧藕方式:
     *      使用原生的request对象获取
     *      在单元方法上声明HttpServletRequest形参即可
     *      在方法内使用req.getParameter("键名")  获取数据即可
     * @return
     */
    @RequestMapping("show")
    public String demo(HttpServletRequest req){ 
        String uname=req.getParameter("uname");
        int age=Integer.parseInt(req.getParameter("age"));
        System.out.println("TestCon.demo(紧藕方式:)"+uname+age);
        return "a.jsp";
    }

    /**
     * 解耦藕方式一:使用基本类型形参获取请求数据
     *      在单元方法上直接使用形参进行声明。
     *      Servlet在调用单元方法时会自动给形参赋值。
     *      问题:
     *          默认使用形参名即请求数据的键名规则进行形参赋值。如果形参和请求键名不匹配,则报错。
     *      解决:
     *          可以给形参使用别名@RequestParam(value="请求键名")
     *      @RequestParam的其他属性:
     *              defaultValue="默认值"。当请求中没有对应的数据时,给默认值。
     *              required="true" true表示该形参必须有请求数据的赋值。 false表示可有可无。
     *          
     * @return
     */
    @RequestMapping("show1")
    public String demo1(@RequestParam(value="uname",defaultValue="aaa") String uname1,int age){ 
        System.out.println("TestCon.demo(解耦藕方式一:使用基本类型形参获取请求数据)"+uname1+age);
        return "a.jsp";
    }


    /**
     * 解耦藕方式二:使用引用类型形参获取请求数据
            使用:在形参中声明引用类型对象(实体类),Servlet会按照
                 属性名和键名一致的规则,自动将请求数据注入到实体类对象中。
                 并将此对象作为实参传递给单元方法。
            注意:
                对象的属性名和请求数据的键名要一致。
     *          
     * @return
     */
    @RequestMapping("show2")
    public String demo2(User u){    
        System.out.println("TestCon.demo(解耦藕方式二:使用引用类型形参获取请求数据)"+u.getUname()+":"+u.getAge());
        return "a.jsp";
    }

    /**
     * 解耦藕方式三:获取同键不同值的请求数据
     *          在单元方法上声明ArrayList类型集合形参
     *          必须使用别名据)@RequestParam("键名") 
     * @return
     */
    @RequestMapping("show3")
    public String demo3(@RequestParam("fav")ArrayList<String> fav){ 
        System.out.println("TestCon.demo(解耦藕方式三:获取同键不同值的请求数据)"+fav.get(0));
        return "a.jsp";
    }

    /**
     * 解耦藕方式四:使用restful方式获取数据
     *      restful是请求数据的书写格式。
     *          格式为:方法别名/数据/数据/../..
     *      后台获取数据方法别名格式:
     *          @RequestMapping("方法别名/{占位键名}/{占位键名}/../..")
     *      方法的形参声明使用注解@PathVariable表示获取请求路径上的数据。
     *      注意:
     *          形参名和占位名一致。
     * @return
     */
    @RequestMapping("show4/{name}/{age}")
    public String demo4(@PathVariable String name,@PathVariable int age){   
        System.out.println("TestCon.demo(解耦藕方式四:使用restful方式获取数据)"+name+":"+age);
        return "a.jsp";
    }


    /**
     * 解耦藕方式五:Ajax请求
     *   1 前端ajax代码不变,请求地址变为单元方法别名即可
     * 
     *  前提:
     *      导入jackson相关jar包
     *      在单元方法的@RequestMapping("show5")注解下使用@ResponseBody注解,将返回值转换为Json      
     *   2 后台处理代码可以直接返回查找到的java对象,不用再转换为Json格式的字符串了。
     * @return
     */
    @RequestMapping("show5")
    @ResponseBody
    public User demo5(String uname,int age){    
        System.out.println("TestCon.demo(解耦藕方式五:Ajax请求)"+uname+":"+age);
        User  u=new User("李四",20);
        return u;
    }








}

增加的web.xml和spingmvc.xml

增加Jar包:jackSon 3个 作用:将java对象转换成js对象

web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <!--配置spring  -->
      <!--配置applicationContext,xml的路径  -->
  <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
     <!--配置监听器  -->
  <listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>
  <!--配置SpringMVC 的servlet  -->
  <servlet>
    <servlet-name>servlet123</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--配置Spring MVC 的配置文件路径  -->
    <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>servlet123</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>


springmvc.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
        <!--配置注解扫描  -->
        <context:component-scan base-package="com.bjsxt.controller"></context:component-scan>
        <!--配置mvc注解驱动  -->
        <mvc:annotation-driven></mvc:annotation-driven>
        <!--配置静态资源方式  -->
        <mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
        <mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
        <mvc:resources location="/image/" mapping="/image/**"></mvc:resources>
        </beans>

小案例

需求:
这里写图片描述

需要:数据库:
2个表:
news表:
CREATE TABLE news (
id int(10) NOT NULL,
title varchar(100) NOT NULL,
content varchar(100) NOT NULL,
cid int(10) NOT NULL,
PRIMARY KEY (id),
KEY cid (cid),
CONSTRAINT cid FOREIGN KEY (cid) REFERENCES news_clazz (cid) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
news_clazz表:
CREATE TABLE news_clazz (
cid int(10) NOT NULL AUTO_INCREMENT,
cname varchar(100) NOT NULL,
PRIMARY KEY (cid)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

导入相关jar包:
aopalliance.jar
asm-3.3.1.jar
aspectjweaver.jar
cglib-2.2.2.jar
commons-logging-1.1.1.jar
commons-logging-1.1.3.jar
jackson-annotations-2.4.0.jar
jackson-core-2.4.1.jar
jackson-databind-2.4.1.jar
javassist-3.17.1-GA.jar
log4j-1.2.17.jar
log4j-api-2.0-rc1.jar
log4j-core-2.0-rc1.jar
mybatis-3.2.7.jar
mybatis-spring-1.2.3.jar
mysql-connector-java-5.1.30.jar
slf4j-api-1.7.5.jar
slf4j-log4j12-1.7.5.jar
spring-aop-4.1.6.RELEASE.jar
spring-aspects-4.1.6.RELEASE.jar
spring-beans-4.1.6.RELEASE.jar
spring-context-4.1.6.RELEASE.jar
spring-core-4.1.6.RELEASE.jar
spring-expression-4.1.6.RELEASE.jar
spring-jdbc-4.1.6.RELEASE.jar
spring-tx-4.1.6.RELEASE.jar
spring-web-4.1.6.RELEASE.jar
spring-webmvc-4.1.6.RELEASE.jar

src:
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"
    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/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        "
        default-autowire="byName"
        >

        <!--配置注解扫描  -->
        <context:component-scan base-package="com.bjsxt.serviceImpl,com.bjsxt.pojo"></context:component-scan>
        <!--配置代理模式为cglib  -->
        <aop:aspectj-autoproxy proxy-target-class="true" ></aop:aspectj-autoproxy>
        <!--配置数据源文件扫描  -->
        <context:property-placeholder location="classpath:db.properties"/>
        <!--配置数据源  -->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        </bean>
        <!--配置工厂  -->
        <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean"></bean>
        <!--配置mapper包扫描  -->
       <bean id="mapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       <property name="basePackage" value="com.bjsxt.mapper"></property>
       <property name="sqlSessionFactoryBeanName" value="factory"></property>
       </bean>
       <!--配置事务  -->
         <!--配置事务Bean  -->
         <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"></bean>
         <!--配置事务管理办法  -->
         <tx:advice id="advice" transaction-manager="transactionManager">
         <tx:attributes>
         <tx:method name="ins*"/>
         <tx:method name="del*"/>
         <tx:method name="up*"/>
         <tx:method name="sel*" read-only="true"/>
         </tx:attributes>
         </tx:advice>
         <!--配置相关事件  -->
         <aop:config>
         <aop:pointcut expression="execution(* com.bjsxt.serviceImpl.*.*(..))" id="my"/>
         <aop:advisor advice-ref="advice" pointcut-ref="my"/>
         </aop:config>
         <!--配置切面  -->
            <!--配置切点bean  -->
            <!--配置通知bean  -->
            <!--织入形成切面  -->
         <!--配置其他bean  -->
        </beans>

db.properties:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=root

springmvc.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
        <!--配置注解扫描  -->
        <context:component-scan base-package="com.bjsxt.controller"></context:component-scan>
        <!--配置mvc注解驱动  -->
        <mvc:annotation-driven></mvc:annotation-driven>
        <!--配置静态资源方式  -->
        <mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
        <mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
        <mvc:resources location="/image/" mapping="/image/**"></mvc:resources>
        </beans>

com.bjsxt.controller:
NewsController.java:

package com.bjsxt.controller;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bjsxt.pojo.News;
import com.bjsxt.pojo.PageInfo;
import com.bjsxt.service.NewsService;
import com.bjsxt.serviceImpl.NewsServiceImpl;

@Controller
public class NewsController {
    //获取业务层对象
    @Resource
    private  NewsServiceImpl newsServiceImpl;
    @RequestMapping
    @ResponseBody
    public PageInfo show(@RequestParam(defaultValue="1")int pageNum,@RequestParam(defaultValue="2")int pageSize){
        PageInfo p= newsServiceImpl.getPageInfo(pageNum, pageSize);
        return p;
    }
}

com.bjsxt.mapper:
NewsMapper.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

  <mapper namespace="com.bjsxt.mapper.NewsMapper">
  <!--查询新闻信息  -->
  <resultMap type="com.bjsxt.pojo.News" id="n">
  <id column="id" property="id"/>
  <result column="title" property="title"/>
  <result column="content" property="content"/>
  <result column="cid" property="cid"/>
  <association property="nc" javaType="com.bjsxt.pojo.News_clazz">
  <id  column="cid" property="cid"/>
  <result column="cname" property="cname"/>
  </association>
  </resultMap>
  <select id="sel" resultMap="n">
    select n.id,n.title,n.content,nc.cname from news  n
    join news_clazz nc
    on n.cid=nc.cid   limit #{pageStart},#{pageSize}
  </select>
  <!--查询新闻条数  -->
  <select id="selCount" resultType="int">
  select count(*) from news 
  </select>
  </mapper>

NewsMapper.java:

package com.bjsxt.mapper;

import java.util.List;

import com.bjsxt.pojo.News;
import com.bjsxt.pojo.PageInfo;

public interface NewsMapper {
    //查询新闻信息
    List<News> sel(PageInfo  pageInfo);
    //查询新闻总条数
    int  selCount();
}

com.bjsxt.pojo:
News.java:

package com.bjsxt.pojo;

public class News {
  private int id;
  private String title;
  private String content;
  private int cid;
  private News_clazz nc;
public News() {
    super();
    // TODO Auto-generated constructor stub
}
public News(int id, String title, String content, int cid, News_clazz nc) {
    super();
    this.id = id;
    this.title = title;
    this.content = content;
    this.cid = cid;
    this.nc = nc;
}
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getTitle() {
    return title;
}
public void setTitle(String title) {
    this.title = title;
}
public String getContent() {
    return content;
}
public void setContent(String content) {
    this.content = content;
}
public int getCid() {
    return cid;
}
public void setCid(int cid) {
    this.cid = cid;
}
public News_clazz getNc() {
    return nc;
}
public void setNc(News_clazz nc) {
    this.nc = nc;
}
@Override
public String toString() {
    return "News [id=" + id + ", title=" + title + ", content=" + content + ", cid=" + cid + ", nc=" + nc + "]";
}
@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + cid;
    result = prime * result + ((content == null) ? 0 : content.hashCode());
    result = prime * result + id;
    result = prime * result + ((nc == null) ? 0 : nc.hashCode());
    result = prime * result + ((title == null) ? 0 : title.hashCode());
    return result;
}
@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    News other = (News) obj;
    if (cid != other.cid)
        return false;
    if (content == null) {
        if (other.content != null)
            return false;
    } else if (!content.equals(other.content))
        return false;
    if (id != other.id)
        return false;
    if (nc == null) {
        if (other.nc != null)
            return false;
    } else if (!nc.equals(other.nc))
        return false;
    if (title == null) {
        if (other.title != null)
            return false;
    } else if (!title.equals(other.title))
        return false;
    return true;
}


}

News_clazz.java:

package com.bjsxt.pojo;

public class News_clazz {
    private int cid;
    private String cname;
    public News_clazz() {
        super();
        // TODO Auto-generated constructor stub
    }
    public News_clazz(int cid, String cname) {
        super();
        this.cid = cid;
        this.cname = cname;
    }
    public int getCid() {
        return cid;
    }
    public void setCid(int cid) {
        this.cid = cid;
    }
    public String getCname() {
        return cname;
    }
    public void setCname(String cname) {
        this.cname = cname;
    }
    @Override
    public String toString() {
        return "News_clazz [cid=" + cid + ", cname=" + cname + "]";
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + cid;
        result = prime * result + ((cname == null) ? 0 : cname.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        News_clazz other = (News_clazz) obj;
        if (cid != other.cid)
            return false;
        if (cname == null) {
            if (other.cname != null)
                return false;
        } else if (!cname.equals(other.cname))
            return false;
        return true;
    }

}  

PageInfo.java:

package com.bjsxt.pojo;

import java.util.List;

import org.springframework.stereotype.Component;
@Component
public class PageInfo {
  private int pageNum;
  private int pageSize;
  private int pageStart;
  private int count;
  private int pages;
  private List<News> ln;
public PageInfo() {
    super();
    // TODO Auto-generated constructor stub
}
public PageInfo(int pageNum, int pageSize, int pageStart, int count, int pages, List<News> ln) {
    super();
    this.pageNum = pageNum;
    this.pageSize = pageSize;
    this.pageStart = pageStart;
    this.count = count;
    this.pages = pages;
    this.ln = ln;
}
public int getPageNum() {
    return pageNum;
}
public void setPageNum(int pageNum) {
    this.pageNum = pageNum;
}
public int getPageSize() {
    return pageSize;
}
public void setPageSize(int pageSize) {
    this.pageSize = pageSize;
}
public int getPageStart() {
    return pageStart;
}
public void setPageStart(int pageStart) {
    this.pageStart = pageStart;
}
public int getCount() {
    return count;
}
public void setCount(int count) {
    this.count = count;
}
public int getPages() {
    return pages;
}
public void setPages(int pages) {
    this.pages = pages;
}
public List<News> getLn() {
    return ln;
}
public void setLn(List<News> ln) {
    this.ln = ln;
}
@Override
public String toString() {
    return "PageInfo [pageNum=" + pageNum + ", pageSize=" + pageSize + ", pageStart=" + pageStart + ", count=" + count
            + ", pages=" + pages + ", ln=" + ln + "]";
}
@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + count;
    result = prime * result + ((ln == null) ? 0 : ln.hashCode());
    result = prime * result + pageNum;
    result = prime * result + pageSize;
    result = prime * result + pageStart;
    result = prime * result + pages;
    return result;
}
@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    PageInfo other = (PageInfo) obj;
    if (count != other.count)
        return false;
    if (ln == null) {
        if (other.ln != null)
            return false;
    } else if (!ln.equals(other.ln))
        return false;
    if (pageNum != other.pageNum)
        return false;
    if (pageSize != other.pageSize)
        return false;
    if (pageStart != other.pageStart)
        return false;
    if (pages != other.pages)
        return false;
    return true;
}

}

com.bjsxt.service:
NewsService.java:

package com.bjsxt.service;

import java.util.List;

import com.bjsxt.pojo.News;
import com.bjsxt.pojo.PageInfo;

public interface NewsService {
    //获取所有新闻数据并分页
    PageInfo getPageInfo(int pageNum,int pageSize);

}

com.bjsxt.serviceImpl:
NewsServiceImpl.java:

package com.bjsxt.serviceImpl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.bjsxt.mapper.NewsMapper;
import com.bjsxt.pojo.News;
import com.bjsxt.pojo.PageInfo;
import com.bjsxt.service.NewsService;
@Service
public class NewsServiceImpl implements NewsService{
    //创建mapper对象
    @Resource
    private  NewsMapper newsMapper;
    //创建pageInfo对象
    @Resource
    private PageInfo pageInfo;
    //查询所有的新闻信息并分页显示

    @Override
    public PageInfo getPageInfo(int pageNum, int pageSize) {
        //转换pageStart
        int pageStart=pageNum*pageSize-pageSize;
        //给参数赋值
        pageInfo.setPageNum(pageNum);
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageStart(pageStart);
        //获取数据
        pageInfo.setLn(newsMapper.sel(pageInfo));
        int count=newsMapper.selCount();
        int pages=(int) Math.ceil(count*1.0/pageSize);
        pageInfo.setPages(pages);
        pageInfo.setCount(count);
        return pageInfo;
    }



}

WebContent:
js:1.9js
WEB-INF:
web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

  <!--配置applicationContext,xml的路径  -->
  <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!--配置监听器  -->
  <listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>
  <!--配置SpringMVC 的servlet  -->
  <servlet>
    <servlet-name>servlet123</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--配置Spring MVC 的配置文件路径  -->
    <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>servlet123</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

news.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>show my news</title>
<style type="text/css">
a:hover{
    color:red
}
</style>
<script type="text/javascript" src="js/j.js"></script>
<script type="text/javascript">
 $(function(){
     //声明总页数
       var pages;
     //声明当前页码数
      var pn;
     getData(1,2);
     //上一页
      $("#up").click(function(){
          if(pn>1){
              getData(pn-1,2); 
          }else{
              alert("已经是第一页")
          }

      })
     //下一页
      $("#down").click(function(){
         if(pn<pages){
             getData(pn+1,2);
         }else{
             alert("已经是最后一页")
         }
      })
     //封装ajax分页
     function getData(pageNum,pageSize){
         $.get("show",{pageNum:pageNum,pageSize:pageSize},function(data){
              //获取table
              var ta= $("#ta");
              pn=data.pageNum;
              pages=data.pages;
              //清空表头
              ta.empty();
              ta.append("<tr>"+
                        "<td>新闻标题</td>"+
                        "<td>新闻内容</td>"+
                        "<td>新闻类</td>"+
                    "</tr>");
              //填充内容
              for(var i=0;i<data.ln.length;i++){
                  ta.append("<tr>"+
                "<td>"+data.ln[i].title+"</td>"+
                "<td>"+data.ln[i].content+"</td>"+
                "<td>"+data.ln[i].nc.cname+"</td>"+
            "</tr>");
              }
              //遍历生成页面数
                //获取span
                var span= $("#sp");
                 span.empty();
                 for(var i=1;i<=data.pages;i++){
                     if(pn==i){
                         span.append("<a href='javascript:void(0)' name='page' style='color:red' >"+i+"</a>&nbsp;&nbsp;")
                     }else{
                         span.append("<a href='javascript:void(0)' name='page'  >"+i+"</a>&nbsp;&nbsp;")
                     }
                 }
                 //点击页面数请求页码数据
                 $("a[name=page]").click(function(){
                     getData($(this).html(),2);
                 })
         })
     }   
 })
</script>
</head>
<body>
  <table cellpadding="0" cellspacing="0" border="solid 1px" id="ta">
  </table>
  <a href="javascript:void(0)" id="up">上一页</a>  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  <span id="sp"></span>
   <a href="javascript:void(0)" id="down">下一页</a>
</body>
</html>

源码:
链接:https://pan.baidu.com/s/1gsbr7kgXKFFgt4KeY_vYBg 密码:azvf
问题的解决:

问题:Pojo类  什么情况下使用注解?
需要创建对象的时候,并且不使用new方式创建,例如使用:
@Resource
private PageInfo pageInfo;
前提是在创建Pojo类时:
@Component
public class PageInfo{}

错误:
Error creating bean with name 'newsController': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'newsServiceImpl' must be of type [com.bjsxt.serviceImpl.NewsServiceImpl], but was actually of type [com.sun.proxy.$Proxy14]


解决:

private  NewsServiceImpl newsServiceImpl;-->private  NewsService newsServiceImpl;

或者:
applicationContext:                         
<!--配置代理模式为cglib  -->
        <aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>


注意不是:expose-proxy="true"

错误:
Error creating bean with name 'newsServiceImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.bjsxt.pojo.PageInfo] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.annotation.Resource(shareable=true, mappedName=, description=, name=, type=class java.lang.Object, authenticationType=CONTAINER, lookup=)}


解决:
 <!--配置注解扫描  -->
        <context:component-scan base-package="com.bjsxt.serviceImpl,com.bjsxt.pojo"></context:component-scan>

小结

springmvc的概念介绍
SpringMVC配置方式
Springmvc单元方法获取请求数据
Spring接收参数的例子
增加的web.xml和spingmvc.xml
注意
小案例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值