maven tomcat7插件启动
maven依赖
<?xml version="1.0" encoding="UTF-8"?>
<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>com.painter</groupId>
<artifactId>SSM</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>SSM Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<!--整合springmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<!--整合mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<!--使用alibaba数据源jdbc数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
<!-- servlet依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--使用@ResponseBody 能够响应数据 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<configuration>
<address>127.0.0.1</address>
<port>8080</port>
<path>/</path> <!-- 应用程序上下文-->
<ignorePackaging>true</ignorePackaging>
</configuration>
</plugin>
</plugins>
</build>
</project>
web依赖
<?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">
</web-app>
配置层 com.painter.config
JdbcConfig数据库配置类
package com.painter.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
/**
* @Author: Painter
* @project_name: SSM
* @system_login: sunshine
* @time: 2022/10/1119:30
*/
public class JdbcConfig { // 数据库配置
/**
* 定义数据源配置
*
* @return
*/
@Bean
public DataSource dataSource() {
DruidDataSource druidDataSource = new DruidDataSource(); // 创建数据源(阿里巴巴)
druidDataSource.setDriverClassName("com.mysql.jdbc.Driver"); // 加载数据库驱动
druidDataSource.setUrl("jdbc:mysql://localhost:3306/ssm?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT"); // 设置url
druidDataSource.setUsername("root"); // 数据库用户名
druidDataSource.setPassword("root"); // 数据库用户密码
return druidDataSource;
}
/**
* 整合事务
* * @Autowired加上该注解,就会自动调用本类的该方法
* @param dataSource
* @return
*/
@Bean
public PlatformTransactionManager platformTransactionManager(@Autowired DataSource dataSource) {
DataSourceTransactionManager dataSourceTransactionManager =
new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource); //设置数据源
return dataSourceTransactionManager;
}
}
MybatisConfig配置类
package com.painter.config;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
/**
* @Author: Painter
* @project_name: SSM
* @system_login: sunshine
* @time: 2022/10/1119:34
*/
public class MybatisConfig {
/**
* mybatis相关配置
*
* @param dataSource
* @return
*/
@Bean
public SqlSessionFactoryBean sqlSessionFactory(@Autowired DataSource dataSource) {
SqlSessionFactoryBean sqlSessionFactoryBean =
new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
// 实体层包
sqlSessionFactoryBean.setTypeAliasesPackage("com.painter.entity");
return sqlSessionFactoryBean;
}
}
ServletConfig配置类
package com.painter.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/**
* @Author: Painter
* @project_name: SSM
* @system_login: sunshine
* @time: 2022/10/120:28
*/
public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
/**
* 加载spring所有配置
* @return
*/
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
/**
* 加载springmvc所有配置
* @return
*/
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMVCConfig.class};
}
/**
* 拦截所有的请求
* @return
*/
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
SpringConfig配置类
package com.painter.config;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @Author: Painter
* @project_name: SSM
* @system_login: sunshine
* @time: 2022/10/1119:35
*/
@Configuration
@EnableTransactionManagement //开启事务
@Import({MybatisConfig.class, JdbcConfig.class}) // 导入类
@MapperScan("com.painter.mapper") // 扫包范围
@ComponentScan("com.painter.service") // 扫包范围
public class SpringConfig {
}
SpringMVCConfig配置类
package com.painter.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
/**
* @Author: Painter
* @project_name: SSM
* @system_login: sunshine
* @time: 2022/10/120:26
*/
@EnableWebMvc
@Configuration
@ComponentScan("com.painter.controller")
public class SpringMVCConfig implements WebMvcConfigurer {
/**
* 1.@Configuration 定义SpringMVCConfig.xml配置文件
* 2.需要将我们的控制类注入到ioc容器 @ComponentScan("com.mayikt.controller")
* *@ComponentScan("com.mayikt.controller")将该包下所有的类 注入到IOC容器种
* 3.在springmvc原理 所有请求过来先达到我们的 DispatcherServlet 分发具体控制类 方法执行
*
*
* @Configuration
* SpringMVCConfig.java @Configuration
* springmvc.xml=== SpringMVCConfig.java
* -->
*/
//WebMvcConfigurer
@Bean
public InternalResourceViewResolver resourceViewResolver() {
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
//请求视图文件的前缀地址
internalResourceViewResolver.setPrefix("/WEB-INF/jsp/");
//请求视图文件的后缀
internalResourceViewResolver.setSuffix(".jsp");
internalResourceViewResolver.setExposeContextBeansAsAttributes(true);
return internalResourceViewResolver;
}
/**
* 视图配置
*
* @param registry
*/
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.viewResolver(resourceViewResolver());
}
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
控制层 com.painter.controller
GlobalExceptionHandler全局捕获异常类
package com.painter.controller;
import com.painter.model.ResultData;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
* @Author: Painter
* @project_name: SSM
* @system_login: sunshine
* @time: 2022/10/1212:00
*/
@ControllerAdvice // 全局捕获异常信息
public class GlobalExceptionHandler extends ResultData {
@ResponseBody
@ExceptionHandler(value = Exception.class)
public HashMap<String, Object> handleException(Exception e) {
HashMap<String, Object> h = new HashMap<>();
h.put("customize exception message", ""+e.getMessage());
return setResult("500","系统发生了错误!",h);
}
}
UserController控制类
package com.painter.controller;
import com.painter.entity.UserEntity;
import com.painter.model.ResultData;
import com.painter.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
/**
* @Author: Painter
* @project_name: SSM
* @system_login: sunshine
* @time: 2022/10/1119:09
*/
@RestController // 表示该类为控制类,返回的是json数据(相当于每个接口都加了@ResponseBody注解)
public class UserController extends ResultData {
@Autowired // 自动装配,bean对象
private UserService userService;
@PostMapping("/add") // 增
public HashMap<String, Object> adds(UserEntity userEntity){
int insert = userService.insert(userEntity); // 调用方法插入数据
if (insert > 0) {
return resultOk(insert);
}
return resultError("用户信息添加失败");
}
@GetMapping("/deletes") // 删
public HashMap<String, Object> deletes(Integer id){
int delete = userService.delete(id); // 调用方法删除数据
if (delete > 0) {
return resultOk(delete);
}
return resultError("用户信息删除失败");
}
@PostMapping("/updates") // 修改
public HashMap<String, Object> updates(UserEntity userEntity){
int update = userService.update(userEntity); // 调用方法修改数据
if (update >0){
return resultOk(update);
}
return resultError("用户信息更新失败");
}
@GetMapping("/querys") // 查询指定id的数据
public HashMap<String, Object> querys(Integer id){
UserEntity userEntity = userService.get(id); // 调用方法查询指定用户信息
if(userEntity != null){
return resultOk(userEntity);
}
return resultError("没有查询到id = "+id+"的用户信息");
}
@GetMapping("/queryss") // 查询所有信息
public HashMap<String, Object> queryss(){
List<UserEntity> list = userService.gets(); // 调用方法查询所有信息
if (list.size() > 0){
return resultOk(list);
}
return resultError("没有查询到用户信息");
}
@GetMapping("/test") // 测试url
public String test(){
// 返回的就是网页数据 html文件格式
return "<a href=\"http://127.0.0.1:8080/001.jpg\"><h1>test</h1></a>";
}
}
viewController视图控制类
package com.painter.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
/**
* @Author: Painter
* @project_name: SSM
* @system_login: sunshine
* @time: 2022/10/1211:21
*/
@Controller
public class viewController { // 视图url映射
@GetMapping("/add") // 增
public String add(){
return "add";
}
@GetMapping("/delete") // 删
public String delete(){
return "delete";
}
@GetMapping("/update") // 改
public String update(){
return "update";
}
@GetMapping("/query") // 查
public String query(){
return "query";
}
}
实体层com.painter.entity
UserEntity user数据表实体类
package com.painter.entity;
/**
* @Author: Painter
* @project_name: SSM
* @system_login: sunshine
* @time: 2022/10/1118:46
*/
public class UserEntity { //数据库ssm user表 的实体类
private Integer id;
private String userName;
private String password;
public UserEntity(Integer id, String userName, String password) {
this.id = id;
this.userName = userName;
this.password = password;
}
public UserEntity(String userName, String password) {
this.userName = userName;
this.password = password;
}
public UserEntity() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "UserEntity{" +
"id=" + id +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
'}';
}
}
mapper层 com.painter.mapper
UserMapper sql语句执行接口
/**
* @Author: Painter
* @project_name: SSM
* @system_login: sunshine
* @time: 2022/10/1118:48
*/
package com.painter.mapper;
import com.painter.entity.UserEntity;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import java.util.List;
public interface UserMapper {
/**
* #{userName}, #{password} 从该方法的形参值获取
* 会将UserEntity对象的对应的成员属性值赋值给#{userName}, #{password}
*
* @param userEntity 数据表的实体类
* @return 插入数据
*/
@Insert("INSERT INTO `ssm`.`user` (`id`, `userName`, `password`) VALUES (null, #{userName}, #{password});")
int insert(UserEntity userEntity);
/**
* id=#{id}
* 会将方法的参数值赋值给#{id}
*
* @param id 数据表的id
* @return 删除数据
*/
@Delete("delete from `ssm`.`user` where id=#{id}")
int delete(Integer id);
/**
* #{userName}, #{password}
* 会将UserEntity对象的对应的成员属性值赋值给#{userName}, #{password}
* @param userEntity
* @return 修改数据
*/
@Update("UPDATE `ssm`.`user` SET `userName` = #{userName}, `password` = #{password} WHERE `id` = #{id};")
int update(UserEntity userEntity);
/**
*
* @param id
* @return 查询数据
*/
@Select("select * from `ssm`.`user` where id=#{id}")
UserEntity get(Integer id);
/**
* @return 查询所有数据
*/
@Select("select * from `ssm`.`user`")
List<UserEntity> gets();
}
model层 com.painter.model
ResultData 返回数据模型类
package com.painter.model;
import java.util.HashMap;
/**
* @Author: Painter
* @project_name: SSM
* @system_login: sunshine
* @time: 2022/10/1211:14
*/
public class ResultData {
// 返回成功json数据
public HashMap<String,Object> resultOk(Object data){
return setResult("200", "OK", data);
}
// 返回错误json数据
public HashMap<String,Object> resultError(String msg){
return setResult("500", msg, null);
}
// 设置返回数据
public HashMap<String,Object> setResult(String code, String msg, Object data){
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("code", code);
hashMap.put("msg",msg);
hashMap.put("data",data);
return hashMap;
}
}
service层 com.painter.service
UserService user数据表业务处理类
package com.painter.service;
import com.painter.entity.UserEntity;
import com.painter.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @Author: Painter
* @project_name: SSM
* @system_login: sunshine
* @time: 2022/10/1119:04
*/
@Service // 将该类注入到ioc容器当中
public class UserService{ // 业务逻辑处理类,主要执行数据库的增删改查
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Autowired
private UserMapper userMapper;
public int insert(UserEntity userEntity){ // 增
return userMapper.insert(userEntity);
}
public int delete(Integer id){ // 删
return userMapper.delete(id);
}
public int update(UserEntity userEntity){ // 改
return userMapper.update(userEntity);
}
public UserEntity get(Integer id){ // 查
return userMapper.get(id);
}
public List<UserEntity> gets(){ // 查
return userMapper.gets();
}
}