-
1、导jar包
-
2、项目目录结构
-
3、配置 web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<servlet>
<servlet-name>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>encodingfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
web-app>
- 4、配置 applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd"
default-autowire="byName">
<context:component-scan
base-package="com.mak.service.impl">context:component-scan>
<context:property-placeholder
location="classpath:db.properties" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${mysql.jdbc.driver}">property>
<property name="url" value="${mysql.jdbc.url}">property>
<property name="username" value="${mysql.jdbc.username}">property>
<property name="password" value="${mysql.jdbc.password}">property>
bean>
<bean id="factory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="typeAliasesPackage" value="com.mak.pojo">property>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="factory">property>
<property name="basePackage" value="com.mak.mapper">property>
bean>
<bean id="txManage"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource">property>
bean>
<tx:advice id="txAdvice" transaction-manager="txManage">
<tx:attributes>
<tx:method name="ins*" />
<tx:method name="del*" />
<tx:method name="upd*" />
<tx:method name="*" read-only="true" />
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut
expression="execution(* com.amk.service.impl.*.*(..))" id="pointcut" />
<aop:advisor advice-ref="txManage" pointcut-ref="pointcut" />
aop:config>
beans>
<?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: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:component-scan
base-package="com.mak.controller"></context:component-scan>
<!-- 配置注解加载驱动 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 放行静态资源 -->
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
<mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
<mvc:resources location="/files/" mapping="/files/**"></mvc:resources>
<!-- 视图解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置拦截器 -->
<mvc:interceptors>
<bean class="com.mak.interceptor.LoginInterceptor"></bean>
</mvc:interceptors>
</beans>
mysql.jdbc.driver=com.mysql.cj.jdbc.Driver
mysql.jdbc.url=jdbc:mysql://localhost:3306/ssm?useSSL=false&serverTimezone=UTC
mysql.jdbc.username=root
mysql.jdbc.password=root
log4j.rootCategory=INFO, CONSOLE, LOGFILE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%m %n
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=E:/my.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%m%n
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '编号',
`name` varchar(20) DEFAULT NULL COMMENT '姓名',
`password` varchar(20) DEFAULT NULL COMMENT '密码',
`age` int(11) DEFAULT NULL,
`gendar` varchar(1) DEFAULT NULL,
`idol` varchar(20) DEFAULT NULL COMMENT '名言',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8 COMMENT='学生';
package com.mak.pojo;
public class Student {
private int id;
private String name;
private String password;
private int age;
private String gendar;
private String idol;
}
package com.mak.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.mak.pojo.Student;
public interface StudentMapper {
@Select("select count(*) from student where name=#{name} and password=#{password}")
int selByNamePwd(Student stu);
@Select("select * from student")
List<Student> selAll();
@Insert("insert into student values(default,#{name},#{password},#{age}),#{gendar},#{idol}")
int insStu(Student stu);
@Delete("delete from student where id=#{0}")
int delById(int id);
@Update("update student set(name=#{name}, password=#{password}, age=#{age}, gendar=#{gendar}, idol=#{idol}) where id=#{id}")
int updById(Student stu);
}
package com.mak.service;
import java.util.List;
import com.mak.pojo.Student;
public interface StudentService {
int login(Student stu);
List<Student> getAll();
int addStu(Student stu);
int delStu(int id);
int updStu(Student stu);
}
package com.mak.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.mak.mapper.StudentMapper;
import com.mak.pojo.Student;
import com.mak.service.StudentService;
@Service
public class StudentServiceImpl implements StudentService{
@Resource
private StudentMapper studentMapper;
@Override
public int login(Student stu) {
return studentMapper.selByNamePwd(stu);
}
@Override
public List<Student> getAll() {
return studentMapper.selAll();
}
@Override
public int addStu(Student stu) {
return studentMapper.insStu(stu);
}
@Override
public int delStu(int id) {
return studentMapper.delById(id);
}
@Override
public int updStu(Student stu) {
return studentMapper.updById(stu);
}
}
package com.mak.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class LoginInterceptor implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
}
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
if (arg0.getRequestURI().equals("/SSM-IDUS/login")) {
return true;
}else if (arg0.getRequestURI().equals("/SSM-IDUS/validcode")) {
return true;
} else {
if (arg0.getSession().getAttribute("stu") != null) {
return true;
} else {
arg1.sendRedirect("/index.jsp");
return false;
}
}
}
}
package com.mak.controller;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.mak.pojo.Student;
import com.mak.service.StudentService;
@Controller
public class StudentController {
@Resource
private StudentService studentServiceImpl;
@RequestMapping("login")
public String login(Student stu, String validcode, HttpServletRequest req, HttpServletResponse resp,
HttpSession session) {
String codeSession = req.getSession().getAttribute("validcode").toString();
if (codeSession.equals(validcode)) {
if (studentServiceImpl.login(stu) > 0) {
session.removeAttribute("error");
return "main";
} else {
session.setAttribute("error", "用户名密码不正确");
return "redirect:/index.jsp";
}
} else {
session.setAttribute("error", "验证码不正确");
return "redirect:/index.jsp";
}
}
}
package com.mak.controller;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class ValidcodeController {
@RequestMapping("validcode")
@ResponseBody
public void getValidcode(HttpServletRequest req, HttpServletResponse resp, HttpSession session) throws IOException {
BufferedImage image = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB);
Graphics2D gra = image.createGraphics();
gra.setColor(Color.WHITE);
gra.fillRect(0, 0, 200, 100);
List<Integer> randList = new ArrayList<Integer>();
Random random = new Random();
for (int i = 0; i < 4; i++) {
randList.add(random.nextInt(10));
}
gra.setFont(new Font("宋体", Font.ITALIC | Font.BOLD, 40));
Color[] colors = new Color[] { Color.RED, Color.YELLOW, Color.BLUE, Color.GREEN, Color.PINK, Color.GRAY };
for (int i = 0; i < randList.size(); i++) {
gra.setColor(colors[random.nextInt(colors.length)]);
gra.drawString(randList.get(i) + "", i * 40, 70 + (random.nextInt(21) - 10));
}
for (int i = 0; i < 2; i++) {
gra.setColor(colors[random.nextInt(colors.length)]);
gra.drawLine(0, random.nextInt(101), 200, random.nextInt(101));
}
ServletOutputStream outputStream = resp.getOutputStream();
ImageIO.write(image, "jpg", outputStream);
session = req.getSession();
session.setAttribute("validcode", "" + randList.get(0) + randList.get(1) + randList.get(2) + randList.get(3));
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录title>
<script type="text/javascript" src="/SSM-IDUS/js/jquery-3.4.1.min.js">script>
<script type="text/javascript">
$(function(){
$("a").click(function(){
$("img").attr("src","validcode?date="+new Date());
return false;
})
})
script>
head>
<body>
<span style="color: red;">${error }span>
<form action="login" method="post">
用户名:<input type="text" name="name"/><br/>
密码:<input type="password" name="password"/><br/>
验证码:<input type="text" size="1" name="validcode"/><img src="validcode" width="80" height="40"/><a href="">看不清a><br/>
<input type="submit" value="登录"/>
<input type="reset" value="重置"/>
form>
body>
html>