生成动态验证码
一.静态随机验证码
1. servlet层ValidCodeServlet.java
@WebServlet("/validcode")
public class ValidCodeServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, 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中
HttpSession session = req.getSession();
session.setAttribute("code",
""+randList.get(0)+randList.get(1)+randList.get(2)+randList.get(3));
}
}
2.界面表单index.jsp
<form action="login" method="post">
用户名:<input type="text" name="username"/><br/>
密码:<input type="password" name="password"/><br/>
验证码:<input type="text" size="1" name="code"/>
<img src="validcode" width="80" height="40"/><a href="">看不清</a>
<br/>
<input type="submit" value="登录"/><input type="reset" value="重置"/>
</form>
3.刷新验证码index.jsp
引入jquery库
<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function(){
$("a").click(function(){
//浏览器带有缓存功能,不会多次请求相同数据
$("img").attr("src","validcode?date="+new Date());
return false;
})
})
</script>
二.登陆
1.导jar包
2.编写web.xml(spring整合web)
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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">
<!-- 当tomcat加载web.xml时,把spring配置文件信息存放application对象 -->
<!-- WebApplicationContext 容器 ,是ApplicationContext子接口 -->
<!-- 设置spring配置文件路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 加载Spring配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
3.配置applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 获取数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver">
</property>
<property name="url" value="jdbc:mysql://localhost:3306/sum">
</property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- spring帮助创建SqlSessionFactory -->
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 扫描器,扫描接口,并创建接口对象-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.youdian.mapper"></property>
<property name="sqlSessionFactory" ref="factory"></property>
</bean>
<!-- 创建Service -->
<bean id="usersService"
class="com.youdian.service.impl.UsersServiceImpl">
<property name="usersMapper" ref="usersMapper"></property>
</bean>
</beans>
至此,环境搭建完成
4.设计数据库
create table users(
id int(10) primary key auto_increment,
username varchar(20) unique,
password varchar(20)
);
5.pojo层
加入set和get方法
public class Users {
private int id;
private String username;
private String password;
}
6.mapper层
接口
public interface UsersMapper {
@Select("select * from users where username=#{username} and password=#{password}")
Users selByUsersPwd(Users users);
}
7.service层
接口
public interface UsersService {
Users login(Users users);
}
实现类
public class UsersServiceImpl implements UsersService {
private UsersMapper usersMapper;
public UsersMapper getUsersMapper() {
return usersMapper;
}
public void setUsersMapper(UsersMapper usersMapper) {
this.usersMapper = usersMapper;
}
@Override
public Users login(Users users) {
return usersMapper.selByUsersPwd(users);
}
}
8.servlet层
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private UsersService usersService;
@Override
public void init() throws ServletException {
ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
usersService=ac.getBean("usersService",UsersServiceImpl.class);
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String code = req.getParameter("code");
String codeSession = req.getSession().getAttribute("code").toString();
if(codeSession.equals(code)){
String username = req.getParameter("username");
String password = req.getParameter("password");
Users users = new Users();
users.setPassword(password);
users.setUsername(username);
Users user = usersService.login(users);
if(user!=null){
resp.sendRedirect("index.jsp");
}else{
req.setAttribute("error", "用户名密码不正确");
req.getRequestDispatcher("index.jsp").forward(req, resp);
}
}else{
req.setAttribute("error", "验证码不正确");
req.getRequestDispatcher("index.jsp").forward(req, resp);
}
}
}