您好,登錄后才能下訂單哦!
項目結構;
代碼如下:
BookController
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
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
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
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
<?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
<%@ 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> <h4>登錄</h4> <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
<%@ 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> <h4>注冊頁面</h4> <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
<%@ 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> <h4>歡迎[${requestScope.user.userName }]登錄</h4> </body> </html>
web.xml
<?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
<%@ 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>
所有用到的包如下:
我們有兩個方法來進行軟件設計:一個是讓其足夠的簡單以至于讓BUG無法藏身;另一個就是讓其足夠的復雜,讓人找不到BUG。前者更難一些。
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持億速云!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。