login登陆页面如何进行服务端校验?

1.在servlet中获取数据之后马上进行服务端校验,如果校验成功那么执行后面的代码;
如果校验不成功,那么响应给客户错误信息并返回请求页面。

2.具体如何做呢?

定义校验表单数据的方法,返回一个StringBuffer,在servlet中进行响应

private StringBuffer validateLoginForm(String username,
			String password) {
		StringBuffer errors_message=new StringBuffer("");
		if(username==null||"".equals(username))//不要帮用户空格,他输入是什么就是什么
		{
			errors_message.append("用户名不能为空");
		}
		if(password==null||"".equals(password))
		{
			errors_message.append("密码不能为空");
		}
			return errors_message;//返回存有校验结果的字符串
	}

login登录代码

public void login(HttpServletRequest request,HttpServletResponse response)
	{
		//获取表单数据
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		
		/*
		 * 2.合法性校验:如果校验通过那么继续执行后面的代码,如果校验不通过,那么程序结束返回用户出错信息
		 */
		StringBuffer sb=validateLoginForm(request, response, username, password);
		if(sb.toString().length()>0)
		{
			//如果校验不通过,那么在这里对请求响应
			request.setAttribute("message", sb.toString());
			try {
				request.getRequestDispatcher("login.jsp").forward(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			} 
		}else
		{
		
		//3.调用service的login方法
		UserServiceIfac userService=ServiceFactory.getUserServiceInstance();
		User user=userService.login(username, password);
		
		//4.根据user是否为空进行登录结果判断
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter pw=null;
		try {
			pw=response.getWriter();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//根据登录业务方法的返回值是否为空,作出如下响应
		if(user==null)
		{
			//告诉用户登录失败,并返回登录页面
			/*
			 * 第一种做法
			 * 如果开发严格要求,后台代码中不能出现前端脚本,那么这个做法不行
			 */
			//pw.println("<script>alert('登录失败');location.href='login.jsp';</script>");
			
			/*
			//第二种做法:这种做法是跳转,所以url不会变,如果用户刷新页面的表单会再提交一次
			request.setAttribute("message", "用户名或密码错误");//朝接收端发送信息
			
			try {
				request.getRequestDispatcher("login.jsp").forward(request, response);//forward方法的参数不能为null
			} catch (Exception e) {
				e.printStackTrace();
			}
			*/
			
			/*
			 * 第三种做法:重定向,没有告诉用户出什么事了,但url变了
			 */
			try {
				response.sendRedirect(request.getContextPath()+"/login.jsp");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else
		{
			//===============================================================
			/*
			 * 需求:我们希望登录成功之后不管在当前应用哪个页面都能访问到用户的信息
			 * 实现技术:HttpSession
			 */
			//1、获取session对象
			HttpSession session=request.getSession();
			//2、把用户信息放入session,那么不管在当前应用的哪个页面都能访问到用户信息
			session.setAttribute("user", user);
			
			//告诉用户登录成功,并重定向都首页面
			//需要根据用户的身份定位页面
			if("1".equals(user.getRule()))
			{	//	管理员
				pw.println("<script>alert('登录成功');location.href='admin/index.jsp';</script>");
			}else if("2".equals(user.getRule()))
			{	//	普通用户
				pw.println("<script>alert('登录成功');location.href='user/index.jsp';</script>");
			}
				
		}
		}

=======================
login.jsp部分代码
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以帮你写一个基于 Spring Boot 和 Netty 实现的 TCP 通信协议的 Demo。下面是代码实现: 1. 客户端代码: ```java @Component public class TcpClient { private static final Logger LOGGER = LoggerFactory.getLogger(TcpClient.class); private static final String HOST = "localhost"; private static final int PORT = 8888; private Channel channel; @PostConstruct public void start() throws InterruptedException { EventLoopGroup group = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new TcpClientHandler()); } }); ChannelFuture future = bootstrap.connect(HOST, PORT).sync(); channel = future.channel(); LOGGER.info("TcpClient started and connected to {}:{}", HOST, PORT); } public void send(String message) { channel.writeAndFlush(Unpooled.copiedBuffer(message.getBytes())); } @PreDestroy public void stop() throws InterruptedException { channel.closeFuture().sync(); LOGGER.info("TcpClient stopped"); } } ``` 2. 客户端处理器代码: ```java public class TcpClientHandler extends SimpleChannelInboundHandler<ByteBuf> { private static final Logger LOGGER = LoggerFactory.getLogger(TcpClientHandler.class); @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { String username = "username"; String password = "password"; String message = String.format("%s:%s", username, password); ctx.writeAndFlush(Unpooled.copiedBuffer(message.getBytes())); } @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { String response = msg.toString(CharsetUtil.UTF_8); LOGGER.info("Received response from TcpServer: {}", response); if (response.startsWith("Login success")) { String data = "Hello, TcpServer!"; LOGGER.info("Sending data to TcpServer: {}", data); ctx.writeAndFlush(Unpooled.copiedBuffer(data.getBytes())); } else { LOGGER.warn("Invalid response from TcpServer: {}", response); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { LOGGER.error("Exception caught in TcpClient", cause); ctx.close(); } } ``` 3. 服务端代码: ```java @Component public class TcpServer { private static final Logger LOGGER = LoggerFactory.getLogger(TcpServer.class); private static final int PORT = 8888; @PostConstruct public void start() throws InterruptedException { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap() .group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new TcpServerHandler()); } }); ChannelFuture future = bootstrap.bind(PORT).sync(); LOGGER.info("TcpServer started and listening on port {}", PORT); future.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } } ``` 4. 服务端处理器代码: ```java public class TcpServerHandler extends SimpleChannelInboundHandler<ByteBuf> { private static final Logger LOGGER = LoggerFactory.getLogger(TcpServerHandler.class); private static final String USERNAME = "username"; private static final String PASSWORD = "password"; private String clientIp; @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { clientIp = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress(); LOGGER.info("Received new connection from {}", clientIp); } @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { String request = msg.toString(CharsetUtil.UTF_8); LOGGER.info("Received request from {}: {}", clientIp, request); String[] parts = request.split(":"); if (parts.length != 2) { LOGGER.warn("Invalid request from {}: {}", clientIp, request); ctx.writeAndFlush(Unpooled.copiedBuffer("Invalid request".getBytes())); return; } String username = parts[0]; String password = parts[1]; if (!USERNAME.equals(username) || !PASSWORD.equals(password)) { LOGGER.warn("Invalid username or password from {}: {}", clientIp, request); ctx.writeAndFlush(Unpooled.copiedBuffer("Invalid username or password".getBytes())); return; } LOGGER.info("Login success for {}", clientIp); ctx.writeAndFlush(Unpooled.copiedBuffer("Login success".getBytes())); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { LOGGER.error("Exception caught in TcpServer", cause); ctx.close(); } } ``` 以上就是一个基于 Spring Boot 和 Netty 实现的 TCP 通信协议的 Demo,它可以实现客户端使用服务端账号进行登录,客户端收到客户端的登录信息以后进行校验校验成功记录客户端的 IP 地址并返回校验成功信息,客户端收到返回的成功的信息后进行发送数据,服务端收到信息后与记录的 IP 进行校验,成功就接收信息的功能。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值