服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Spring MVC登录注册以及转换json数据

Spring MVC登录注册以及转换json数据

2020-09-07 09:09雨落秋垣 Java教程

本文主要介绍了Spring MVC登录注册以及转换json数据的相关知识。具有很好的参考价值。下面跟着小编一起来看下吧

项目结构;

Spring MVC登录注册以及转换json数据

代码如下:

BookController

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.mstf.controller;
 
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.ObjectMapper;
import com.mstf.domain.Book;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/json")
public class BookController {
 private static final Log logger = LogFactory.getLog(BookController.class);
 // @RequestMapping 根据 json 数据,转换成对应的 Object
 @RequestMapping(value="/testRequestBody")
 public void setJson(@RequestBody Book book,HttpServletResponse response) throws Exception {
  // ObjectMapper 类是 Jackson 库的主要类。他提供一些功能将 Java 对象转换成对应的 JSON
  ObjectMapper mapper = new ObjectMapper();
  // 将 Book 对象转换成 json 输出
  logger.info(mapper.writeValueAsString(book));
  book.setAuthor("汪政");
  response.setContentType("text/html;charset=UTF-8");
  // 将 Book 对象转换成 json 写到客户端
  response.getWriter().println(mapper.writeValueAsString(book));
 }
}

UserController

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.mstf.controller;
 
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.mstf.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
 
// Controller 注解用于指示该类是一个控制器,可以同时处理多个请求动作
@Controller
// RequestMapping 可以用来注释一个控制器类,此时,所有方法都将映射为相对于类级别的请求,
// 表示该控制器处理所有的请求都被映射到 value属性所指示的路径下
@RequestMapping(value="/user")
public class UserController {
 // 静态 List<User> 集合,此处代替数据库用来保存注册的用户信息
 private static List<User> userList;
 // UserController 类的构造器,初始化 List<User> 集合
 public UserController() {
  super();
  userList = new ArrayList<User>();
 }
 // 静态的日志类 LogFactory
 private static final Log logger = LogFactory.getLog(UserController.class);
 // 该方法映射的请求为 http://localhost:8080/context/user/register ,该方法支持GET请求
 @RequestMapping(value="/register",method=RequestMethod.GET)
 public String registerForm() {
  logger.info("register GET方法被调用...");
  // 跳转到注册页面
  return "register";
 }
 // 该方法映射的请求支持 POST 请求
 @RequestMapping(value="/register",method=RequestMethod.POST)
 // 将请求中的 loginname 参数的值赋给 loginname 变量, password 和 username 同样处理
 public String register(
   @RequestParam("loginName") String loginName,
   @RequestParam("passWord") String passWord,
   @RequestParam("userName") String userName) {
  logger.info("register POST方法被调用...");
  // 创建 User 对象
  User user = new User();
  user.setLoginName(loginName);
  user.setPassWord(passWord);
  user.setUserName(userName);
  // 模拟数据库存储 User 信息
   userList.add(user);
  // 跳转到登录页面
  return "login";
 }
 // 该方法映射的请求为 http://localhost:8080/RequestMappingTest/user/login
 @RequestMapping("/login")
 public String login(
   // 将请求中的 loginName 参数的值赋给 loginName 变量, passWord 同样处理
   @RequestParam("loginName") String loginName,
   @RequestParam("passWord") String passWord,
   Model model) {
  logger.info("登录名:"+loginName + " 密码:" + passWord);
  // 到集合中查找用户是否存在,此处用来模拟数据库验证
  for(User user : userList){
   if(user.getLoginName().equals(loginName)
     && user.getPassWord().equals(passWord)){
    model.addAttribute("user",user);
    return "welcome";
   }
  }
  return "login";
 }
}

Book

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.mstf.domain;
import java.io.Serializable;
public class Book implements Serializable {
 private static final long serialVersionUID = 1L;
 private int id;
 private String name;
 private String author;
 public Book() {
 }
 public Book(int id, String name, String author) {
  super();
  this.id = id;
  this.name = name;
  this.author = author;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getAuthor() {
  return author;
 }
 public void setAuthor(String author) {
  this.author = author;
 }
 @Override
 public String toString() {
  return "Book [id=" + id + ", name=" + name + ", author=" + author + "]";
 }
}

User

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.mstf.domain;
import java.io.Serializable;
// 域对象,实现序列化接口
public class User implements Serializable {
 // 序列化
 private static final long serialVersionUID = 1L;
 // 私有字段
 private String loginName;
 private String userName;
 private String passWord;
 // 公共构造器
 public User() {
  super();
 }
 // get/set 方法
 public String getLoginName() {
  return loginName;
 }
 public void setLoginName(String loginName) {
  this.loginName = loginName;
 }
 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;
 }
}

