javaWeb基础三:Web常见功能

3. 常见实现功能

实体类:

父类(Person)

public class Person {
    @FieldInfo(name= "id",type = "int",length = 10)
    private int id;
    @FieldInfo(name= "name",type = "varchar",length = 10)
    private String name;
    @FieldInfo(name= "username",type = "varchar",length = 10)
    private String username;
    @FieldInfo(name= "password",type = "varchar",length = 10)
    private String password;
    @FieldInfo(name= "sex",type = "varchar",length = 10)
    private String sex;
    @FieldInfo(name= "age",type = "int",length = 10)
    private int age;

    public Person() {
    }

    public Person(int id, String name, String username, String sex, int age) {
        this.id = id;
        this.name = name;
        this.username = username;
        this.sex = sex;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

子类(Student)

public class Student extends Person {

    @FieldInfo(name= "hobby",type = "varchar",length = 10)
    private String hobby;

    public Student() {
    }

    public Student(int id, String name, String username, String sex, int age, String hobby) {
        super(id, name, username, sex, age);
        this.hobby = hobby;
    }

    public String getHobby() {
        return hobby;
    }

    public void setHobby(String hobby) {
        this.hobby = hobby;
    }
}

3.1 后端实现自动生成验证码

要点:

1.要随机生成验证码,需要Random随机类,与图像缓冲区类BufferedImage。

2.前端页面能够点击验证码图片,切换验证码。

3.生成的验证码信息要实时保存在Session中,验证时再从Session中获取。

@WebServlet("/CodeServlet")
public class CodeServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置验证码的大小(宽高)
        int width = 100;
        int height = 40;

        //1.获取画布画笔

        //1.1创建画布
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //1.2获取画笔
        Graphics graphics = image.getGraphics();

        //2.填充背景颜色

        //2.1设置画笔的颜色
        graphics.setColor(Color.PINK);
        //2.2使用画笔填充验证码背景颜色(0,0)~(width,height)
        graphics.fillRect(0,0,width,height);

        //3.生成验证码,并画在画布上
        
        //3.1字验证码字符内容数组
        String[] ranTexts = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","1","2","3","4","5","6","7","8","9","0"};
        //3.2验证码字符颜色数组
        Color[] colors = {Color.RED,Color.BLACK,Color.BLUE,Color.MAGENTA,Color.GREEN,Color.LIGHT_GRAY};
        Random ran = new Random();

        //4.画验证码
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            //4.1设置字体,随机大小
            graphics.setFont(new Font("宋体",Font.BOLD,20+ran.nextInt(20)));
            //4.2设置随机颜色
            graphics.setColor(colors[ran.nextInt(colors.length-1)]);
            //4.3获取随机内容
            String str = ranTexts[ran.nextInt(ranTexts.length - 1)];
            //4.4将随机内容设置在画布上
            graphics.drawString(str,8+i*20,20+ran.nextInt(10));

            //4.5拼接字符
            sb.append(str);

        }

        //5.将验证码存入Session对象中
        HttpSession session = request.getSession();
        session.setAttribute("code",sb.toString());

        //6.画干扰线
        graphics.setColor(Color.BLACK);
        for (int i = 0; i < 5; i++) {
            graphics.drawLine(ran.nextInt(width),ran.nextInt(height),ran.nextInt(width),ran.nextInt(height));

        }
        //7.将画布传给前端
        ImageIO.write(image,"jpg",response.getOutputStream());
    }
}

前端设计:

