SSM整合(spring、springMVC、mybatis)

需要用的包:

包括:spring的包、springMVC的包、mybatis的包、数据库驱动包、json相关的包

配置如下,首先是mybatis的配置

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

<configuration>
    <typeAliases>
        <package name="com.maya.model" />
    </typeAliases>
    
</configuration>

然后是springMVC的配置

<?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" xmlns:p="http://www.springframework.org/schema/p"
    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.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">


    <context:component-scan base-package="com.maya.controller"></context:component-scan>
    <!-- 开启注解 -->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!-- springmvc 解决乱码问题的方式 -->
        <mvc:annotation-driven>
            <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
            </mvc:message-converters>
    </mvc:annotation-driven>
    

    <!-- 加上前缀和后缀 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:prefix="/" p:suffix=".jsp">
    </bean>

</beans>

然后是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: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/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">


    <!-- spring配置 -->

    <!-- 加载外部属性文件 -->
    <context:property-placeholder location="classpath:db.properties" />

    <!-- 配置扫描器 -->
    <context:component-scan base-package="com.maya" />

    <!-- 数据源 -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!-- SqlSession -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <property name="mapperLocations" value="classpath:com/maya/mapper/*.xml" />
    </bean>
    
    <!-- 数据库操作接口 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.maya.dao"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>
    
    <!-- spring事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 配置事务属性 -->
        <tx:advice id="txadvice" transaction-manager="transactionManager">
            <tx:attributes>
                <tx:method name="*" read-only="false"/>
            </tx:attributes>
        </tx:advice>
        
    <!-- 配置切面 -->
    <aop:config>
        <aop:pointcut expression="execution(* com.maya.dao.*.*(..))" id="aoppointcut"/>
        <aop:advisor advice-ref="txadvice" pointcut-ref="aoppointcut"/>
    </aop:config>

</beans>

在WEB-INF文件夹下建立web.xml文件,配置如下

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


    <!-- 过滤中文乱码 -->
    <filter>
        <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>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!--spring配置  -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-all.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
<!--spring mvc配置 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--参数,加载时,需要装载的内容 param-name 中的名字是固定的不能改变--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- 让其启动时就加载 --> <load-on-startup>1</load-on-startup> </servlet> <!--映射,名字要与上面对应起来 url 中的*.do 表示只过滤这种形式的请求 比如 add.do--> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>

建立包

(可以不建立这么多)

建立实体类,将其对应关系写好

在dao层写好接口(这里就只贴了一个了)

package com.maya.dao;

import java.util.List;

import com.maya.model.Articles;

public interface ArticlesDao {

    /**
     * 
     *分页查询,第三个参数如果传一个null,那么默认查询所有,如果有任意值,那么值显示备品数量不为空的
     * @param param1
     * @param param2
     * @return
     */
    public List<Articles> select(int param1, int param2,String param3);
    /**
     * 查询所有数量不为0的
     * 
     */
    public List<Articles> select1();
    
    /**
     * 模糊查询
     */
    public List<Articles> selectbyname(String str,int param1, int param2);
    
    
    /**
     * 添加
     * @param articles
     * @return
     */
    public Integer insert(Articles articles);
    
    
    /**
     * 修改
     */
    public Integer update(Articles articles);
    
    
    /**
     * 根据id查询
     */
    public Articles    selectById(Integer id);
    
    /**
     * 查询列表中的总数
     * 
     *
     */
    public Integer count();    
    
}

在mapping的包中写好对应的配置文件