springmvc-config.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?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:mvc="http://www.springframework.org/schema/mvc"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="
  http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
  http://www.springframework.org/schema/mvc
  http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-4.2.xsd">
 
 <!-- spring可以自动去扫描base-pack下面的包或者子包下面的java文件,
  如果扫描到有Spring的相关注解的类,则把这些类注册为Spring的bean -->
 <context:component-scan base-package="com.mstf.controller"/>
 
 <!-- 设置配置方案 -->
 <mvc:annotation-driven/>
 <!-- 使用默认的 servlet 来响应静态文件 -->
 <mvc:default-servlet-handler/>
 
 <!-- 视图解析器 -->
  <bean id="viewResolver"
   class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <!-- 前缀 -->
  <property name="prefix">
   <value>/WEB-INF/jsp/</value>
  </property>
  <!-- 后缀 -->
  <property name="suffix">
   <value>.jsp</value>
  </property>
 </bean>
</beans>

login.jsp

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<%@ 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>登录</title>
</head>
<body>
 <h3>登录</h3>
 <br>
 <form action="login" method="post">
  <table>
   <tr>
    <td>
     <label>
      登录名:
     </label>
    </td>
    <td>
     <input type="text" id="loginName" name="loginName">
    </td>
   </tr>
   <tr>
    <td>
     <label>
      密 码:
     </label>
    </td>
    <td>
     <input type="password" id="passWord" name="passWord">
    </td>
   </tr>
   <tr>
    <td>
     <input id="submit" type="submit" value="登录">
    </td>
   </tr>
  </table>
 </form>
</body>
</html>

register.jsp

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<%@ 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>注册</title>
</head>
<body>
 <h3>注册页面</h3>
 <br>
 <form action="register" method="post">
  <table>
   <tr>
    <td>
     <label>
      登录名:
     </label>
    </td>
    <td>
     <input type="text" id="loginName" name="loginName">
    </td>
   </tr>
   <tr>
    <td>
     <label>
      密 码:
     </label>
    </td>
    <td>
     <input type="password" id="passWord" name="passWord">
    </td>
   </tr>
   <tr>
    <td>
     <label>
      姓 名:
     </label>
    </td>
    <td>
     <input type="text" id="userName" name="userName">
    </td>
   </tr>
   <tr>
    <td>
     <input id="submit" type="submit" value="注册">
    </td>
   </tr>
  </table>
 </form>
</body>
</html>

welcome.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"%>
<!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>欢迎登录</title>
</head>
<body>
 <h3>欢迎[${requestScope.user.userName }]登录</h3>
</body>
</html>

web.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 version="3.0">
 <!-- 定义 Spring MVC 的前端控制器 -->
 <servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>
   org.springframework.web.servlet.DispatcherServlet
  </servlet-class>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>
    /WEB-INF/config/springmvc-config.xml
   </param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <!-- 让 Spring MVC 的前端控制器拦截所有请求 -->
 <servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>
 <!-- 乱码过滤器 -->
 <filter>
  <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
</web-app>

index.jsp

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试接收JSON格式的数据</title>
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/json2.js"></script>
<script type="text/javascript">
 $(document).ready(function(){
  testRequestBody();
 });
 function testRequestBody(){
  $.ajax("${pageContext.request.contextPath}/json/testRequestBody",// 发送请求的 URL 字符串。
    {
    dataType : "json", // 预期服务器返回的数据类型。
    type : "post", // 请求方式 POST 或 GET
    contentType:"application/json", // 发送信息至服务器时的内容编码类型
    // 发送到服务器的数据。
    data:JSON.stringify({id : 1, name : "你们都是笨蛋"}),
    async: true , // 默认设置下,所有请求均为异步请求。如果设置为 false ,则发送同步请求
    // 请求成功后的回调函数。
    success :function(data){
     console.log(data);
     $("#id").html(data.id);
     $("#name").html(data.name);
     $("#author").html(data.author);
    },
    // 请求出错时调用的函数
    error:function(){
     alert("数据发送失败");
    }
  });
 }
</script>
</head>
<body>
 编号:<span id="id"></span><br>
 书名:<span id="name"></span><br>
 作者:<span id="author"></span><br>
</body>
</html>

所有用到的包如下:

Spring MVC登录注册以及转换json数据

我们有两个方法来进行软件设计:一个是让其足够的简单以至于让BUG无法藏身;另一个就是让其足够的复杂,让人找不到BUG。前者更难一些。

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持服务器之家!

原文链接:http://www.cnblogs.com/ceet/p/6670433.html

延伸 · 阅读

精彩推荐