3 Servlet、Filter使用

1 使用Servlet获取数据

使用Servlet获取前端的数据,在后端从控制台中打印出前端的数据,前端页面如下图

前端页面程序:需要注意的是form的提交,以及input的不同类型对应的显示不同

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>登录页面</title>
  </head>
  <body>
    <form action="login" method="post">
      <!--Servlet根据name的名字获取相应的值-->
      账号:<input type="text" name="name"> <br>
      密码:<input type="password" name="password"> <br>
      <input type="submit" value="登录">
    </form>
  </body>
</html>

 后端程序:后端需要创建相应的Servlet类

package cn.uestc;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 使用Servlet来获取请求的参数
 */

//@WebServlet(name = "LoginServlet", urlPatterns="/login")
//使用注解的方式来配置Servlet,name=类名,urlPatterns=前段访问的地址

public class LoginServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8"); //为了解决输出中文乱码问题,java内部要设置为utf-8
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        System.out.println("name: " + name);
        System.out.println("password: " + password);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

在上面代码中有一个注解被我注释了,这是Servlet的注解有了这个在web.xml中就可以不用再写了,注解一般在小项目中使用,因为灵活方便,但在大项目中就显得不方便管理了。

因为注解被注释了,所以下面为web.xml中的配置:

<?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">

    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>cn.uestc.LoginServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

</web-app>

 上面即为基础的功能,可以在此基础上进行优化,下面是多种方式的提交:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>登录页面</title>
  </head>
  <body>
  <div align="center"> <!--控制整个表单居中-->
    <!--
            在这里有头像的上传即是文件的上传,所以有必要了解文件上传的特殊要求
            文件上传的条件
            * 表单必须是post提交方式
            * 表单中必须有文件上传项,文件上传项必须有name属性和值
            * 表单的enctype属性必须设置为multipart/form-data
         -->
    <form action="/login" method="post"  enctype="multipart/form-data">
      <table align="center">
        <tr>
          <td class="td1">用户名</td>
          <td><input type="text"  name="username"></td>
        </tr>
        <tr>
          <td>密码</td>
          <td><input type="password"  name="password"></td>
        </tr>
        <tr>
          <td>昵称</td>
          <td><input type="text" name="nickname"></td>
        </tr>
        <tr>
          <td >性别</td>
          <td> <!--单选按钮-->
            <input type="radio" name="sex" value="male"><input type="radio" name="sex" value="female"></td>
        </tr>
        <tr>
          <td >上传头像</td>
          <td><input type="file" id="photo" name="upload"></td>
        </tr>
        <tr>
          <td >兴趣爱好</td> <!--复选框-->
          <td><label>
            <input type="checkbox" name="hobby" value="篮球">篮球
            <input type="checkbox" name="hobby" value="足球">足球
            <input type="checkbox" name="hobby" value="排球">排球
            <input type="checkbox" name="hobby" value="羽毛球">羽毛球
          </label></td>
        </tr>
        <tr>
          <td colspan="2">
              <input type="submit" value="注册">
          </td>
        </tr>
      </table>
    </form>
  </div>
  </body>
</html>

 2 Servlet跳转

Servlet的跳转分两种:服务端跳转与客户端跳转,在客户端跳转时相当于从新提交了申请,浏览器地址会发生改变而服务端则不会,一般常用的也是客户端跳转

 代码部分稍有不同只是跳转的界面不同,当失败时没有失败界面仍是登录界面

public class LoginServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8"); //为了解决输出中文乱码问题,java内部要设置为utf-8
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        System.out.println( "1234");
        System.out.println( name +" " +password);
        if ("admin".equals(name) && "123".equals(password)){
           //进行服务端跳转
            request.getRequestDispatcher("success.jsp").forward(request,response);
        }else {
            //进行客户端跳转
            response.sendRedirect("index.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

 3 Filter拦截优化

 上面实现了简单的登录功能,但有两点问题,(1)由于中文字符的问题,所以如果后续其他Servlet要用到用户名就需要在每个Servlet中进行编码设置,虽然只有一行代码但仍不想设置(2)有安全性问题,如果直接访问success.jsp那么就相当于没有登录就直接访问登录成功后的界面了。基于这两个问题的解决采用的是过滤器的方式。

UserFilter类:

public class UserFilter implements Filter {
    private  String encoding;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //获取配置字符集信息
        this.encoding = filterConfig.getInitParameter("encoding");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //设置请求字符集
        servletRequest.setCharacterEncoding(encoding);
        
        // 涉及到HTTP请求处理,转型处理
        HttpServletRequest hrequest = (HttpServletRequest) servletRequest;
        // 涉及到HTTP请求处理,转型处理
        HttpServletResponse hresponse = (HttpServletResponse) servletResponse;
        // 判断用户是否完成了登录操作,session中是否存储用户名
        String loginUser = (String) hrequest.getSession().getAttribute("name");
        //决定是否放行
        if (loginUser == null) {
            // 未登录,系统强制重定向至登录页面
            hresponse.sendRedirect(hrequest.getContextPath() + "/index.jsp");
            return;
        } else {
            filterChain.doFilter(hrequest, hresponse);
            return;
        }
    }

    @Override
    public void destroy() {

    }
}

对UserFilter类进行配置,在配置时要注意Filter要在最前面

<filter>
        <filter-name>UserFilter</filter-name>
        <filter-class>cn.uestc.UserFilter</filter-class>
        <init-param>
            <!-- 初始化中根据encoding名字寻找配置的字符集-->
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>

    <!-- 配置要拦截的页面 -->
    <filter-mapping>
        <filter-name>UserFilter</filter-name>
        <url-pattern>/success.jsp</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>cn.uestc.LoginServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

0

原文地址:https://www.cnblogs.com/youngao/p/11215021.html