码迷,mamicode.com
首页 > 编程语言 > 详细

java web开发入门八(ssm整合)基于intellig idea

时间:2019-11-23 12:53:11      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:ide   limit   支持   连接失败   pass   attribute   注解   def   sel   

ssm整合

一、导入相关包

技术图片

 

二、开发流程

1.写entity

技术图片
package com.eggtwo.euq.entity;


import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;

public class Member {
    private int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    private String name;
    private int age;
    private Date birthday;
    private boolean man;
    private BigDecimal score;

    public BigDecimal getScore() {
        return score;
    }

    public void setScore(BigDecimal score) {
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public boolean isMan() {
        return man;
    }

    public void setMan(boolean man) {
        this.man = man;
    }

    @Override
    public String toString() {
        return "Member{" +
                "id=" + id +
                ", name=‘" + name + ‘\‘‘ +
                ", age=" + age +
                ", birthday=" + birthday +
                ", man=" + man +
                ", score=" + score +
                ‘}‘;
    }
}
Member

2.配mapper.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.eggtwo.euq.dao.MemberDao">
    <!--
    *******当实体属性和表字段名称一致的话resultMap标签可以省略********
    resultMap标签:映射实体和表关系
    id:映射关系id,要唯一
    type:实体全路径
    -->
    <resultMap id="memberMap" type="com.eggtwo.euq.entity.Member">
        <!--id:映射主键属性
        result:映射非主键属性
        property:实体属性名称
        column:表字段名称
        -->
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="age" column="age"/>
        <result property="birthday" column="birthday"/>
        <result property="man" column="man"/>
        <result property="score" column="score"/>
    </resultMap>

    <insert id="add" parameterType="com.eggtwo.euq.entity.Member" useGeneratedKeys="true" keyProperty="id">
      insert  into t_member(name,age,birthday,man,score)
       values(#{name},#{age},#{birthday},#{man},#{score})
    </insert>

    <update id="update" parameterType="com.eggtwo.euq.entity.Member">
        update t_member set
        name = #{name},
        age = #{age},
        birthday = #{birthday},
        man = #{man},
        score = #{score}
        where id = #{id}
    </update>

    <delete id="delete" parameterType="int">
        delete from t_member where id = #{id}
    </delete>

    <!-- <select id="getById" parameterType="int" resultType="com.eggtwo.entity.Member">-->
    <!--resultType使用mybatis.xml中设置的别名,这样可以简化难度-->
    <select id="getById" parameterType="int"  resultMap="memberMap">
        select id,name,age,birthday,man,score
        from  t_member
        where id=#{id}
    </select>
    <!--
    理论上resultType的值应该是:List<com.eggtwo.entity.Member>
    实际上只需要写List集合中的类型就可以
    -->
    <select id="getAll" resultMap="memberMap">
        select *
        from  t_member
    </select>
    <!--分页:多参数的写法-->
    <select id="getPageList" parameterType="map" resultMap="memberMap">
        select id,name,age,birthday,man,score
         from t_member limit #{start},#{size}
    </select>

    <!--多条件查询-->
    <select id="getListByWhere" parameterType="map" resultMap="memberMap">
        select id,name,age,birthday,man,score
        from t_member
        <where>
            <if test="name!=null and name!=‘‘">
                and name like #{name}
            </if>
            <if test="score!=null">
                and score > #{score}
            </if>
        </where>
    </select>


    <!--动态更新:可以支持部分字段更新-->
    <update id="dynamicUpdate" parameterType="map">
        update t_member
        <set>
            <if test="name!=null">
                name = #{name},
            </if>
            <if test="age!=null">
                age = #{age},
            </if>
            <if test="birthday!=null">
                birthday = #{birthday},
            </if>
            <if test="man!=null">
                man = #{man},
            </if>
            <if test="score!=null">
                score = #{score},
            </if>
        </set>
        where id=#{id}
    </update>

    <!--根据ids数组批量删除数据-->
    <delete id="batchDelete" >
        delete from t_member where id in
        <!--
        循环数组
        解析成:(1,2,34)
        #id表示数组中的每一个元素,名称可以任意写
        -->
        <foreach collection="array" open="(" close=")" separator="," item="id">
            #{id}
        </foreach>
    </delete>
    <!--根据ids列表批量删除数据-->
    <delete id="batchDeleteList" >
        delete from t_member where id in
        <!--
        循环数组
        解析成:(1,2,34)
        #id表示数组中的每一个元素,名称可以任意写
        -->
        <foreach collection="list" open="(" close=")" separator="," item="id">
            #{id}
        </foreach>
    </delete>
</mapper>
View Code

3.配mybatis.xml

技术图片
<?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>
    <!--配置类的别名:使用type的地方可以直接写alias的值-->
    <typeAliases>     
        <!--用类名做别名-->
        <package name="com.eggtwo.euq.entity"/>
    </typeAliases>

    
</configuration>
View Code

4.编写dao

技术图片
package com.eggtwo.euq.dao;

import com.eggtwo.euq.entity.Member;

public interface MemberDao {
    public void  add(Member member);
}
View Code

4.1编写service

技术图片
package com.eggtwo.euq.service;

import com.eggtwo.euq.dao.MemberDao;
import com.eggtwo.euq.entity.Member;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

//用注解实现IOC
@Service("memberService")
public class MemberService {

    @Autowired
    private MemberDao memberDao;

    public void add(Member member) throws Exception {
        memberDao.add(member);
       // int a = 3 / 0;

    }
}
View Code

5.配置spring.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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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.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/mvc
           http://www.springframework.org/schema/tx/spring-mvc.xsd

">
 
    <!-- 配置C3P0连接池,目的:管理数据库连接 -->
    <bean id="comboPooledDataSourceID" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=utf8"/>
        <property name="user" value="root"/>
        <property name="password" value="123456"/>

        <!-- c3p0连接池的私有属性 -->
        <property name="maxPoolSize" value="30" />
        <property name="minPoolSize" value="10" />
        <!-- 关闭连接后不自动commit -->
        <property name="autoCommitOnClose" value="false" />
        <!-- 获取连接超时时间 -->
        <property name="checkoutTimeout" value="10000" />
        <!-- 当获取连接失败重试次数 -->
        <property name="acquireRetryAttempts" value="2" />

    </bean>


    <!-- 配置SqlSessionFactoryBean,目的:加载mybaits配置文件和映射文件,即替代原Mybatis工具类的作用 -->
    <bean id="sqlSessionFactoryBeanID" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="comboPooledDataSourceID"/>
        <!--加载mybatis.xml文件-->
        <property name="configLocation" value="classpath:mybatis.cfg.xml"/>
        <!--配置扫描式加载sql映射文件,去掉mybatis.xml中的mappers-->
        <property name="mapperLocations" value="classpath:com/eggtwo/euq/entity/*.xml"/>
    </bean>


    <!-- 配置Mybatis的事务管理器,即因为Mybatis底层用的是JDBC事务管事器,所以在这里依然配置JDBC事务管理器 -->
    <bean id="dataSourceTransactionManagerID" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="comboPooledDataSourceID"/>
    </bean>


    <!-- 配置事务通知,即让哪些方法需要事务支持 -->
    <tx:advice id="tx" transaction-manager="dataSourceTransactionManagerID">
        <tx:attributes>
            <!-- 默认只处理运行时异常,可加rollback-for="Exception/Throwable"等处理所有异常或包括错误 -->
            <tx:method name="add*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="insert*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="update*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="delete*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="*" propagation="SUPPORTS"/>
        </tx:attributes>
    </tx:advice>

    <!-- 配置事务切面,即让哪些包下的类需要事务 -->
    <aop:config>
        <!--在service包下面使用事务-->
        <aop:pointcut id="pointcut" expression="execution(* com.eggtwo.euq.service.*.*(..))"/>
        <aop:advisor advice-ref="tx" pointcut-ref="pointcut"/>
    </aop:config>


    <!-- 配置SessionTemplate,已封装了繁琐的数据操作 -->
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactoryBeanID"/>
    </bean>


    <!-- 自动扫描组件,要把controller去除,他们是在spring-mvc.xml中配置,如果不去除会影响事务管理。 -->
    <context:component-scan base-package="com.eggtwo.euq">
        <context:exclude-filter type="annotation"
                                expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- 配置 转换器,对于在basePackage设置的包(包括子包)下的接口类,
    如果接口类的全类名在Mapper.xml文件中和定义过命名空间一致,
     将被转换成spring的BEAN,在调用的地方通过@Autowired方式将可以注入接口实例 -->
    <!--ps:mappeer.xml中的namespace="com.eggtwo.euq.dao.MemberDao  标签:id="add"
    servcie中的类在调用dao中的方法时会查找(dao.way=com.eggtwo.euq.dao.MemberDao.add)
    -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactory" ref="sqlSessionFactoryBeanID"/>
        <property name="basePackage" value="com.eggtwo.euq.dao"/>
    </bean>

</beans>
View Code

 

6.配置springmvc.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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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.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/mvc
           http://www.springframework.org/schema/tx/spring-mvc.xsd

">


    <!-- 注册Action:自动扫描 单例模式-->
    <context:component-scan base-package="com.eggtwo.euq.action" />

    <!-- 通知springioc容器这些注解的作用 -->
    <context:annotation-config/>

    <!--注解映射器:可省略-->
    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>


    <!--视图解析器-->
    <!--
        如果Action中书写的是视图逻辑名称,那么视图解析器就必须配置
        如果Action中书写的是视图真实名称,那么视图解析器就不能配置
    -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 路径前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!-- 路径后缀 -->
        <property name="suffix" value=".jsp"/>
        <!-- 前缀+视图逻辑名+后缀=真实路径 -->
    </bean>


    <!-- 注册json解析适配器 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
            </list>
        </property>
    </bean>
    <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"/>
        <property name="maxUploadSize" value="10485760000"/>
        <property name="maxInMemorySize" value="40960"/>
    </bean>
</beans>
View Code

7.配置web.xml

技术图片
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!-- Spring配置 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param>



    <!-- 注册springmvc核心控制器-->
    <servlet>
        <!--servlet-name的值对应一个文件:/WEB-INF/DispatcherServlet-servlet.xml   -->
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <!-- 指定application.xml文件 -->
            <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>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>


    <!--spring编码过滤器:解决POST提交中文乱码问题-->
    <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>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>



</web-app>
View Code

8.编写action

技术图片
package com.eggtwo.euq.action;

import com.eggtwo.euq.entity.Member;
import com.eggtwo.euq.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.math.BigDecimal;
import java.util.Date;

@Controller
@RequestMapping("member")
public class MemberController extends BaseController {
    @Autowired
    private MemberService memberService;
    @RequestMapping(value = "add", method = RequestMethod.GET)
    public String add(Model model)  {

        try{
            Member member = new Member();
            member.setName("旺旺");
            member.setScore(new BigDecimal(12));
            member.setMan(new Boolean(true));
            member.setBirthday(new Date());
            member.setAge(14);
            memberService.add(member);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "member/add";


    }
}
View Code

 

java web开发入门八(ssm整合)基于intellig idea

标签:ide   limit   支持   连接失败   pass   attribute   注解   def   sel   

原文地址:https://www.cnblogs.com/eggTwo/p/11824130.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!