Mybatis实战_web应用_fastjson的使用_前后端分离(跨域问题的解决)

一、建立一个maven项目,war包。pom文件如下:

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>ztt.mybatis</groupId>
	<artifactId>mybatis02</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<dependencies>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.18</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.5.3</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>4.0.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.62</version>
		</dependency>

	</dependencies>
	<build>
		<plugins>
			<plugin>
				<!-- 编译器配置 -->
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<!-- 防止web.xml文件头报错 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>3.2.3</version>
				<configuration>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

二、创建mybatis.xml文件和log4j2.xml文件。

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>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis_db"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <package name="ztt.mybatis.dao"/>
  </mappers>
</configuration>

log4j2.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
	<Appenders>
		<Console name="Console" target="SYSTEM_OUT">
			<PatternLayout
				pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
		</Console>
	</Appenders>
	<Loggers>
		<Logger name="ztt.mybatis.mapper" level="trace" additivity="false">
			<AppenderRef ref="Console" />
		</Logger>
		<Root level="error">
			<AppenderRef ref="Console" />
		</Root>
	</Loggers>
</Configuration>

三、创建JavaBean,在ztt.mybatis.model包下,类名为Employee

package ztt.mybatis.model;

import java.util.Date;

import com.alibaba.fastjson.annotation.JSONField;

public class Employee {
	
	private String e_id;
	private String e_name;
	private Double e_sal;
	//json格式化日期
	 @JSONField(format="yyyy-MM-dd")
	private Date e_date;
	
	public Employee(String e_id, String e_name, Double e_sal, Date e_date) {
		super();
		this.e_id = e_id;
		this.e_name = e_name;
		this.e_sal = e_sal;
		this.e_date = e_date;
	}
	
	public Employee() {
		super();
		// TODO Auto-generated constructor stub
	}
	public String getE_id() {
		return e_id;
	}
	public void setE_id(String e_id) {
		this.e_id = e_id;
	}
	public String getE_name() {
		return e_name;
	}
	public void setE_name(String e_name) {
		this.e_name = e_name;
	}
	public Double getE_sal() {
		return e_sal;
	}
	public void setE_sal(Double e_sal) {
		this.e_sal = e_sal;
	}
	public Date getE_date() {
		return e_date;
	}
	public void setE_date(Date e_date) {
		this.e_date = e_date;
	}

}

四、创建Dao层,里面为接口,类名为EmployeeDao

package ztt.mybatis.dao;
import java.util.List;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import ztt.mybatis.model.Employee;
public interface EmployeeDao {
	@Select("select * from emp")
	public List<Employee> findEmployeeList();
}

五、创建一个工具包,里面放工具类

package ztt.mybatis.utils;

import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class Utils {
	private static final SqlSessionFactory FACTORY=buildSqlSessionFactory();
	//创建SqlSessionFactory
	private static SqlSessionFactory buildSqlSessionFactory() {
		try {
			//加载配置文件
			InputStream is=Resources.getResourceAsStream("mybatis.xml");
			//new一个SqlSessionFactory
			return new SqlSessionFactoryBuilder().build(is);
		} catch (IOException e) {
			throw new ExceptionInInitializerError();
		}
	}
	//因为获取工厂方法是私有的,所以重写一个公有方法获取SqlSessionFactory
	public static SqlSessionFactory getSqlSessionFactory() {
		return FACTORY;
	}
	//打开session
	public static SqlSession openSession() {
		return FACTORY.openSession(ExecutorType.REUSE);
	}
	
}

六、写Service层。

package ztt.mybatis.service;

import java.util.List;
import org.apache.ibatis.session.SqlSession;

import ztt.mybatis.dao.EmployeeDao;
import ztt.mybatis.exception.SysException;
import ztt.mybatis.model.Employee;
import ztt.mybatis.utils.Utils;
public class EmployeeService {
public List<Employee> getEmployeeList(){
		SqlSession session = Utils.openSession();
		try {
			EmployeeDao employeeDao = session.getMapper(EmployeeDao.class);		
			List<Employee> list = employeeDao.findEmployeeList();		
			session.commit();		
			return list;		
		}catch(Exception e) {
			session.rollback();			
			throw new SysException(e);			
		}finally {
			session.close();
		}
		
	}
}

