SSM整合进阶版

        

目录

1.整体结构及呈现样式

2.添加依赖

3.自动生成代码配置(generator)

4.java部分代码展示

4.1 controller层下对应代码

4.1.1 StudentController

4.1.2 UserController

4.2 dao包

4.2.1 StudentMapper

4.2.2 UserMapper

4.3 entity包

4.3.1 Student

4.3.2 User

4.4 interceptor

4.4.1 LoginInterceptor

4.5 service

4.5.1 UserService

4.5.2 StudentService

4.5.3(1) UserServiceImpl

4.5.3(2) StudentServiceImpl

4.6 utils公共类

4.6.1 CommonResult

4.7 test(为自动生成)

5.resources部分

5.1 spring.xml

5.2 mapper包下

5.2.1 UserMapper.xml

5.2.2 StudentMapper.xml

6.webapp部分

6.1 WEB-INF

6.1.1 web.xml

6.2 前端界面代码

6.2.1 登录界面(login.jsp)

6.2.2 登录成功进入界面(elementui.html)


相对于之前的整合增加了登录界面及非登录者拦截,以及分页的使用、模糊查询的使用。

1.整体结构及呈现样式

2.添加依赖

<dependencies>
<!--添加测试依赖-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
    </dependency>
<!--添加spring依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.15.RELEASE</version>
    </dependency>
<!--添加日志-->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
<!--添加更细致的日志,每次请求都会打印出来-->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.29</version>
    </dependency>
<!--添加lombok节省get,set代码-->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.24</version>
    </dependency>
<!--添加mysql驱动依赖-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.28</version>
    </dependency>
<!--添加MYBATIS依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.9</version>
    </dependency>
<!--添加服务依赖-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
    </dependency>
<!--添加数据源依赖-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.2.8</version>
    </dependency>
<!--添加json依赖-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.13.3</version>
    </dependency>
<!--添加mybatis-spring依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.7</version>
    </dependency>
<!--添加spring-jdbc依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.15.RELEASE</version>
    </dependency>
<!--添加generator自动生成代码依赖-->
    <dependency>
      <groupId>org.mybatis.generator</groupId>
      <artifactId>mybatis-generator-core</artifactId>
      <version>1.4.0</version>
    </dependency>
<!--添加依赖-->
    <dependency>
      <groupId>com.fasterxml.jackson.datatype</groupId>
      <artifactId>jackson-datatype-jsr310</artifactId>
      <version>2.13.2</version>
    </dependency>
<!--添加分页依赖-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.3.0</version>
    </dependency>

  </dependencies>

3.自动生成代码配置(generator)

        只能自动生成student的相关代码。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <!--mysql驱动jar包位置-->
    <classPathEntry location="D:\soft\repMaven\mysql\mysql-connector-java\8.0.28\mysql-connector-java-8.0.28.jar" />
    <!--数据源的配置信息-->
    <context id="DB2Tables" targetRuntime="MyBatis3" defaultModelType="flat">
        <!--是否生成注释 suppressAllComments:去除掉注释后的影响-->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai"
                        userId="root"
                        password="123456">
        </jdbcConnection>

        <javaTypeResolver >
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        <!--java实体类的配置 enableSubPackages:小驼峰 trimStrings:去除空格-->
        <javaModelGenerator targetPackage="com.qy151wd.entity" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!--映射文件的配置-->
        <sqlMapGenerator targetPackage="mapper"  targetProject=".\src\main\resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!--dao数据访问层的配置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.qy151wd.dao" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <!--数据库名和实体的映射关系
                 schema:数据库名称
              tableName: 表名
              domainObjectName:实体类名
              -->
        <table schema="mydb" tableName="student2" domainObjectName="Student" enableCountByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false" enableDeleteByExample="false">

        </table>

    </context>
</generatorConfiguration>

4.java部分代码展示

4.1 controller层下对应代码

4.1.1 StudentController

@RestController
@Slf4j
public class StudentController {

