Web开发学习之路--Springmvc+Hibernate之初体验
本来想继续学习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.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效果如下:
在浏览器中,输入http://localhost:8080/EMLazyChatServer/login/eastmoon,效果如下:
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);
} }
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之初体验的更多相关文章
- Android开发学习之路--百度地图之初体验
手机都有gps和网络,通过gps或者网络可以定位到自己,然后通过百度,腾讯啊之类的地图可以显示我们的地理位置.这里学习下百度地图的使用.首先就是要申请开发者了,这个详细就不多讲了.http://dev ...
- Android开发学习之路--Content Provider之初体验
天气说变就变,马上又变冷了,还好空气不错,阳光也不错,早起上班的车上的人也不多,公司来的同事和昨天一样一样的,可能明天会多一些吧,那就再来学习android吧.学了两个android的组件,这里学习下 ...
- Android开发学习之路--数据持久化之初体验
上班第一天,虽然工作上处于酱油模式,但是学习上依旧不能拉下,接着学习android开发吧,这里学习数据持久化的 知识. 其实数据持久化就是数据可以保存起来,一般我们保存数据都是以文件,或者数据库的形式 ...
- Android开发学习之路--Broadcast Receiver之初体验
学习了Activity组件后,这里再学习下另一个组件Broadcast Receiver组件.这里学习下自定义的Broadcast Receiver.通过按键自己发送广播,然后自己接收广播.新建MyB ...
- Android开发学习之路--网络编程之初体验
一般手机都是需要上网的,一般我们的浏览器就是个webview.这里简单实现下下功能,先编写Android的layout布局: <?xml version="1.0" enco ...
- Web开发学习之路--Eclipse+Tomcat+mysql之初体验
学习了一段时间android,正好要用到android和服务器之间的交互,既然要学习android,那么就涉猎下服务器端的开发了,以前学过php,用thinkphp很快可以搭建起来,但是android ...
- web开发学习之路是否有尽头
Linux/Git/Pip/Npm/Composer Apache/Ngnix Mysql/MongoDb/Redis PHP/Python/NodeJS javascript/jQuery/Expr ...
- Android开发学习之路--网络编程之xml、json
一般网络数据通过http来get,post,那么其中的数据不可能杂乱无章,比如我要post一段数据,肯定是要有一定的格式,协议的.常用的就是xml和json了.在此先要搭建个简单的服务器吧,首先呢下载 ...
- Spring MVC 学习笔记12 —— SpringMVC+Hibernate开发(1)依赖包搭建
Spring MVC 学习笔记12 -- SpringMVC+Hibernate开发(1)依赖包搭建 用Hibernate帮助建立SpringMVC与数据库之间的联系,通过配置DAO层,Service ...
随机推荐
- ●BZOJ 1076 [SCOI2008]奖励关
题链: http://www.lydsy.com/JudgeOnline/problem.php?id=1076题解: 期望dp. (模糊的题意,2333) 题中的:"现在决定不吃的宝物以后 ...
- Codeforces278E Tourists
来自FallDream的博客,未经允许,请勿转载,谢谢. 给定一张无向图,有点权,要支持单点修改点权和询问从一个点到另一个点不重复经过节点的路径上点权最小值的最小值. n,m<=10^5 考虑求 ...
- 关于 Cannot forward after response has been committed的错误
这个错误顾名思义:就是在给客户端做出提交响应完毕后,就不能再次使用request的转发. 代码原先是这样的: package com.bdqn.jsp.study.web.filter; import ...
- c语言的第三次作业
(一)改错题 计算f(x)的值:输入实数x,计算并输出下列分段函数f(x)的值,输出时保留1位小数. 输入输出样例1: Enterr x: 10.0 f(10.0) = 0.1 输入输出样例2: En ...
- C语言程序设计第二次作业—————顺序结构
(一)改错题 1.输出带框文字:在屏幕上输出以下3行信息. ************* Welcome ************* 源程序 include int mian() { printf(&q ...
- php+xdebug远程调试(单人)
目录 服务器上安装 XDebug 及配置 客户端 PHPstorm 配置 浏览器安装插件 服务器上安装 XDebug 及配置 XDebug 安装 略 配置: 打开 php.ini 配置文件: vim ...
- @Transient 理解
transient使用小结 1)一旦变量被transient修饰,变量将不再是对象持久化的一部分,该变量内容在序列化后无法获得访问. 2)transient关键字只能修饰变量,而不能修饰方法和类.注意 ...
- 去掉textarea和input在ios下默认出现的圆角
-webkit-appearance:none;/*清除ios默认圆角*/ border-radius:0;
- 补充Mysql5.7用法
下面简单介绍一下安装: [root@MySQL soft]# tar xf mysql-5.7.10-linux-glibc2.5-x86_64.tar.gz -C /data/service/ [r ...
- 40. Combination Sum II(midum, backtrack, 重要)
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...