前端怎么调用后台数据接口?(前提是服务器搭建好,并且项目能正常启动)
前端用ajax方式调用,分为get方式和post,这两者的区别就不说了
ajax中的url:URL:http://ip:port/ 项目名 /控制器名/方法名
example:URL:http:///ip:8080/ 项目名/User/Login
@Controller
@RequestMapping("/User")
public class UserController {
@CrossOrigin(allowCredentials = "true")
@ResponseBody
@PostMapping("/Login")
public ResponseMessage login(String userId, String password, HttpServletRequest request) {
...代码块...
}
}
当前端采用get方式时,用@GetMapping("/Login"),采用post方式时,用@PostMapping("/Login")
(后面极有可能遇到session无法传递,这就是跨域问题,可以看本篇博文后面部份)
SSM框架集成了mybaties,Spring,Spring MVC,能实现接口开发
mybaties配置
<?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>
<!-- 别名配置 把entity包中简单类起个别名(如User类的别名就是user) -->
<typeAliases>
<package name="entity"/>
</typeAliases>
</configuration>
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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:aop="http://www.springframework.org/schema/aop"
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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 配置数据源(spring接管了mybatis的配置) -->
<!-- c3p0连接池 -->
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- jdbc:mysql://localhost:3306/testdb?serverTimezone=UTC -->
<!-- 本地数据库可以省略localhost:3306 -->
<property name="jdbcUrl"
value="jdbc:mysql://服务器ip/数据库名?serverTimezone=UTC"></property>
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
<property name="user" value="root"></property>
<property name="password" value="*****数据库密码"></property>
<!-- 当连接池中的连接耗尽的时候c3p0一次同时获取的连接数,Default: 3 -->
<property name="acquireIncrement" value="3"></property>
<!-- 初始化时获取连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize" value="10"></property>
<property name="minPoolSize" value="2"></property>
<property name="maxPoolSize" value="10"></property>
</bean>
<!-- sqlSessionFactory配置 (回忆一下mybatis编程,现在由spring注入) -->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 加载mybatis-config配置 -->
<property name="configLocation"
value="classpath:mybatis/mybatis-config.xml" />
</bean>
<!-- 配置mybatis mapper批量扫描 -->
<!-- 从basePackage指定的mapper包中扫描mapper类,自动生成bean -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName"
value="sqlSessionFactory" />
<property name="basePackage" value="mapper" />
</bean>
<!-- 事务配置(spring接管mybatis事务操作,如事务的提交、回滚、关闭等) -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 使用annotation注解方式配置事务 -->
<tx:annotation-driven
transaction-manager="transactionManager" />
<!-- 自动扫描配置 -->
<!-- 在base-package包中扫描@Service、@Component注解的类, 并把这些类自动注册为bean 备注:@Controller放到spring
mvc扫描 -->
<context:component-scan base-package="service" />
<context:component-scan base-package="entity" />
</beans>
Spring MVC配置
<?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: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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 启用注解映射+json转换器 -->
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter "/>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 自动扫描 -->
<!-- spring mvc自动扫描base-pack下或子包下的@Controller注解的类,自动注册为bean
注:@Service、@Component一般放到spring配置文件中去扫描-->
<context:component-scan base-package="controller"/>
<!-- 视图解析路径配置 依赖jstl包-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="contentType" value="text/html"/>
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 文件上传配置 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/><!-- 默认编码ISO-8859-1 -->
<property name="maxInMemorySize" value="10240"/><!-- 最大内存 10M -->
<property name="uploadTempDir" value="/Static-Resources/images/" /><!-- 上传的文件夹名字 -->
<property name="maxUploadSize" value="-1" /><!-- 最大文件,-1不限制 -->
</bean>
<!-- 配置静态资源(JS、CSS、图片等)的访问路径-->
<!--对location文件夹下内容的访问将不再被DispatcherServlet拦截,在webapp下面兴建文件夹-->
<mvc:resources mapping="/images/**" location="/Static-Resources/images/"/>
<!--<mvc:resources mapping="/gif/**" location="/gif/"/>
<mvc:resources mapping="/jquery/**" location="/jquery/"/>
<mvc:resources mapping="/css/**" location="/Static-Resources/css/"/>
<mvc:resources mapping="/js/**" location="/Static-Resources/js/"/>-->
</beans>
然后下面介绍遇到的一系列问题
- 前端ajax请求始终error
跨域问题,需要在接口上方添加注解 @CrossOrigin(allowCredentials=“true”) - javax.servlet.http无法导入,导致session创建失败
需要从Tomcat中导入依赖 - idea 打包war包程序包javax.servlet.http不存在
在pom.xml中添加依赖
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
- SSM静态文件存放位置
需要在Spring MVC配置中添加
<mvc:resources mapping="/images/**" location="/Static-Resources/images/"/>
访问方式:http://localhost:8080/images/default-avatar.jpg
- 文件上传时如果上传到Tomcat/weebapps/ROOT/upload/目录下
访问方式:http://服务器ip:8080/upload/3.jpg - 跨域拦截配置
前后端分离时,会出现跨域问题
一方面会使后端数据不能送达前端
解决办法:在方法上添加注解
@CrossOrigin(allowCredentials="true")
另一方面,会出现sessionId不一致问题
解决办法:添加配置函数
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
// 设置跨域访问
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "TRACE")
.allowCredentials(true);
}
}
前端ajax请求添加
xhrFields: {
withCredentials: true
}
希望有所帮助