    @Autowired
    private StudentService service;
    @RequestMapping(value = "/student",method = RequestMethod.POST,params = {"id"})
    public CommonResult getById(int id){
        return service.selectByPrimaryKey(id);
    }
    @RequestMapping(value = "/findStudent",method = RequestMethod.POST)
    public PageInfo<Student> findTestAll(Integer currentPage, Integer pageSize,@RequestBody Student student){
        log.info(currentPage+"================="+pageSize);
        return service.findAll(currentPage,pageSize,student);
    }
    @RequestMapping(value = "/deleteStudent",method = RequestMethod.POST)
    public CommonResult deleteTestAll(int id){
        return service.deleteByPrimaryKey(id);
    }
    //@RequestBody将json转换为java数据映射到student实体类中
    @RequestMapping(value = "/insertStudent",method = RequestMethod.POST)
    public CommonResult insertTestAll(@RequestBody Student student){
        return service.insert(student);
    }
    @RequestMapping(value = "/updateStudent",method = RequestMethod.POST)
    public CommonResult updateTestAll(@RequestBody Student student){
        System.out.println(student);
        return service.updateByPrimaryKeySelective(student);
    }
}

4.1.2 UserController

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public CommonResult testLogin(String username, String password, HttpSession httpSession){
        return userService.getName(username, password,httpSession);
    }
}

4.2 dao包

4.2.1 StudentMapper

public interface StudentMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(@Param("record") Student record, @Param("year") int year);

    int insertSelective(Student record);

    Student selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(@Param("record") Student record, @Param("birth") int year);

    int updateByPrimaryKey(Student record);

    List<Student> findAll(Student student);

}

4.2.2 UserMapper

public interface UserMapper {
    public User getName(@Param("name") String username, @Param("pass") String password, HttpSession httpSession);
}

4.3 entity包

4.3.1 Student

@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private Integer id;

    private String name;

    private String sex;

    @JsonSerialize(using = LocalDateSerializer.class)
    @JsonDeserialize(using = LocalDateDeserializer.class)
    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDate birth;

    private String department;

    private String address;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex == null ? null : sex.trim();
    }

    public LocalDate getBirth() {
        return birth;
    }

    public void setBirth(LocalDate birth) {
        this.birth = birth;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department == null ? null : department.trim();
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address == null ? null : address.trim();
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", birth='" + birth + '\'' +
                ", department='" + department + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

4.3.2 User

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String uername;
    private String password;

    public User(String uername, String password) {
        this.uername = uername;
        this.password = password;
    }
}

4.4 interceptor

4.4.1 LoginInterceptor

public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if (user != null) {
            return true;
        }

        response.sendRedirect("login.jsp");
//        PrintWriter writer = response.getWriter();
//        response.setCharacterEncoding("utf-8");
//        response.setContentType("application/json;charset=utf-8");
//        writer.write(new ObjectMapper().writeValueAsString(CommonResult.error("未知异常")));
//        writer.flush();
//        writer.close();
        return false;
    }
}

4.5 service

4.5.1 UserService

public interface UserService {
    CommonResult getName(@Param("name") String username, @Param("pass") String password, HttpSession httpSession);
}

4.5.2 StudentService

public interface StudentService {
    CommonResult selectByPrimaryKey(Integer id);
    PageInfo<Student> findAll(Integer currentPage, Integer pageSize,Student student);
    CommonResult deleteByPrimaryKey(Integer id);
    CommonResult insert(Student record);
    CommonResult updateByPrimaryKeySelective(Student record);

}

4.5.3(1) UserServiceImpl

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    public CommonResult getName(String username, String password, HttpSession httpSession) {
        User passName = userMapper.getName(username, password, httpSession);
        if(passName!=null){
            httpSession.setAttribute("user",passName);
            return CommonResult.success(passName);
        }else {
            return CommonResult.notFont();
        }
    }
}

4.5.3(2) StudentServiceImpl

@Service
public class StudentServiceImpl implements StudentService {

    //byType
    @Autowired
    private StudentMapper studentMapper;

    public CommonResult selectByPrimaryKey(Integer id) {
        Student student = studentMapper.selectByPrimaryKey(id);
        return CommonResult.success(student);
    }