<?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.maya.dao.ArticlesDao">
    <select id="select" resultType="Articles">
        select * from(select a.*,rownum rn from (select * from t_articles where 1=1
        <if test="param3!=null">
            and snumber>0
        </if>
        ) a
        where rownum  <![CDATA[  < ]]>
        #{param2}) where rn>#{param1}
    </select>
    
    <select id="select1" resultType="Articles">
        select * from t_articles 
    </select>

    <select id="selectbyname" resultType="Articles">
        select * from(select a.*,rownum rn from (select * from t_articles
        where sname like #{param1}) a where rownum  <![CDATA[  < ]]>
        #{param3}) where rn>#{param2}
    </select>

    <select id="selectById" resultType="Articles">
        select * from t_articles
        where id=#{param1}
    </select>

    <select id="count" resultType="int">
        select count(*) from T_ARTICLES t
    </select>

    <insert id="insert" parameterType="Articles">
        insert into t_articles
        values(sq_mybatis.nextval,#{sname},#{money},#{snumber})
    </insert>

    <update id="update" parameterType="Articles">
        update t_articles set
        sname=#{sname},money=#{money},snumber=#{snumber}
        where id=#{id}
    </update>


</mapper>

 

 service包中建立一个类:在这个包中写逻辑

package com.maya.service;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.maya.dao.ArticlesDao;
import com.maya.model.Articles;
import com.maya.model.PageBean;

/**
 * 这个类涉及到备品表的增,改查,同样没涉及到删除
 * 
 * @author Administrator
 *
 */
@Service
public class ArticlesService {

    @Autowired
    private ArticlesDao ad;

    /**
     * 查询 如果str是null,那么就分页查询所有,如果str不是空的,那么就查询所有备品剩余数量不是0的
     * 
     * @param str
     * @param page
     * @return
     */
    public List<Articles> select(String str, PageBean page) {
        if (str == null) {
            return ad.select((page.getPage() - 1) * page.getRows(), page.getPage() * page.getRows() + 1, null);
        } else {
            return ad.select((page.getPage() - 1) * page.getRows(), page.getPage() * page.getRows() + 1, str);
        }
    }
    
    /**
     * 根据备品的名称查询
     * @param str
     * @param page
     * @return
     */
    public List<Articles> byname(String str, PageBean page) {
        String str2="%"+str+"%";
        return ad.selectbyname(str2, (page.getPage() - 1) * page.getRows(), page.getPage() * page.getRows() + 1);

    }
    /**
     * 通过id查询
     */
    public Articles byId(Integer id){
        return ad.selectById(id);
    }
    /**
     * 添加   这个没什么好说的
     * @param articles
     */
    public void insert(Articles articles){
        ad.insert(articles);
    }
    
    /**
     * 修改
     * @param articles
     */
    public void update(Articles articles){
        ad.update(articles);
    }
    
    /**
     * 查询总条数
     */
    
    public Integer count(){
        return ad.count();
    }
    
    
    /**
     * 查询所有不为0的
     * @return
     */
    public List<Articles> selectall(){
        return ad.select1();
    }

}

在controller包中建立:

package com.maya.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
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.maya.model.Articles;
import com.maya.model.PageBean;
import com.maya.service.*;
import com.maya.util.ResponseUtil;
import com.sun.xml.internal.ws.client.ResponseContext;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
public class ArticlesController {
    @Autowired
    private ArticlesService as;

    //查询、模糊查询
    @ResponseBody
    @RequestMapping(value = "selectall")
    public String select(@RequestParam("page") String page, @RequestParam("rows") String rows,
            @RequestParam(value = "s_dname", required = false, defaultValue = "") String s_dname) {
        PageBean pagebean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
        List<Articles> list = null;
        Integer ins = 0;
        if (s_dname.equals("")) {
            list = as.select(null, pagebean);
            ins = as.count();
        } else {
            list = as.byname(s_dname, pagebean);
            ins = list.size();
        }

        JSONArray jsonarray = new JSONArray();
        for (Articles a : list) {
            JSONObject json = new JSONObject();
            json.put("id", a.getId());
            json.put("sname", a.getSname());
            json.put("money", a.getMoney());
            if(a.getSnumber()==0){
                json.put("snumber", "暂无库存");
            }
            else{
                json.put("snumber", a.getSnumber());
            }
            jsonarray.add(json);
        }
        JSONObject json1 = new JSONObject();
        json1.put("total", ins);
        json1.put("rows", jsonarray.toString());
        return json1.toString();
    }

    //添加或者修改
    @ResponseBody
    @RequestMapping("sevaOrUpdate")
    public String sevaOrUpdate(@RequestParam("id") String id, @RequestParam("sname") String sname,
            @RequestParam("money") String money, @RequestParam("snumber") String snumber) {
        Articles ac = new Articles();
        ac.setMoney(Double.parseDouble(money));
        ac.setSname(sname);
        ac.setSnumber(Integer.parseInt(snumber));

        if (id.equals("")) {
            as.insert(ac);
        } else {
            ac.setId(Integer.parseInt(id));
            as.update(ac);
        }
        JSONObject json = new JSONObject();
        json.put("success", true);
        return json.toString();
    }
}

 

 建立页面,完成

 

posted @ 2017-05-02 15:41  赵天成123  阅读(579)  评论(0编辑  收藏  举报