作为一个小萌新最近刚学了spring框架和ajax,也算是摸爬滚打写了一个简单的前台登录界面,接下来展示给大家看吧~
jsp页面代码:
<!DOCTYPE html>
<html lang="en">
<head>
<%@ page contentType="text/html;charset=utf-8" language="java"%>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="/static/jquery/jquery-3.3.1.min.js"></script>
<title>学生信息管理系统登录</title>
<script type="text/javascript">
function resetValue(){
document.getElementById("username").value="";
document.getElementById("password").value="";
}
function login() {
var username=$("#username").val();
var password=$("#password").val();
$.ajax({
type:"post",
url:"/login",
data:{"username":username,"password":password},
async:true,
success:function (data) {
if(data.success==true) {
alert("登陆成功");
location.href = "/index"
}
else{
alert("登录失败");
location.href = "/login"
}
}
})
}
</script>
</head>
<body>
<div align="center" style="padding-top: 50px;">
<table width="1200" height="600" >
<tr height="250">
<td colspan="4"></td>
</tr>
<tr height="10">
<td width="40%"></td>
<td width="10%">账 号 :</td>
<td><input type="text" name="username" id="username"/></td>
<td width="30%"></td>
</tr>
<tr height="10">
<td width="40%"></td>
<td width="10%">密 码:</td>
<td><input type="password" name="password" id="password"/></td>
<td width="30%"></td>
</tr>
<tr height="10">
<td width="40%"></td>
<td width="10%"> <input type="submit" value="登录" onclick="login()"></td>
<td><input type="button" value="重置" onclick="resetValue()"/></td>
<td width="30%"></td>
</tr>
<tr >
<td></td>
</tr>
</table>
</div>
</body>
</html>
哈~这是一个再简单不过的登录界面了,除了几个字另外可以说是什么都没有了
接下来是控制器层
package com.ceit.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.ceit.service.LoginService;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import com.ceit.until.JsonMapper;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Map;
@Controller
public class LoginController {
@Autowired
private LoginService loginService;
JsonMapper nonNullBinder = JsonMapper.nonEmptyMapper();
@RequestMapping(value = "/",method = RequestMethod.GET)
public String login(){
return "login";
}
@RequestMapping(value = "/login",method = RequestMethod.GET)
public String login2(){
return "login";
}
@ResponseBody
@RequestMapping(value = "login",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
public String login(String username, String password, HttpSession session) throws UnsupportedEncodingException, NoSuchAlgorithmException {
Map map=loginService.judge(username,password);
session.setAttribute("isLogin",1);
return nonNullBinder.toJson(map);
}
}
其中@RequestMapping中的value值会与前台的ajax对应
实体层:
package com.ceit.model;
public class User {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
以上这个类在我写的这个登录界面中没有用到,如果扩展功能就可以利用
Dao层:
package com.ceit.dao;
import java.util.HashMap;
public interface UserMapper {
public String judge_Password(String username);
public int selectUserCount(String username);
public HashMap selectRole_nameByAcc(String username);
}
Service层:
package com.ceit.service;
import com.ceit.dao.UserMapper;
import com.ceit.until.EncoderMD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
@Service
public class LoginService {
@Autowired
private UserMapper userMapper;
public Map judge(String username, String password) throws UnsupportedEncodingException, NoSuchAlgorithmException {
Map map=new HashMap();
String password_1=userMapper.judge_Password(username);
int count=userMapper.selectUserCount(username);
if(password.equals(password_1)&&count==1)
{
map.put("success",true);
}else {
map.put("success",false);
}
return map;
}
}
Jsonmapper:
package com.ceit.until;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.text.SimpleDateFormat;
/**
* ASUS
* 简单封装Jackson,实现JSON String<->Java Object的Mapper.
*
* 封装不同的输出风格, 使用不同的builder函数创建实例.
*/
public class JsonMapper {
private static Logger logger = LoggerFactory.getLogger(JsonMapper.class);
private ObjectMapper mapper;
public JsonMapper() {
this(null);
}
public JsonMapper(Include include) {
mapper = new ObjectMapper();
//设置日期格式当使用jackson在处理时间时,默认是将时间输出为timestamps格式
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
mapper.setDateFormat(fmt);
//设置输出时包含属性的风格
if (include != null) {
mapper.setSerializationInclusion(include);
}
//设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
//Include.Include.ALWAYS 默认
//Include.NON_DEFAULT 属性为默认值不序列化
//Include.NON_EMPTY 属性为 空(“”) 或者为 NULL 都不序列化
//Include.NON_NULL 属性为NULL 不序列化
/**
* 属性为 空(“”) 或者为 NULL 都不序列化
*/
public static JsonMapper nonEmptyMapper() {
return new JsonMapper(Include.NON_EMPTY);
}
/**
* 属性为默认值不序列化
*/
public static JsonMapper nonDefaultMapper() {
return new JsonMapper(Include.NON_DEFAULT);
}
/**
* 属性为NULL不序列化
*/
public static JsonMapper nonNullMapper() {
return new JsonMapper(Include.NON_NULL);
}
/**
* Object可以是POJO,也可以是Collection或数组。
* 如果对象为Null, 返回"null".
* 如果集合为空集合, 返回"[]".
*/
public String toJson(Object object) {
try {
return mapper.writeValueAsString(object);
} catch (IOException e) {
logger.warn("write to json string error:" + object, e);
return null;
}
}
/**
* 反序列化POJO或简单Collection如List.
*
* 如果JSON字符串为Null或"null"字符串, 返回Null.
* 如果JSON字符串为"[]", 返回空集合.
*
* 如需反序列化复杂Collection如List, 请使用fromJson(String,JavaType)
*
* @see #fromJson(String, JavaType)
*/
public <T> T fromJson(String jsonString, Class<T> clazz) {
if (StringUtils.isEmpty(jsonString)) {
return null;
}
try {
return mapper.readValue(jsonString, clazz);
} catch (IOException e) {
logger.warn("parse json string error:" + jsonString, e);
return null;
}
}
/**
* 反序列化复杂Collection如List, 先使用函數createCollectionType构造类型,然后调用本函数.
*
* @see #createCollectionType(Class, Class...)
*/
public <T> T fromJson(String jsonString, JavaType javaType) {
if (StringUtils.isEmpty(jsonString)) {
return null;
}
try {
return (T) mapper.readValue(jsonString, javaType);
} catch (IOException e) {
logger.warn("parse json string error:" + jsonString, e);
return null;
}
}
/**
* 構造泛型的Collection Type如:
* ArrayList, 则调用constructCollectionType(ArrayList.class,MyBean.class)
* HashMap, 则调用(HashMap.class,String.class, MyBean.class)
*/
public JavaType createCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
}
/**
* 當JSON裡只含有Bean的部分屬性時,更新一個已存在Bean,只覆蓋該部分的屬性.
*/
public <T> T update(String jsonString, T object) {
try {
return (T) mapper.readerForUpdating(object).readValue(jsonString);
} catch (JsonProcessingException e) {
logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
} catch (IOException e) {
logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
}
return null;
}
/**
* 輸出JSONP格式數據.
*/
public String toJsonP(String functionName, Object object) {
return toJson(new JSONPObject(functionName, object));
}
}
之后是和Usermapper对应的Usermapper.xml
<mapper namespace="com.ceit.dao.UserMapper">
<select id="judge_Password" parameterType="java.lang.String" resultType="java.lang.String">
SELECT password FROM users WHERE username=#{username}
select>
<select id="selectUserCount" resultType="int" parameterType="java.lang.String">
SELECT count(*) FROM users WHERE username=#{username}
select>
mapper>
刚开始写代码的时候很容易忘记在这里添加数据库查询语句导致各种报错,点击登录按钮之后浏览器控制台报错500。
这是数据库表单user的结构,数据库名称在我之前的代码里都有,这样就完成啦!
觉得什么问题的小伙伴可以提出来喔。