? 最近自學了一周springMVC,做了個小東西,分享一下。
? ? ? ?首先是web.xml。這里我用了指定的位置和名稱來映射springmvc配置文件(即springMVC.xml)。存在src目錄下。
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd"><display-name>Spring MVC Application</display-name><servlet><servlet-name>springMVC</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!-- 通過初始化參數,指定xml文件的位置 --><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:springMVC.xml</param-value></init-param></servlet><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>
然后是springMVC.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:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"><!-- 啟用spring mvc注解 --><context:annotation-config></context:annotation-config><!-- 掃描包 --><context:component-scan base-package="com.keerqin"></context:component-scan><!-- 返回頁面的前后綴設置 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/jsp/" /><property name="suffix" value=".jsp" /></bean><!-- 請求的編碼格式,必須和jSP的pageEncoding屬性一致,以便正確讀取表單的內容,默認為ISO-8859-1 --><property name="defaultEncoding"><value>UTF-8</value></property></bean>
</beans>
jar包都一樣,多了一個jstl.jar,commons-el.jar。
啟動服務器,先進入index.jsp。。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>index</title>
</head>
<body><a href="getAll">getAll</a>
</body>
</html>
很簡單,就一個超鏈接。
然后是重頭戲Controller.java。
package com.keerqin.handler;import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;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.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;import com.keerqin.entities.User;@org.springframework.stereotype.Controller
public class Controller {private static final String SUCCESS = "success";public void init(){Map<Integer,User> map = new LinkedHashMap();HttpSession session = getSession();map.put(1, new User(1,18,"三星"));map.put(2, new User(2,20,"蘋果"));map.put(3, new User(3,21,"華為"));session.setAttribute("map", map);}@RequestMapping("/getAll")public ModelAndView getAll(){init();HttpSession session = getSession();ModelAndView mv = new ModelAndView(SUCCESS);mv.addObject("map",(Map<Integer, User>)session.getAttribute("map"));return mv;}@RequestMapping(value="/addOne")public ModelAndView addOne(User user) {HttpSession session = getSession();ModelAndView mv = new ModelAndView(SUCCESS);Map<Integer,User> map = (Map<Integer, User>) session.getAttribute("map");int lastKey = getLastKeyOfMap(map);map.put(lastKey+1, user);mv.addObject("map",map);session.setAttribute("map", map);return mv;} @RequestMapping(value="/delete/{id}")public ModelAndView delete(@PathVariable String id){HttpSession session = getSession();Map<Integer,User> map = (Map<Integer, User>) session.getAttribute("map");map.remove(Integer.parseInt(id));ModelAndView mv = new ModelAndView(SUCCESS);mv.addObject("map", map);session.setAttribute("map", map);return mv;}public int getLastKeyOfMap(Map map){Set<Entry<Integer, String>> mapValues = map.entrySet();//map -> setint maplength = mapValues.size(); //set.size()Entry<Integer,String>[] test = new Entry[maplength];//new entry() [] mapValues.toArray(test);// set -> arrayreturn test[maplength-1].getKey();}public static HttpSession getSession() { HttpSession session = null; try { session = getRequest().getSession(); } catch (Exception e) {} return session; } public static HttpServletRequest getRequest() { ServletRequestAttributes attrs =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); return attrs.getRequest(); } }
Controller.java用到了一個實體類User.java。
package com.keerqin.entities;public class User {private int id;private int age;private String name;public int getId() {return id;}public void setId(int id) {this.id = id;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "User [id=" + id + ", age=" + age + ", name=" + name + "]";}public User(int id, int age, String name) {super();this.id = id;this.age = age;this.name = name;}public User() {super();// TODO Auto-generated constructor stub}}
很普通,沒什么說的。
先點擊index.jsp 的超鏈接,
<a href="getAll">getAll</a>
這個時候web.xml中的接下來會執行Controller.java中的getAll()方法,該方法先調用init(),模擬數據庫中的數據,并把map存到session中。
然后再把從init中獲取的map存到ModelAndView 中,返回到success.jsp頁面中。如下所示:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>success</title>
</head>
<body><table border="1"><tr><th>id</th><th>userId</th><th>userAge</th><th>userName</th><th>操作</th></tr><c:forEach items="${map}" var="node"><tr><td><c:out value="${node.key}"></c:out></td><td><c:out value="${node.value.id}"></c:out></td><td><c:out value="${node.value.age}"></c:out></td><td><c:out value="${node.value.name}"></c:out></td><td><a href="delete/${node.key}">刪除</a> <a href="${node.key}">修改</a></td></tr></c:forEach></table><br><br><form action="addOne" method="post">userId<input type="text" name="id"><br> userAge<input type="text" name="age"><br> userName<input type="text" name="name"><br> <input type="submit" value="submit"><br></form>
</body>
</html>
jsp頁面使用jstl進行輸出。以上算是查詢操作。顯示如下:
表格下面還有輸入userId,userAge,userName的文本框,這個是添加操作。輸入之后submit會跳轉到Controller.java的addOne()。接收參數的直接獲取user對象,會把三個值直接填充到對象,但是名稱不能寫錯,不然會接收不到。接收參數后,再從session獲取init()中定義的map。之后調用getLasKeyOfMap()方法獲取map的最后一個鍵的值,再根據這個值添加新的屬性到map中,存到ModelAndView,返回頁面。
提交后
至此,增加功能完成。之后是刪除。
點擊任意一欄的刪除按鈕,會跳轉到Controller.java的delete()方法。刪除操作是個超鏈接,鏈接后面帶有id屬性即map的key值。后臺通過spring的@PathVariable注解獲取到該值,再通過map的remove(key)方法刪除該entry。再返回到succes.jsp。這樣就實現了刪除操作。
修改操作沒來得及寫,有時間再補上。
這是項目:鏈接:https://pan.baidu.com/s/1gfzWYRL 密碼:lclp
這是我第一次寫博客,不足的地方希望大家指正,謝謝。
總結
以上是生活随笔為你收集整理的springMVC 实现的增删查(没有数据库,用session代替)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。