    public PageInfo<Student> findAll(Integer currentPage, Integer pageSize,Student student){
        PageHelper.startPage(currentPage,pageSize);
        List<Student> all = studentMapper.findAll(student);
        PageInfo<Student> studentPageInfo = new PageInfo<>(all);
        return studentPageInfo;
    }

    public CommonResult deleteByPrimaryKey(Integer id) {
        int i = studentMapper.deleteByPrimaryKey(id);
        return CommonResult.success(i);
    }

    public CommonResult insert(Student record) {
        int insert = studentMapper.insert(record,record.getBirth().getYear());

        return CommonResult.success(insert);
    }

    public CommonResult updateByPrimaryKeySelective(Student record) {
        int i = studentMapper.updateByPrimaryKeySelective(record,record.getBirth().getYear());
        return CommonResult.success(i);
    }


}

4.6 utils公共类

4.6.1 CommonResult

@Data
@AllArgsConstructor
@NoArgsConstructor
public class CommonResult {
    private final static int success=200;
    private final static int error=500;
    private final static int not_fount=404;

    private int code;
    private String msg;
    private Object data;

    public static CommonResult success(Object data){
        return new CommonResult(CommonResult.success,"查询成功",data);
    }
    public static CommonResult error(Object data){
        return new CommonResult(CommonResult.error,"登录异常,请联系管理员",data);
    }
    public static CommonResult notFont(){
        return new CommonResult(CommonResult.not_fount,"未找到",null);
    }
}

4.7 test(为自动生成)

public class UserTest {
    public static void main(String[] args) throws Exception {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        //注意此处的generator.xml,要跟自己的generator的全局配置文件命名一致generator在根目录下
        File configFile = new File("generator.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
    }
}

5.resources部分

5.1 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:context="http://www.springframework.org/schema/context"
       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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
        <context:component-scan base-package="com.qy151wd"/>
    
    <mvc:annotation-driven/>
    
    <mvc:default-servlet-handler/>

    <!--数据源配置-->
    <bean id="ds" class="com.alibaba.druid.pool.DruidDataSource">
        <!--驱动名称-->
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
        <!--初始化连接池的个数-->
        <property name="initialSize" value="5"/>
        <!--最少的个数-->
        <property name="minIdle" value="5"/>
        <!--最多的个数-->
        <property name="maxActive" value="10"/>
        <!--最长等待时间单位毫秒-->
        <property name="maxWait" value="3000"/>
     </bean>

    <!--sessionFactory 整合mybatis-->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--dataSource:不可随意改名字 ref:注意跟上边的id内容一致-->
        <property name="dataSource" ref="ds"/>
        <!--设置mybatis映射文件的路径-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
        <!--设置分页-->
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                </bean>
            </array>
        </property>
    </bean>

    <!--为dao接口生成代理实现类-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--为com.qy151wd.dao包下的接口生成代理实现类-->
        <property name="basePackage" value="com.qy151wd.dao"/>
    </bean>

    <!--配置拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <mvc:exclude-mapping path="/css/**"/>
            <mvc:exclude-mapping path="/js/**"/>
            <mvc:exclude-mapping path="/login"/>
            <mvc:exclude-mapping path="/login.jsp"/>
            <bean class="com.qy151wd.interceptor.LoginInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
</beans>

5.2 mapper包下

5.2.1 UserMapper.xml

<mapper namespace="com.qy151wd.dao.UserMapper">
<select id="getName" parameterType="String" resultType="com.qy151wd.entity.User">
    select * from tb_user where uername=#{name} and password=#{pass}
</select>
</mapper>

5.2.2 StudentMapper.xml

