前面写了篇博客专门介绍创建基于maven管理的spring项目,本篇将介绍结合使用JSP、Servlet连接前后端,实现可视化。
一、首先了解JSP、Servlet连接前后端工作机制,很多人不了解底层原理也无大碍,会使用便以足够。本地项目JSP页面启动时触发Tomcat服务器,Tomcat与Servlet发送并接收请求,servlet将前端传输来的信息编译成后端可读取的信息,实现与后端的交互,这里Servlet起到了桥梁的作用。
二、了解Serlvet请求源码机制,前面几篇讲过关于实体类,方法声明,实现方法,以下代码就很好理解:
//反序列化时 确保类版本的兼容性
private static final long seriaVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//中文乱码问题:国际标准化
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
//applicationContext.xml
//这个产生一个容器的获取
ApplicationContext ioc = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
//获取用户登录信息
String username = request.getParameter("username");
String password = request.getParameter("password");
// 这里是后台编写的业务层java名称,声明调用,实现交互
LoginService loginService = (LoginService) ioc.getBean("loginService");
//后台编写的java实体类User,doLogin是实现的方法
User user = loginService.dologin(username, password);
request.setAttribute("user", user);
//判断是否从后台取出值
if (user == null) {
//失败
System.out.println("servlet失败!");
}else {
request.getRequestDispatcher("hello.jsp").forward(request, response);
System.out.println("hello.jsp success!");
}
}
二、JSP代码展示
用IDEA创建JSP文件很方便,以下可以观察到JSP与html肉眼可见的区别
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<link rel="stylesheet" type="text/css" href="css/login.css"/>
<html>
<head>
<title>用户登录</title>
</head>
<body class="All-body">
<div id="content" align="center" class="center">
<div class="inner-center">
<div class="inner-msgDiv">
<img src="images/head.png" class="head">
<h1 class="head1">Login to your account</h1>
<h2 class="head2">Login with</h2>
<ul>
<li><a class="fa"></a></li>
<li><a class="tw"></a></li>
<li><a class="g"></a></li>
</ul>
<h3>or</h3>
<form action="loginServlet.do" method="post">
<input type="text" id="username" name="username" placeholder="用户名" />
<input type="password" id="password" name="password" placeholder="密码" />
</form>
<div class="login-check">
<div class="check">
<label>
<input type="checkbox"><span>Remember Me</span>
</label>
</div>
<div class="findPassword">
<span>Forget Password</span>
</div>
</div>
<input type="submit" value="登录" name="submit" id="submit">
<h4>
<span>Don't have an account?</span> <a>Register now!</a>
</h4>
</div>
</div>
</div>
观察以上代码。可以发现有一句<%@ page contentType="text/html;charset=UTF-8" language="java" %>,这是连接java后台的重要语句,在html文件中是没有的,其余部分与html语言相差无几。
三、在写后台业务层文件时会用到一些注解如@Component、@Service、@Autowired等。这些都是用域注入,类似于引用,使各个层之间能够顺利地连接起来。
本文介绍了JSP和Servlet如何连接前后端,揭示了它们在实际项目中的工作原理。通过Servlet作为桥梁,接收和处理前端请求,实现了后端与前端的数据交互。此外,还探讨了Servlet的源码机制,并展示了JSP文件的创建过程,强调了与HTML的区别,以及在JSP中连接Java后台的关键语句。同时提到了在编写后台业务层文件时使用的注解,如@Component、@Service、@Autowired等,这些注解在领域注入中起着关键作用。
3812

被折叠的 条评论
为什么被折叠?