七.写control层

package ztt.mybatis.service;

import java.util.List;
import org.apache.ibatis.session.SqlSession;

import ztt.mybatis.dao.EmployeeDao;
import ztt.mybatis.exception.SysException;
import ztt.mybatis.model.Employee;
import ztt.mybatis.utils.Utils;
public class EmployeeService {
public List<Employee> getEmployeeList(){
		SqlSession session = Utils.openSession();
		try {
			EmployeeDao employeeDao = session.getMapper(EmployeeDao.class);		
			List<Employee> list = employeeDao.findEmployeeList();		
			session.commit();		
			return list;		
		}catch(Exception e) {
			session.rollback();			
			throw new SysException(e);			
		}finally {
			session.close();
		}
		
	}
}

八.异常包,里面写的自定义异常

package ztt.mybatis.exception;

public class SysException extends RuntimeException {

	public SysException() {
		// TODO Auto-generated constructor stub
	}

	public SysException(String message) {
		super(message);
		// TODO Auto-generated constructor stub
	}

	public SysException(Throwable cause) {
		super(cause);
		// TODO Auto-generated constructor stub
	}

	public SysException(String message, Throwable cause) {
		super(message, cause);
		// TODO Auto-generated constructor stub
	}

	public SysException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
		// TODO Auto-generated constructor stub
	}

}

九、服务器端跨域问题的解决-建立一个拦截器,对头信息进行设置。

package ztt.mybatis.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//服务器端设置跨域请求
@WebFilter("/*")
public class MyFilter implements Filter {

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		
        res.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        res.setHeader("Access-Control-Max-Age", "0");
        res.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
        res.setHeader("Access-Control-Allow-Credentials", "true");
        res.setHeader("XDomainRequestAllowed","1");
		chain.doFilter(request, response);
		
	}

    public MyFilter() {
        // TODO Auto-generated constructor stub
    }

	public void destroy() {
		// TODO Auto-generated method stub
	}
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}

以上,服务器端的开发已经完成。下来对客户端进行详细描述:

一、分别建立css和js文件夹,并引入要使用的css文件和js文件

二、建立html页面。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" >
        <title>员工管理</title>
        <link type="text/css" href="css/bootstrap.min.css" rel="stylesheet" >
    </head>
    <body class=".container">
        <div id="app" >
            <table class="table table-striped">
                <thead>
                    <tr>
                        <td>工号</td>
                        <td>姓名</td>
                        <td>月薪</td>
                        <td>入职日期</td>                        
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="item in empList">
                        <td>{{item.e_id}}</td>
                        <td>{{item.e_name}}</td>
                        <td>{{item.e_sal}}</td>
                        <td>{{item.e_date}}</td>                        
                    </tr>
                </tbody>
            </table>
        </div>

        <script src="js/jquery-3.4.1.min.js" ></script>
        <script src="js/popper.min.js"></script>
        <script src="js/bootstrap.min.js" ></script>
        <script src="js/vue.min.js" ></script>
        <script>
        
            const vm = new Vue({
                el:'#app',
                data:{
                    empList:[]
                },
                methods:{

                },
                mounted(){
                    $.ajax({
                        url:'http://localhost:8080/mybatis02/empList',
                        method:'get',
                        dataType:'json',
                        //设置跨域请求
                        crossDomain:true,
                        xhrFields: {
                            withCredentials: true//支持seesion认证
                        }

                    })
                    .done((list)=>{
                        this.empList = list;
                    })
                    .fail((xhr)=>{

                    });

                }
            });   
        
        </script>
    </body>

</html>

将maven项目部署在服务器上,运行效果:

服务器端生成的json:

客户端生成的页面:

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值