        此处为自动生成的代码

<mapper namespace="com.qy151wd.dao.StudentMapper">
  <resultMap id="BaseResultMap" type="com.qy151wd.entity.Student">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="sex" jdbcType="VARCHAR" property="sex" />
    <result column="birth" jdbcType="DATE" property="birth" />
    <result column="department" jdbcType="VARCHAR" property="department" />
    <result column="address" jdbcType="VARCHAR" property="address" />
  </resultMap>
  <sql id="Base_Column_List">
    id, name, sex, birth, department, address
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from student2
    where id = #{id,jdbcType=INTEGER}
  </select>
  <select id="findAll" resultType="com.qy151wd.entity.Student">
    select
    <include refid="Base_Column_List" />
    from student2
    <where>
      <if test="name!=null and name!=''">
        and name like concat('%',#{name},'%')
      </if>
      <if test="sex!=null">
        and sex=#{sex}
      </if>
    </where>
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from student2
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.qy151wd.entity.Student">
    insert into student2 (id, name, sex,
      birth, department, address
      )
    values (null, #{record.name,jdbcType=VARCHAR}, #{record.sex,jdbcType=VARCHAR},
      #{year,jdbcType=DATE}, #{record.department,jdbcType=VARCHAR}, #{record.address,jdbcType=VARCHAR}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.qy151wd.entity.Student">
    insert into student2
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="name != null">
        name,
      </if>
      <if test="sex != null">
        sex,
      </if>
      <if test="birth != null">
        birth,
      </if>
      <if test="department != null">
        department,
      </if>
      <if test="address != null">
        address,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
      <if test="name != null">
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="sex != null">
        #{sex,jdbcType=VARCHAR},
      </if>
      <if test="birth != null">
        #{birth,jdbcType=DATE},
      </if>
      <if test="department != null">
        #{department,jdbcType=VARCHAR},
      </if>
      <if test="address != null">
        #{address,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <!--注意此处部分更新要考虑到字符串为null的情况-->
  <update id="updateByPrimaryKeySelective" parameterType="com.qy151wd.entity.Student">
    update student2
    <set>
      <if test="record.name != null and record.name != 'null'">
        name = #{record.name,jdbcType=VARCHAR},
      </if>
      <if test="record.sex != null and record.sex != 'null'">
        sex = #{record.sex,jdbcType=VARCHAR},
      </if>
      <if test="birth != null">
        birth = #{birth,jdbcType=DATE},
      </if>
      <if test="record.department != null and record.department != 'null'">
        department = #{record.department,jdbcType=VARCHAR},
      </if>
      <if test="record.address != null and record.address != 'null'">
        address = #{record.address,jdbcType=VARCHAR,},
      </if>
    </set>
    where id = #{record.id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.qy151wd.entity.Student">
    update student2
    set name = #{name,jdbcType=VARCHAR},
      sex = #{sex,jdbcType=VARCHAR},
      birth = #{birth,jdbcType=DATE},
      department = #{department,jdbcType=VARCHAR},
      address = #{address,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

6.webapp部分

6.1 WEB-INF

6.1.1 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">

    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring.xml</param-value>
        </init-param>
        <!--当tomcat启动时创建DipatcherServlet 默认当访问controller路径时创建-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <!--
        / 不拦截 有后缀的 例如 .jsp 会拦截静态资源
        /* 都拦截
        -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>encoder</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>encoder</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>
</web-app>

6.2 前端界面代码

6.2.1 登录界面(login.jsp)

<html>
<head>
    <title>登录页面</title>
    <link type="text/css" rel="stylesheet"  href="css/index.css">
    <script type="text/javascript" src="js/qs.min.js"></script>
    <script type="text/javascript" src="js/axios.min.js"></script>
    <script type="text/javascript" src="js/vue.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
    <style>
        html,body{
            width: 100%;
            height: 100%;
        }
        #con{
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%,-50%);
            width: 340px;
            height: 300px;
            border: 1px solid;
            padding-right: 15px;
            background-color: rgba(255, 255, 255, 0.9);
            border-radius: 50px;
            text-align:center;
        }
    </style>
</head>
<body>
<div id="con">
    <el-row :gutter="1" style="margin-top: 40px">
        <el-col :span="22">
            <el-form label-width="80px" :model="form" style="margin-top: 50px" :rules="rules">
                <el-form-item label="账号" prop="username">
                    <el-input v-model="form.username" placeholder="请输入账号名"></el-input>
                </el-form-item>
                <el-form-item label="密码" style="color: #000000" prop="password">
                    <el-input type="password" v-model="form.password" placeholder="请输入密码"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm">提交</el-button>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
</div>
</body>
<script>
    var con=new Vue({
        el:"#con",
        data: {
            form: {
                username: "",
                password: ""
            }
        },
        methods:{
            submitForm(){
                var that=this;
                var qs=Qs;
                axios.post("login", qs.stringify(this.form)).then(function (result) {
                    if(result.data.code==200){
                        that.$message.success("登录成功");
                        setTimeout(function () {
                            window.location.href="elementui.html";
                        },1000)

                    }else{
                        that.$message.error(result.data.msg);
                    }
                })
            }
        }
    })
</script>
</html>

6.2.2 登录成功进入界面(elementui.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>elementui</title>
    <link type="text/css" rel="stylesheet"  href="css/index.css">
    <script type="text/javascript" src="js/qs.min.js"></script>
    <script type="text/javascript" src="js/axios.min.js"></script>
    <script type="text/javascript" src="js/vue.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
</head>
<body>
<div id="con">
    <div align="center">
        <el-button type="primary" @click="insert">添加</el-button>
        <el-form :inline="true" :model="searchForm" class="demo-form-inline" ref="searchForm">
        <el-form-item label="姓名">
            <el-input v-model="searchForm.name" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="性别">
            <el-select v-model="searchForm.sex" placeholder="请输入性别">
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="onSearch">查询</el-button>
        </el-form-item>
        </el-form>
    </div>
    <el-table
            :data="tableData"
            border
            style="width: 100%">
        <el-table-column
                prop="id"
                label="编号"
                >
        </el-table-column>
        <el-table-column
                prop="name"
                label="姓名"
                >
        </el-table-column>
        <el-table-column
                prop="sex"
                label="性别">
        </el-table-column>
        <el-table-column
                prop="birth"
                label="生日">
        </el-table-column>
        <el-table-column
                prop="department"
                label="部门">
        </el-table-column>
        <el-table-column
                prop="address"
                label="地址">
        </el-table-column>
        <el-table-column
                fixed="right"
                label="操作"
                >
            <template slot-scope="scope">
                <el-button type="success" size="small" class="el-icon-edit" @click="updateRow(scope.row)">编辑</el-button>
                <el-button type="warning" size="small" class="el-icon-delete" @click="deleteRow(scope.row.id)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="pageSizes"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
        </el-pagination>
    <el-dialog title="学生信息修改" :visible.sync="dialogFormVisible" >
        <el-form :model="form"  ref="form" :rules="rules">
            <el-form-item label="编号" :label-width="formLabelWidth" prop="id">
                <el-input v-model="form.id" placeholder="编号" readonly></el-input>
            </el-form-item>
            <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
                <el-input v-model="form.name" placeholder="姓名" ></el-input>
            </el-form-item>
            <el-form-item label="出生日期" :label-width="formLabelWidth" prop="birth">
                <el-input v-model="form.birth" placeholder="出生日期" ></el-input>
            </el-form-item>
            <el-form-item label="地址" :label-width="formLabelWidth" prop="address">
                <el-input v-model="form.address" placeholder="地址"></el-input>
            </el-form-item>
            <el-form-item label="性别" :label-width="formLabelWidth" prop="sex">
                <el-input v-model="form.sex" placeholder="性别"></el-input>
            </el-form-item>
            <el-form-item label="部门" :label-width="formLabelWidth" prop="department">
                <el-input v-model="form.department" placeholder="部门"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" align="center">
            <el-button type="primary" @click="onSubmit('form')">确 定</el-button>
            <el-button type="primary" @click="onRemove">取消</el-button>
        </div>
    </el-dialog>
    <el-dialog title="学生信息添加" :visible.sync="adddialogFormVisible" >
        <el-form :model="addform"  ref="addform" :rules="rules">
            <el-form-item label="编号" :label-width="formLabelWidth" prop="id">
                <el-input v-model="addform.id" placeholder="编号" readonly></el-input>
            </el-form-item>
            <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
                <el-input v-model="addform.name" placeholder="姓名" ></el-input>
            </el-form-item>
            <el-form-item label="出生日期" :label-width="formLabelWidth" prop="birth">
                <el-input v-model="addform.birth" placeholder="出生日期" ></el-input>
            </el-form-item>
            <el-form-item label="地址" :label-width="formLabelWidth" prop="address">
                <el-input v-model="addform.address" placeholder="地址"></el-input>
            </el-form-item>
            <el-form-item label="性别" :label-width="formLabelWidth" prop="sex">
                <el-input v-model="addform.sex" placeholder="性别"></el-input>
            </el-form-item>
            <el-form-item label="部门" :label-width="formLabelWidth" prop="department">
                <el-input v-model="addform.department" placeholder="部门"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" align="center">
            <el-button type="primary" @click="addinsert('addform')">确 定</el-button>
            <el-button type="primary" @click="onRemo">取消</el-button>
        </div>
    </el-dialog>
</div>
</body>
<script>
    var con=new Vue({
        el:"#con",
        data:{
            searchForm:{
            },
            //当前显示的页面变量
            currentPage:1,
            //
            pageSizes:[5,10,15,20],
            pageSize:5,
            //总条数
            total:0,
            tableData:[],
            dialogFormVisible:false,
            adddialogFormVisible:false,
            formLabelWidth:"80px",
            form:{
                id:0,
                name:'',
                birth:'',
                address:'',
                sex:'',
                department:''
            },
            addform:{
                id:0,
                name:'',
                birth:'',
                address:'',
                sex:'',
                department:''
            },
            rules: {
                name: [
                    { required: true, message: '请输入名称', trigger: 'blur' },
                    { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
                ],
                age: [
                    { required: true, message: '请输入年龄', trigger: 'blur' },
                    { pattern:/^[1-9][0-9]{0,1}$/, message: '请输入1~99之间的数字', trigger: 'blur'}
                ],
                address: [
                    { required: true, message: '请输入地址', trigger: 'blur' }
                ],
                sex: [
                    { required: true, message: '请输入性别', trigger: 'blur' },
                    { min:1,max:1, message: '请输入男或女', trigger: 'blur'}
                ]
            }
        },
        created(){
            this.init();
        },
        methods: {
            //搜索按钮事件
            onSearch(){
                this.init();
                this.searchForm={};
            },
            handleSizeChange(val) {
                this.pageSize=val;
                this.init();
            },
            handleCurrentChange(val) {
                //console.log("当前页"+val+"条");
                this.currentPage=val;
                this.init();
            },
            init() {
                var that = this;
                axios.post("findStudent?currentPage="+this.currentPage+"&pageSize="+this.pageSize,this.searchForm).then(function (result) {

                        that.tableData = result.data.list;
                        that.total=result.data.total;
                })
            },
            deleteRow(id) {
                var that = this;
                axios.post("deleteStudent?id="+id).then(function (result) {
                    if (result.data.code === 200) {
                        that.$message.success("删除成功");
                        that.init();
                    }
                })
            },
            updateRow(row) {
                this.dialogFormVisible = true;
                this.form = Object.assign({}, row);
            },
            onSubmit(form) {
                this.$refs[form].validate((valid) => {
                    if (valid) {

                        axios.post("updateStudent",con.form).then(function (result) {
                            con.$message.success("修改成功");
                            con.init();
                            con.dialogFormVisible = false;
                        })
                    } else {
                        console.log('error submit');
                        return false;
                    }
                })

            },
            onRemove() {
                this.dialogFormVisible = false;
            },
            insert() {
                this.adddialogFormVisible = true;
            },
            onRemo() {
                this.$refs["addform"].resetFields();
                this.adddialogFormVisible = false;
            },
            addinsert(addform1) {
                console.dir(this.addform)
                this.$refs[addform1].validate((valid) => {
                    if (valid) {
                        axios.post("insertStudent", con.addform).then(function (result) {
                            con.$message.success("添加成功");
                            con.init();
                            con.adddialogFormVisible = false;
                            for(var key in con.addform){
                                if(typeof con.addform[key]==='string'){
                                    con.addform[key]='';
                                }else{
                                    con.addform[key]=0;
                                }

                            }
                        })
                    } else {
                        console.log('error submit');
                        return false;
                    }
                })
            }
        }
    })
</script>
</html>

猜你喜欢

转载自blog.csdn.net/qq_50896786/article/details/125338965