Web开发学习之路--Springmvc+Hibernate之初体验

时间:2023-12-11 17:05:03

本来想继续学习android的,可是用到了android和服务器交互,需要实现个login的功能,苦于没有这么个环境,那就只能自己来搭建了。既然已经基本上可以玩web了,那么接下来使用web开源的框架了,spring-mvc相信很多人都听说过,我也是听说了,所以想玩一下,首先下载相关的一些包啊之类的,这个是最新的http://repo.spring.io/libs-release-local/org/springframework/spring/4.2.3.RELEASE/https://github.com/spring-projects/spring-framework/releases,这里用spring
mvc的4.2。

先新建一个工程吧,具体怎么建就参考上一篇文章了。因为后面需要用到login的功能,所以就直接使用了sping mvc的框架,新建工程名为EMLazyChatServer,把下载好后的spring mvc的jar包拷贝到lib目录下,因为这里还依赖两个库,害我整死了,从tomcat7搞到tomcat8,又把eclipse重新更新到java ee的,心好累,不过终于可以搞出来了,也不枉纠结了这么久。好了,这里我主要用到的库如下:

Web开发学习之路--Springmvc+Hibernate之初体验

接着配置web.xml,如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID"
version="2.5"> <filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-context.xml</param-value>
</context-param> <servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> </web-app>

1、这里先通过encodingFilter把格式转化为utf-8的格式,防止乱码;

2、接着注册listener,监听spring上下文容器;

3、通过contextConfigLocation,加载spring的xml配置文件到spring上下文容器中;

4、配置

spring mvc的Dispatcherservlet,初始化参数加载spring-mvc.xml到spring上下文容器中,通过mapping拦截所有的url;

接着实现spring-context.xml文件,这个文件暂时很简单,主要是一些声明之类:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
</beans>

然后是spring-mvc.xml文件了:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd"> <!-- 启动包扫描功能,以便注册带有@Controller、@Service、@repository、@Component等注解的类成为spring的bean -->
<context:component-scan base-package="com.jared.emlazychat" /> <mvc:annotation-driven></mvc:annotation-driven> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp" />
</bean>
</beans>

1、这里先通过component-scan扫描指定的包,这里我的包是com.jared.emlazychat;

2、配置spring mvc的视图渲染器,其前缀为/WEB-INF/view,后缀为.jsp。

基本上配置好了,这里就开始为com.jared.emlazychat包创建一个Hello类,代码如下:

package com.jared.emlazychat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView; @Controller
public class Hello {
public Hello() {}
@RequestMapping(value = "/login/{user}", method = RequestMethod.GET)
public ModelAndView myMethod(HttpServletRequest request,HttpServletResponse response,
@PathVariable("user") String user, ModelMap modelMap) throws Exception {
modelMap.put("loginUser", user);
return new ModelAndView("/login/hello", modelMap);
} @RequestMapping(value = "/welcome", method = RequestMethod.GET)
public String registPost() {
return "/welcome";
} @RequestMapping("index")
public ModelAndView index(){
//创建模型跟视图,用于渲染页面。并且指定要返回的页面为home页面
ModelAndView mav = new ModelAndView("welcome");
return mav;
}
}

这个通过@Controller表示是Controller,然后通过RequestMapping来表示,其中可以指定value和method方法,通过ModelAndView来返回。接着在WEB-INF下创建view目录,并且在里面生产代码welcome.jsp,代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
welcome spring mvc
</body>
</html>

这里就输出一句简答的话,接着在view目录下创建login目录,并且创建hello.jsp,代码如下:

<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
你好:<%=request.getAttribute("loginUser") %>,现在时间是<%= new Date() %>
</body>
</html>

接着我们来运行测试下效果:

在浏览器中,输入http://localhost:8080/EMLazyChatServer/welcome,或者http://localhost:8080/EMLazyChatServer/index效果如下:

Web开发学习之路--Springmvc+Hibernate之初体验 
      Web开发学习之路--Springmvc+Hibernate之初体验

在浏览器中,输入http://localhost:8080/EMLazyChatServer/login/eastmoon,效果如下:

    Web开发学习之路--Springmvc+Hibernate之初体验
    好了,基本上的spring mvc就搭建好了。接下去简单地实现post的功能,并可以和手机交互了。先简单地实现下post的功能吧。
    这里用了json数据返回,因为后面会用到数据库,所以hibernate和gson。看下代码中用到的jar包吧:
Web开发学习之路--Springmvc+Hibernate之初体验
    接着我们新建LoginControl,代码如下:
