0%

Java Web项目实战(一)

学了很久Java了,一直做的都是零碎的工作,还从来没有完完整整地撸出一个像样的项目来,最近为了准备实习复习了一遍Java基础,就顺便一步步地搭一个网站出来,大概想到什么就写什么,最后做出来个什么东西也不好说,兴趣使然。这里我也不会很详细地记录,大概就是写一些比较坑的地方,避免以后再犯。

Step 1 新建工程

myeclipse – new – web project – finish
右键工程 – 选择properties – 选择utf8编码(很奇怪我选定了之后新建的jsp文件里头部还是ISO-8859-1╮(╯_╰)╭)
后面需要用到jQuery所以把jquery.min.js文件也先放到webroot下

Step 2 index.jsp

index.jsp即所谓的网站首页,进入网站最先访问到的就是这个页面,可以先用HTML编出一个静态页面,确定了大致效果之后再搬到jsp里面,css样式文件可以写在webroot下单独一个style.css文件里再引入到HTML中,对于header和footer这类公共页面也是如此。

记得在每个jsp页面加入

1
2
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

css的引用:

1
<link rel="stylesheet" type="text/css" href="style.css" />

公共页面引用:

1
<%@include file="common/header.jsp" %>

注:我的header文件放在webroot下的common文件夹里

我的header.jsp:

1
2
3
4
5
6
7
8
9
10
11
12
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<nav class="top">
<a href="#nowhere">首页</a>
<span>喵 施工中</span>
<a href="login.jsp">请登录</a>//跳转到登陆页
<a href="#nowhere">免费注册</a>
<span class="pull-right">
<a href="forebought">捐助</a>
<a href="forecart">更多</a>
</span>
</nav>

Step 3 login.jsp

登陆模块采用MVC架构,即分为model view controller三层来写

前端(view)

html部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<body>
<%@include file="common/header.jsp"%>
<div class='inputBox mt50 ml32'>
<input type="text" id="username" autofocus="autofocus" autocomplete="off" maxlength="60" placeholder="请输入账号/邮箱/手机号">
<i style='font-size:20px;margin-left:-32px;opacity:0.8;' class='iconfont icon-yonghuming'></i>
</div>
<div class='inputBox mt50 ml32'>
<input type="password" id="password" autofocus="autofocus" autocomplete="off" maxlength="60" placeholder="请输入密码">
<i style='font-size:20px;margin-left:-32px;opacity:0.8;' class='iconfont icon-mima'></i>
</div>

<div class='mt50 ml32'>
<button class="login_btn" onclick="login()">登陆</button>
</div></body>

采用jQuery的ajax方法提交验证账号密码

ajax技术在实际开发中非常常见

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script>
function login(){
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
type:"post",//请求方式
url:"./controller/loginController.jsp",//请求地址
data:{"username":username,"password":password},//传递给controller的json数据
error:function(){
alert("登陆出错!");
},
success:function(data){ //返回成功执行回调函数。

}
});};</script>

后台(controller)

loginController.jsp

1
2
3
4
5
6
7
8
9
10
11
12
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
//设置请求的编码
//request.setCharacterEncoding("UTF-8");
//获取客户端传递过来参数
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username);
System.out.println(password);
//如果用户名和密码不为空

%>

先看看console里有没有输出,有就说明前后台成功交互了