今天遇到一面试题,登录注册,登录后个人主页可以修改样式。
登录注册这个太简单了,我就不多讲了。我主要讲下样式切换。首先你得明白一个思路,很简单,数据库user记得加个type字段。
这个type字段就是作为样式id。我们到时候根据这个type去拿样式。代码如下:
前台主页面:
main
.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>个人主页</title> <script type="text/javascript" src="/js/jquery-3.2.1.js"></script> <!-- <script type="text/javascript" src="/js/CSSrefresh.js"></script> --> <link rel="stylesheet" type="text/css" href="/css/main.css" id="css" /> </head> <body> <div id="d1"> <div id="d2"> <div id="top"> <h3> 欢迎你,<span id="userName"></span>.个人主页,你可以自定义页面样式。 </h3> </div> <button class="changeBtn" data-type="1">样式1</button> <button class="changeBtn" data-type="2">样式2</button> <button class="changeBtn" data-type="3">样式3</button> </div> </div> </body> <script type="text/javascript" src="/js/main.js"></script> </html>
写三个css样式表文件,命名为main1.css,main2.css,main3.css。内容写个背景颜色就可以了,每个背景颜色不一样。比如:body{background-color:green};
前台主页面js代码:
$(document).ready(function() { $("#userName").html(localStorage.userName)// 登录时设置的web存储 var type = localStorage.type;// 获取主题样式类型,也可以根据用户去数据库查最新的,我这里是登录得到的type。设置在web存储中。 if (type != 0) {// 新用户为默认主题样式 $("#css").attr("href", "/css/main" + type + ".css");// 初始化主题样式 } // 切换主题样式,更新数据库type,同时切换主题样式 $(".changeBtn").click(function() { var type = $(this).attr("data-type"); var userName = localStorage.userName; if (type != localStorage.type) { $("#css").attr("href", "/css/main" + type + ".css"); localStorage.type = type; $.ajax({ url : "ChangeController", data : { userName : userName, type : type }, dataType : "JSON", type : "post", success : function(data) { if (data == 1) { alert('更换主题成功!'); } else { alert('更换主题失败!'); } } }) } }) })
后台控制器代码:
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import JdbcUtils; @WebServlet("/ChangeController") public class ChangeController extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userName= new String(request.getParameter("userName").getBytes("ISO-8859-1"),"utf-8"); String type= new String(request.getParameter("type").getBytes("ISO-8859-1"),"utf-8"); JdbcUtils ju=JdbcUtils.newInstance(); String sql="update user set type=? where username=? "; int row = ju.update(sql, type,userName); response.getWriter().print(row); } }