package com.jared.emlazychat;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID; import com.jared.emlazychat.User;
import com.jared.emlazychat.UserService;
import com.jared.emlazychat.ClientAccount; import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
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.ResponseBody; import com.google.gson.Gson; @Controller
public class LoginControl {
private final static int LOGIN_PASSWORD_ERROR = 100;
private final static int LOGIN_ACCOUNT_MISS = 101; private final static int REGISTER_ACCOUNT_EXIST = 150; UserService userService; @RequestMapping(value = "/login", produces = "text/html;charset=UTF-8")
@ResponseBody
public String login(String account, String password) {
Map<String, Object> map = new HashMap<String, Object>();
System.out.println("login:"+account+":"+password);
//if (account == null || password == null) { if (account == null || password == null
|| (!account.equals("test")) || (!password.equals("123"))) {
map.put("flag", false);
map.put("errorCode", LOGIN_ACCOUNT_MISS);
map.put("errorString", "用户不存在");
} else {
User user = new User();
user.setAccount(account);
user.setArea("hangzhou");
user.setName("eastmoon");
user.setSex(0);
user.setToken(UUID.randomUUID().toString());
map.put("flag", true);
map.put("data", ClientAccount.toAccount(user));
/*
User user = userService.findUserByAccount(account);
if (user == null) {
map.put("flag", false);
map.put("errorCode", LOGIN_ACCOUNT_MISS);
map.put("errorString", "用户不存在");
} else {
if (password.equals(user.getPassword())) {
user.setToken(UUID.randomUUID().toString());
userService.updateToken(user); user = userService.findUserByAccount(account); map.put("flag", true);
map.put("data", ClientAccount.toAccount(user));
} else {
map.put("flag", false);
map.put("errorCode", LOGIN_PASSWORD_ERROR);
map.put("errorString", "用户密码错误");
}
}
*/
}
return new Gson().toJson(map);
} }

    这里和数据库交互的类还没有完全完成,后续再慢慢完成,这里主要是客户端通过post到login,然后返回指定的数据给app。这里用到了其他的几个类,User类:
package com.jared.emlazychat;

import java.sql.Timestamp;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity
@Table(name = "t_user")
public class User { @Id
@GenericGenerator( name = "generator",
strategy = "uuid")
@GeneratedValue(generator = "generator")
@Column
private String id; @Column
private String account; @Column
private String name; @Column
private String phone; @Column
private String icon; @Column
private String password; @Column(nullable = false,
columnDefinition = "int default 0")
private int state; // 0 : 离线 1: 在线 @Column(nullable = true)
private Long session; // session 编号 @Column
private Timestamp createTime; @Column
private Timestamp lastLoginTime; @Column
private String sign; //个性签名 @Column
private String area; //地区 @Column
private Integer sex; //性别:0:未设置 1:女 2:男 3:其他 @Column
private String qrPath; //二维码存储路径 @Column
private String token; public String getToken() {
return token;
} public void setToken(String token) {
this.token = token;
} public String getSign() {
return sign;
} public void setSign(String sign) {
this.sign = sign;
} public String getArea() {
return area;
} public void setArea(String area) {
this.area = area;
} public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getAccount() {
return account;
} public void setAccount(String account) {
this.account = account;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getPhone() {
return phone;
} public void setPhone(String phone) {
this.phone = phone;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public int getState() {
return state;
} public void setState(int state) {
this.state = state;
} public Long getSession() {
return session;
} public void setSession(Long session) {
this.session = session;
} public Timestamp getCreateTime() {
return createTime;
} public void setCreateTime(Timestamp createTime) {
this.createTime = createTime;
} public Timestamp getLastLoginTime() {
return lastLoginTime;
} public void setLastLoginTime(Timestamp lastLoginTime) {
this.lastLoginTime = lastLoginTime;
} public Integer getSex() {
return sex;
} public void setSex(Integer sex) {
this.sex = sex;
} public String getQrPath() {
return qrPath;
} public void setQrPath(String qrPath) {
this.qrPath = qrPath;
} public String getIcon() {
return icon;
} public void setIcon(String icon) {
this.icon = icon;
} @Override
public String toString() {
return "User [id=" + id + ", account=" + account + ", name=" + name + ", phone=" + phone
+ ", icon=" + icon + ", password=" + password + ", state=" + state + ", session="
+ session + ", createTime=" + createTime + ", lastLoginTime=" + lastLoginTime
+ ", sign=" + sign + ", area=" + area + ", sex=" + sex + ", qrPath=" + qrPath
+ ", token=" + token + "]";
} }

UserServer接口:

package com.jared.emlazychat;

public interface UserService {

	boolean isExist(String account);

	User addUser(String account, String password);

	User findUserByAccount(String account);

	void updateToken(User user);
}

ClientAccount类:

package com.jared.emlazychat;

import com.jared.emlazychat.User;

public class ClientAccount {

	private String	account;	// 账号
private String name; // 用户名
private Integer sex; // 性别
private String icon; // 用户图像
private String sign; // 用户个性签名
private String area; // 用户所在区域
private String token; // 用户与服务器交互的唯一标 public String getAccount() {
return account;
} public void setAccount(String account) {
this.account = account;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getIcon() {
return icon;
} public void setIcon(String icon) {
this.icon = icon;
} public String getSign() {
return sign;
} public void setSign(String sign) {
this.sign = sign;
} public String getArea() {
return area;
} public void setArea(String area) {
this.area = area;
} public String getToken() {
return token;
} public void setToken(String token) {
this.token = token;
} public Integer getSex() {
return sex;
} public void setSex(Integer sex) {
this.sex = sex;
} public static ClientAccount toAccount(User user) {
ClientAccount account = new ClientAccount();
account.account = user.getAccount();
account.area = user.getArea();
account.icon = user.getIcon();
account.name = user.getName();
account.sex = user.getSex();
account.sign = user.getSign();
account.token = user.getToken();
return account;
} }

基本上OK了,接着测试了,首先通过简单的网页来访问吧,输入:http://127.0.0.1:8080/EMLazyChatServer/login

    返回效果如下:
    Web开发学习之路--Springmvc+Hibernate之初体验
    利用手机app也可以得到联调了,具体可以参考github的项目:
    接下去就是把和数据库交互的搞搞,androd app端就可以和服务器交互,之后的聊天socket也可以搞起来了。