目录
1.操作对象数据库配置,以mysql为例,配置文件名为datasource.properties
2.log4j配置,文件名为log4j.properties
六、control目录下创建UserControl类(接口暴露)
一、创建一个Maven工程
pom.xml中导入依赖包
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.12.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
二、分层创建目录
创建模型目录(biz)
映射目录mapper
服务目录service
控制目录(control)
和实体类目录(entity)
三、main下创建资源目录并配置
1.操作对象数据库配置,以mysql为例,配置文件名为datasource.properties
mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://192.168.131.200:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf8
mysql.username=root
mysql.password=12345678
2.log4j配置,文件名为log4j.properties
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=log/hd.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
3.spring-mybatis.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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
">
<context:property-placeholder location="classpath*:datasource.properties" />
<context:annotation-config/>
<context:component-scan base-package="cn.kgc.smmvc.biz"/>
<!-- springframework 控制数据源连接 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${mysql.driver}"/>
<property name="url" value="${mysql.url}"/>
<property name="username" value="${mysql.username}"/>
<property name="password" value="${mysql.password}"/>
</bean>
<!-- springframework 声明式事务配置 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- mybatis-spring 创建SqlSessionFactory -->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="cn.kgc.smmvc.entity"/>
<property name="mapperLocations" value="classpath*:mapping/*Mapper.xml"/>
</bean>
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sessionFactory"/>
<property name="basePackage" value="cn.kgc.smmvc.biz.mapper"/>
</bean>
</beans>
4.spring-mvc.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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
">
<!-- 配置使用注解功能 -->
<context:annotation-config/>
<!-- 组件扫描 -->
<context:component-scan base-package="cn.kgc.smmvc.control"/>
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
</beans>
5.配置webapp中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">
<!-- 配置上下文参数 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring-mybatis.xml</param-value>
</context-param>
<!-- 配置侦听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置过滤器 -->
<filter>
<filter-name>CharSetFilter</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>CharSetFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Springmvc的前端控制器:DispatcherServlet -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 给DispatcherServlet配置初始化参数:指定SPringmvc的核心配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring-mvc.xml</param-value>
</init-param>
<!-- load-on-startup:设置DispatcherServlet在服务器启动时加载
大于等于0表示服务器启动时即创建,数字越大优先级越高;小于0或者不设置表示请求到达后创建 -->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 指定请求的匹配 -->
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<!-- *./表示动态请求 -->
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app >
四、创建UserMapper接口,同一管理方法
package cn.kgc.smmvc.biz.mapper;
import cn.kgc.smmvc.entity.UserCond;
import cn.kgc.smmvc.entity.UserInfo;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface UserMapper {
@Select("select * from user_info limit 0,10")
List<UserInfo> top10();
@Select("select * from user_info where user_id=#{user_id}")
UserInfo findById(int user_id);
@Select("select count(1) from user_info where user_account=#{acc} user_pass=nd5(#{pass})")
int login(@Param("acc") String account, @Param("pass") String password);
/**
* 一个参数随便写
* <=3个参数,直接入参,但要加注解
* @return
*/
List<UserInfo> findBy(UserCond uc);
}
五、server目录下创建UserService作为中间类
package cn.kgc.smmvc.biz.service;
import cn.kgc.smmvc.biz.mapper.UserMapper;
import cn.kgc.smmvc.control.UserControl;
import cn.kgc.smmvc.entity.Message;
import cn.kgc.smmvc.entity.UserCond;
import cn.kgc.smmvc.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
//通过byType形式,用来给指定的字段或方法注入所需的外部资源
@Autowired
UserMapper userMapper;
//查询前十的用户信息
public List<UserInfo> top10(){
return userMapper.top10();
}
//用户登陆验证
public boolean login(String acc,String pass){
return userMapper.login(acc,pass)>0;
}
//多条件查找用户信息
public List<UserInfo> findBy(UserCond uc){
return userMapper.findBy(uc);
}
//根据user_id查找用户信息
public UserInfo findById(int user_id){
return userMapper.findById(user_id);
}
}
六、control目录下创建UserControl类(接口暴露)
package cn.kgc.smmvc.control;
import cn.kgc.smmvc.biz.service.UserService;
import cn.kgc.smmvc.entity.Message;
import cn.kgc.smmvc.entity.UserCond;
import cn.kgc.smmvc.entity.UserInfo;
import org.omg.CORBA.IRObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.sql.SQLException;
import java.util.List;
//http://localhost:8080/user
//@RestController的作用等同于@Controller + @ResponseBody
//打上@Controller注解后,在容器启动的时候系统就会把它加载到Spring的Bean工厂,并且对其实例化。
@RestController
//@CrossOrgin用于解决跨域问题
@CrossOrigin("*")
@RequestMapping("/user")
public class UserControl {
@Autowired
UserService userService;
//注入映射请求
@RequestMapping("/top10.do")
public Message top10(){
return Message.succeed(userService.top10());
}
//开启事务
@Transactional(rollbackFor = SQLException.class,isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
@RequestMapping("/fb.do")
public Message findBy(UserCond uc){
return Message.succeed(userService.findBy(uc));
}
@RequestMapping("/login.do")
//@RequestParam注入参数请求,建议在参数数量低于3个时使用,超过3个建议在配置文件中配置
public Message login(@RequestParam("acc") String acc,@RequestParam("pass") String pass){
return Message.succeed(userService.login(acc,pass));
}
@RequestMapping("/{id}/fbi.do")
public Message findById (@PathVariable("id") int user_id){
return Message.succeed(userService.findById(user_id));
}
}
七、实体类创建
1.创建同一返回类型的抽象类Message
接口暴露需要对返回类型同一管理
package cn.kgc.smmvc.entity;
public abstract class Message<T> {
private int code;
private T t;
public static <T> Message succeed(T t){
return new Message(200,t){};
}
public static <T> Message fail(){
return new Message(500,null) {};
}
public Message(int code, T t) {
this.code = code;
this.t = t;
}
public int getCode() {
return code;
}
public T getT() {
return t;
}
}
2.创建Userinfo实体类
package cn.kgc.smmvc.entity;
public class UserInfo {
private Integer user_id;
private String user_name;
private String user_account;
private String user_pass;
private String user_gender;
private String user_phone;
private String user_pid;
private String user_province;
private String user_city;
private String user_district;
private String user_address;
public UserInfo() {
}
public Integer getUser_id() {
return user_id;
}
public void setUser_id(Integer user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_account() {
return user_account;
}
public String getUser_gender() {
return user_gender;
}
public void setUser_gender(String user_gender) {
this.user_gender = user_gender;
}
public void setUser_account(String user_account) {
this.user_account = user_account;
}
public String getUser_pass() {
return user_pass;
}
public void setUser_pass(String user_pass) {
this.user_pass = user_pass;
}
public String getUser_phone() {
return user_phone;
}
public void setUser_phone(String user_phone) {
this.user_phone = user_phone;
}
public String getUser_pid() {
return user_pid;
}
public void setUser_pid(String user_pid) {
this.user_pid = user_pid;
}
public String getUser_province() {
return user_province;
}
public void setUser_province(String user_province) {
this.user_province = user_province;
}
public String getUser_city() {
return user_city;
}
public void setUser_city(String user_city) {
this.user_city = user_city;
}
public String getUser_district() {
return user_district;
}
public void setUser_district(String user_district) {
this.user_district = user_district;
}
public String getUser_address() {
return user_address;
}
public void setUser_address(String user_address) {
this.user_address = user_address;
}
public Double getUser_balance() {
return user_balance;
}
public void setUser_balance(Double user_balance) {
this.user_balance = user_balance;
}
private Double user_balance;
public UserInfo(Integer user_id, String user_name, String user_account, String user_pass, String user_gender, String user_phone, String user_pid, String user_province, String user_city, String user_district, String user_address, Double user_balance) {
this.user_id = user_id;
this.user_name = user_name;
this.user_account = user_account;
this.user_pass = user_pass;
this.user_gender = user_gender;
this.user_phone = user_phone;
this.user_pid = user_pid;
this.user_province = user_province;
this.user_city = user_city;
this.user_district = user_district;
this.user_address = user_address;
this.user_balance = user_balance;
}
}
3.创建多条件查询实体类UserCond
package cn.kgc.smmvc.entity;
public class UserCond {
private String user_name;
private String user_gender;
private Integer user_id;
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_gender() {
return user_gender;
}
public void setUser_gender(String user_gender) {
this.user_gender = user_gender;
}
public Integer getUser_id() {
return user_id;
}
public void setUser_id(Integer user_id) {
this.user_id = user_id;
}
}
八、添加测试环境
九、测试
点击如下按钮运行程序
出现以下界面表示发布成功
测试按user_id查询用户信息 http://localhost:8080/user/fb.do?user_id=6