<body>
    <%
    //获取请求中的错误信息
    String msg = (String) request.getAttribute("msg");
    %>

    <%=(msg!=null)?msg:""%>
    <h1 style="text-align: center;">登录界面</h1>
    <div class="con">
        <form action="LoginServlet" method="post">
            <table >
                <tr>
                    <th width="100px">账号:</th>
                    <td width="400px">
                        <input type="text" name="username" id="username"/>
                    </td>
                </tr>
                <tr>
                    <th>密码:</th>
                    <td>
                        <input type="password" name="password" id="password"/>
                    </td>
                </tr>
                <tr>
                    <th>验证码:</th>
                    <td>
                        <input type="text" name="code" id="code"/>
                        <img src="CodeServlet" width="100px" height="40px" οnclick="loadCode()">
                    </td>
                </tr>
                <tr>
                    <th>角色:</th>
                    <td>
                        <select name="role">
                            <option value="student">学生</option>
                            <option value="teacher">教师</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <th colspan="2">
                        <input  type="checkbox" name="checkbox" >记住我<br/>
                    </th>
                </tr>
                <tr>
                    <th colspan="2">
                        <input  type="submit" style="width:90px;height:30px" value="登录"><br/>
                    </th>
                </tr>
            </table>
        </form>
        <script type="text/javascript">
            var img = document.getElementsByTagName("img")[0];
            function loadCode() {
                img.src = "CodeServlet?" + new Date();
            }
            loadCode();
        </script>
    </div>
</body>

在这里插入图片描述

3.2 Cookie+Session 免登陆

1.在前端页面增加checkedbox控件,实现用户能够主动勾选记住我

 <input  type="checkbox" name="checkbox" >记住我<br/>

2.登录按钮点击提交之后,增加对checkedbox的判断(当checkedbox被勾选时,从请求中获取的checkedbox为on,未勾选则获取的值为null。)

if(checkbox!=null) {
    //通过CookieUtil创建cookie添加入响应域中。
    response.addCookie(CookieUtil.createCookie("username", p.getUsername(),60*60*24));
    response.addCookie(CookieUtil.createCookie("name", p.getName(),60*60*24));
    response.addCookie(CookieUtil.createCookie("role", role,60*60*24));
}

3.在Cookie中存储登录过后的界面所需要的相关信息,并设置过期时间为需要免登陆的时间期限。

CookieUtil(创建Cookie的工具类):

public class CookieUtil {
    public static Cookie createCookie(String key,String value,int time){

        Cookie cookie = null;
        try {
            cookie = new Cookie(URLEncoder.encode(key,"UTF-8"),URLEncoder.encode(value,"UTF-8"));
            cookie.setMaxAge(time);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return cookie;
    }
}

注:在存储Cookie时,如果可能出现中文,需要使用URLEncoder.encode()进行编码,在获取 Cookie中的数据时还要记得使用URLDecoder.decode()解码

4.在登录界面之前,优先判断是否含有免登陆所需要的信息,如果有,就通过Session存储,再通过 重定向或转发 实现跳转(跳过登录界面)。

<%
//获取Cookie
Cookie[] cookies = request.getCookies();
if (cookies!=null){
    int num = 0;
    for (Cookie cookie :cookies){
        String key = URLDecoder.decode(cookie.getName(),"UTF-8");
        String value = URLDecoder.decode(cookie.getValue(),"UTF-8");
        if(key.equals("username")){
            num++;
            request.getSession().setAttribute(key,value);
        }
        if(key.equals("role")){
            num++;
            request.getSession().setAttribute(key,value);
        }
        if(key.equals("name")){
            num++;
            request.getSession().setAttribute(key,value);
        }
        if(num == 3){
            response.sendRedirect("page.jsp");
        }
    }
}
%>

5.安全退出,即消除当前账号免登陆的功能,通过将Cookie对应的数据清空实现。

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	req.getSession().setAttribute("username",null);
    req.getSession().setAttribute("name",null);
    req.getSession().setAttribute("role",null);
    //将Cookie对应数据设置为过期。
    resp.addCookie(CookieUtil.createCookie("username","",0));
    resp.addCookie(CookieUtil.createCookie("name","",0));
    resp.addCookie(CookieUtil.createCookie("role","",0));
    //返回到欢迎页面
    resp.sendRedirect("welcome.html");
}

3.3 修改信息功能

1.首先,前端页面点击修改信息之后,应当先跳入一个Servlet中,并且将详情页面的用户标志信息传入这个Servlet中。

 <a href="StuInitModifyServlet?username=<%=username%>" >修改学生信息</a>

