首先创建一个个人信息表来实现增删改查的操作.
创建个人信息表 t_personal
DROP TABLE IF EXISTS `t_personal`;
CREATE TABLE `t_personal` (
`id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '自增id',
`name` varchar(255) NOT NULL DEFAULT '' COMMENT '名称',
`age` bigint(3) NOT NULL DEFAULT '0',
`sex` varchar(1) NOT NULL DEFAULT '' COMMENT '性别',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk COMMENT='个人信息表';
现在已经建立了一个数据库表
接下来建一个maven项目.
记得要创建webapp的maven
项目结构如下:
这里面有一个PrintReqUriFilter.java是因为我没有配置路径拦截并将访问的编码格式改为UTF-8
package com.easyit.ssm.common;
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;
import org.apache.log4j.Logger;
@WebFilter("/*")
public class PrintReqUriFilter implements Filter{
private final static Logger log = Logger.getLogger(PrintReqUriFilter.class);
@Override
public void destroy() {
log.info("销毁........");
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) arg0;
HttpServletResponse response = (HttpServletResponse) arg1;
String url = request.getRequestURI();
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
arg2.doFilter(arg0, arg1);
log.info(url);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
log.info("初始化.....");
}
}
建好后的pom.xml文件如下:
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.easyit</groupId>
<artifactId>personal</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>personal Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.22</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.22</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>personal</finalName>
<plugins>
<!-- compiler插件, 设定JDK版本 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<showWarnings>true</showWarnings>
</configuration>
</plugin>
</plugins>
</build>
</project>
然后是jdbc.properties
注意这里是mysql数据库,iphone是你建立t_personal表的数据库,name是数据库的账号,password是账号密码.
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/iphone
name=root
password=root
接下来是一个log4j.properties文件
# Root logger option
log4j.rootLogger=debug, stdout
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c{2}: %m%n
然后是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>
<!-- 这里会通过log4j将SQL语句处理语句打印出来,非常方便 -->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
<mappers>
<mapper resource="personal.xml" />
</mappers>
</configuration>
然后对应实体类Personal.java
package com.easyit.ssm.model;
public class Personal {
private Long id;
private String name;
private Long age;
private String sex;
public Personal() {
}
public Personal(Long id, String name, Long age, String sex) {
super();
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getAge() {
return age;
}
public void setAge(Long age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Personal [id=" + id + ", name=" + name + ", age=" + age + ", sex=" + sex + "]";
}
}
然后是personal.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.easyit.ssm.dao.PersonalDao">
<resultMap type="com.easyit.ssm.model.Personal" id="personalMap">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="age" property="age"/>
<result column="sex" property="sex"/>
</resultMap>
<!-- 添加个人信息 -->
<insert id="insertPersonal">
insert into t_personal(name,age,sex) values(#{name},#{age},#{sex})
</insert>
<!-- 修改年龄 -->
<update id="updatePersonal">
update t_personal set age = #{age} where id = #{id}
</update>
<!-- 删除个人信息 -->
<delete id="deletePersonal">
delete from t_personal where id = #{id}
</delete>
<select id="selectPersonalToName" resultMap="personalMap">
select * from t_personal where name like '#{name}'
</select>
<select id="selectPersonalToSex" resultMap="personalMap">
select * from t_personal where sex = #{sex}
</select>
</mapper>
说明一下#与$处理SQL语句的区别
#{} 表示在预处理中会把参数部分用?占位符,能够防止大量sql语句注入.
${} 表示在动态解析过程中,会直接将数据替代进去,可能会导致大量SQL语句注入
然后是personal.xml的命名空间PersonalDao.java
package com.easyit.ssm.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.easyit.ssm.model.Personal;
public interface PersonalDao {
// 添加一条个人信息
int insertPersonal(Personal personal);
// 修改个人信息
int updatePersonal(Long id, Long age);
// 删除个人信息
int deletePersonal(Long id);
// 通过名字查询个人信息
List<Personal> selectPersonalToName(@Param("name") String name);
// 通过性别查询个人信息
List<Personal> selectPersonalToAge(String sex);
}
现在配置命名空间Dao接口的xml
dao.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:property-placeholder location="classpath:jdbc.properties" />
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driverClass}"></property>
<property name="jdbcUrl" value="${url}"></property>
<property name="user" value="${name}"></property>
<property name="password" value="${password}"></property>
</bean>
<!-- spring sessionFactoryBean 该类实现Spring 的FactoryBean 接口 getObject 返回SqlSessionFactroy对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis.xml"></property>
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- mybatis自动扫描加载Sql映射文件/接口 : MapperScannerConfigurer sqlSessionFactory
basePackage:指定sql映射文件/接口所在的包(自动扫描) -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--配置扫描的包位置,扫描会创建该包下面所有接口的Mybatis 映射代理对象 -->
<property name="basePackage" value="com.easyit.ssm.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
</beans>
然后是代理接口以及代理接口实现类
PersonalService.xml
package com.easyit.ssm.service;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.easyit.ssm.model.Personal;
public interface PersonalService {
// 添加一条个人信息
int insertPersonal(Personal personal);
// 修改个人信息
int updatePersonal(Long id, Long age);
// 删除个人信息
int deletePersonal(Long id);
// 通过名字查询个人信息
List<Personal> selectPersonalToName(String name);
// 通过性别查询个人信息
List<Personal> selectPersonalToAge(String sex);
}
这里的方法名可以不一样,但是返回值要一样,我就偷懒一波写一模一样的了.
然后是实现类
package com.easyit.ssm.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.easyit.ssm.dao.PersonalDao;
import com.easyit.ssm.model.Personal;
import com.easyit.ssm.service.PersonalService;
@Service
public class PersonalServiceImpl implements PersonalService {
@Autowired
PersonalDao personalDao;
@Override
public int insertPersonal(Personal personal) {
// 这里是可以写代码出理的
return personalDao.insertPersonal(personal);
}
@Override
public int updatePersonal(Long id, Long age) {
// 这里是可以写代码出理的
return personalDao.updatePersonal(id, age);
}
@Override
public int deletePersonal(Long id) {
// 这里是可以写代码出理的
return personalDao.deletePersonal(id);
}
@Override
public List<Personal> selectPersonalToName(String name) {
// 这里是可以写代码出理的
return personalDao.selectPersonalToName(name);
}
@Override
public List<Personal> selectPersonalToSex(String sex) {
// 这里是可以写代码出理的
return personalDao.selectPersonalToSex(sex);
}
}
然后是出来代理接口与代理接口实现类的
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:aop="http://www.springframework.org/schema/aop"
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">
<context:annotation-config />
<!-- 启动注解扫描 -->
<mvc:annotation-driven />
<context:component-scan base-package="com.easyit.ssm.service.impl"></context:component-scan>
</beans>
然后是springmvc.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:aop="http://www.springframework.org/schema/aop"
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">
<!-- 启动MVC扫描 -->
<mvc:annotation-driven />
<context:component-scan base-package="com.easyit.shiro.controller"></context:component-scan>
<!-- 配置视图解析器 -->
<!-- <bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:view-controller path="/unauthor" view-name="unauthor"/>
<mvc:view-controller path="/login" view-name="login"/>
<mvc:view-controller path="/" view-name="login"/>
<mvc:view-controller path="/register" view-name="register"/>
<mvc:view-controller path="/add" view-name="addUser"/> -->
</beans>
然后最重要的是web.xml的配置
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<!-- 配置Spring上下文监听器,该监听器WEB启动时,初始化Spring上下文 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
<url-pattern>*.css</url-pattern>
<url-pattern>*.jpg</url-pattern>
<url-pattern>*.jpeg</url-pattern>
</servlet-mapping>
<!-- 配置Spring映射 -->
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml,classpath:dao.xml</param-value>
</context-param>
</web-app>
然后运行项目(我是用jetty的)
没有报错就表示运行成功了
然后到浏览器上访问如图:
说明就成功了.
然后在简单的描述一下PersonalController.java
package com.easyit.ssm.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.easyit.ssm.service.PersonalService;
@Controller
public class PersonalController {
@Autowired
PersonalService personalService;
@RequestMapping("/add")
public String personalAdd(/* 参数 */) {
// 代码操作
//return "forward:/select";
return "要跳转的文件路径";
}
@RequestMapping("/select")
public String personalSelect(/* 参数 */){
// 代码操作
return "要跳转的文件路径";
}
}
controller层中的return也可以使用forward与redirect
详情请参考https://blog.csdn.net/qq_43052309/article/details/82260828