2.通过Servlet接受前端传来的请求,在数据库中查询这个学生的所有信息,并将信息转发给一个jsp页面。

@WebServlet("/StuInitModifyServlet")
public class StuInitModifyServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置请求和响应的编码格式
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String username = request.getParameter("username");

        ArrayList<Student> students = DBUtil.commonQuery(Student.class, "select * from student where username=?", username);

        request.setAttribute("student",students.get(0));

        request.getRequestDispatcher("stuinfo.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

3.在jsp页面中获取请求的数据,进行处理和展示。

<%@ page import="com.dream.vo.Student" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="java"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fun"%>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>学生信息页面</h1>

    <form action="StuModifyServlet" method="post">
        <input type="hidden" name="currentPage" value="${currentPage}">
        <input type="hidden" name="role" value="${role}" >
        <input type="hidden" name="username" value="${student.username}"/>
        账号:${student.username}<br/>
        姓名:<input name="name" type="text" value="${student.name}"/><br/>
        年龄:<input name="age" type="number" value="${student.age}"/><br/>
        性别:

        <input name="sex" value="man" type="radio" <java:if test="${student.sex eq 'man'}">checked='checked'</java:if>/>男
        <input name="sex" value="woman" type="radio" <java:if test="${student.sex eq 'woman'}">checked='checked'</java:if>/>女
        <br/>
        爱好:

        <input name="hobby" value="football" type="checkbox" <java:if test="${fun:contains(student.hobby, 'football')}">checked='checked'</java:if>/>足球
        <input name="hobby" value="basketball" type="checkbox" <java:if test="${fun:contains(student.hobby, 'basketball')}">checked='checked'</java:if>/>篮球
        <input name="hobby" value="shop" type="checkbox" <java:if test="${fun:contains(student.hobby, 'shop')}">checked='checked'</java:if>/>购物
        <br/>

        <input type="submit" value="确认修改"/><a href="page.jsp" >取消修改</a>

    </form>
</body>

4.确认修改之后再跳转到另一个Servlet中进行修改处理。

@WebServlet("/StuModifyServlet")
public class StuModifyServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置请求和响应的编码格式
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //获取请求传来的数据
        String username = request.getParameter("username");
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        String age = request.getParameter("age");
        String[] hobbies = request.getParameterValues("hobby");
        try {
            DBUtil.commUpdate("update student set name=?,sex=?,age=?,hobby=? where username=?",name,sex,age, HobbyUtil.getHobby(hobbies),username);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        response.sendRedirect("page.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面我来详细介绍一下JavaWeb登录注册的实现方法。 1. 前端页面设计 使用HTML、CSS、JavaScript等技术实现登录注册页面的设计。登录页面由用户名和密码输入框以及登录按钮组成。注册页面由用户名、密码、确认密码等输入框以及注册按钮组成。需要注意的是,需要进行一些基本的表单验证,比如用户名和密码不能为空、密码需要输入两次并保持一致等。 2. 后端技术选型 JavaWeb应用可以使用Spring、SpringMVC、MyBatis等技术进行开发,其中Spring框架是比较常用的一个。在这里,我们使用Spring框架进行开发。 3. 数据库设计 使用MySQL等数据库进行数据存储。需要设计用户表,存储用户的信息。用户表至少包含用户名和密码两个字段。 4. 注册功能实现 用户在注册页面输入信息后,提交表单。后端接收到请求后,通过表单提交的用户名查询数据库中是否已存在该用户。如果存在,则返回注册失败的信息;如果不存在,则将用户信息存入数据库中,注册成功。 5. 登录功能实现 用户在登录页面输入信息后,提交表单。后端接收到请求后,通过表单提交的用户名和密码查询数据库中是否存在该用户,如果存在且密码正确,则登录成功,否则登录失败。 以上是JavaWeb登录注册的基本流程。需要注意的是,为了提高用户体验和安全性,我们可以增加一些功能,比如用户密码的加密存储、登录状态的保存等。具体的实现过程需要根据实际情况进行设计和开发。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值