更新時間:2022-07-08 10:22:19 來源:動力節點 瀏覽1541次
動力節點小編來給大家舉例介紹一下最基本的增刪改查。
web.xml,主要用于配置Filter,Servlet,Lisenter等
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>usermanage</display-name>
<!-- 配置spring容器初始化監聽器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置編碼的過濾器 -->
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<!--攔截路徑 -->
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置DispatcherServlet -->
<servlet>
<servlet-name>usermanage</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/usermanage-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>usermanage</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
usermanage-servlet.xml,對應于Controller
主要步驟:配置注解驅動;開啟注解掃描;解決靜態資源的攔截問題;配置視圖解析器
<?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:p="http://www.springframework.org/schema/p"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:view-controller path="/user/users" view-name="users"/>
<mvc:view-controller path="/user/page/add" view-name="user-add"/>
<mvc:view-controller path="/user/page/edit" view-name="user-edit"/>
<!-- 配置注解驅動:替代推薦使用的注解映射器和適配器,提供對json的支持 -->
<mvc:annotation-driven />
<!-- 開啟注解掃描,和spring是一樣的 -->
<context:component-scan base-package="com.cn.usermanage.controller" />
<!-- 解決靜態資源被攔截的問題 -->
<mvc:default-servlet-handler/>
<!-- 配置視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
applicationContext.xml 中需要配置(省略數據庫的配置文件)
<!-- 注解掃描 -->
<context:component-scan base-package="com.cn.usermanage.service"/>
<!-- 加載資源文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 配置數據源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="driverClass" value="${jdbc.driver}" />
</bean>
applicationContext-mybatis.xml中需要配置,和利用mybatis操作數據庫相關
步驟:需要初始化SqlsessionFactory對象;配置Mapper接口的包掃描
<!-- spring初始化bean的方式: 1.無參構造 2.靜態工廠方法 3.實例化工廠 4.工廠bean -->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 指定數據源 -->
<property name="dataSource" ref="dataSource" />
<!-- 指定全局配置文件 -->
<property name="configLocation"
value="classpath:mybatis/mybatis-config.xml"></property>
<!-- 指定映射文件(不需要mybatis-config.xml中映射),利用通配符匹配任意目錄任意xml配置 -->
<property name="mapperLocations" value="classpath:mybatis/mappers/**/*.xml"></property>
<!-- 開啟別名掃描 -->
<property name="typeAliasesPackage"
value="com.cn.usermanage.pojo"></property>
</bean>
<!-- 配置mapper接口的包掃描 -->
<mybatis-spring:scan
base-package="com.cn.usermanage.mapper" />
mybatis-config.xml只需要配置行為參數即可
<settings>
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
實體類對象User可以通過注解的方式對屬性進行數據校驗,常用的注解如:
@Null 驗證對象是否為 null
@NotNull 驗證對象是否不為 null
@Size(min,max) 驗證對象長度是否在給定的范圍內
@Past 驗證 Date 和 Calendar 對象是否在當前時間之前
@Future 驗證 Date 和 Calendar 對象是否在當前時間之后
@Pattern 驗證 String 對象是否符合正則表達式的規則
@NotBlank 檢查字符串是不是 Null,被 Trim 的長度是否大于0,只對字符串,且會去掉前后空格
@URL 驗證是否是合法的 url
@Email 驗證是否是合法的郵箱
User.java
public class User {
private Long id;
// 用戶名
@NotNull
@Length(min=6, max=20, message="用戶名長度不合法")
private String userName;
// 密碼
@JsonIgnore
@NotNull
@Length(min=6, max=20, message="用戶名長度不合法")
private String password;
// 姓名
@NotNull
private String name;
// 年齡
@NotNull
private Integer age;
// 性別,1男性,2女性
@NotNull
private Integer sex;
// 出生日期
@NotNull
@DateTimeFormat(pattern="yyyy-MM-dd")
@Past(message="生日必須是過去式")
private Date birthday;
// 創建時間
private Date created;
// 更新時間
private Date updated;}
UserController.java
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("users")
public String toUsers() {
return "users";
}
@RequestMapping("list")
@ResponseBody
public Map<String, Object> queryUserAll() {
Map<String, Object> map = new HashMap<>();
// 查詢總條數
Long total = this.userService.queryTotal();
map.put("total", total);
List<User> users = this.userService.queryUserAll();
map.put("rows", users);
return map;
}
@RequestMapping("save")
@ResponseBody
public Map<String, String> saveUser(@Valid User user,BindingResult result)
{
Map<String,String> map=new HashMap<>();
if(result.hasErrors())
{
//輸出到控制臺
System.out.println(result.getAllErrors()); //status用于前端校驗是否執行成功
map.put("status", "500");
return map;
}
//調用Service方法新增用戶信息
Boolean flag=this.userService.saveUser(user);
if(flag)
map.put("status", "200");
else
map.put("status", "500");
return map;
}
//修改
@RequestMapping("edit")
@ResponseBody
public Map<String, String> editUser(@Valid User user)
{
Map<String,String> map=new HashMap<>();
//調用Service方法新增用戶信息
Boolean flag=this.userService.editUser(user);
if(flag)
map.put("status", "200");
else
map.put("status", "500");
return map;
}
//刪除
@RequestMapping("delete")
@ResponseBody
public Map<String, String> deleteUser(@RequestParam("ids")List<Long> ids )
{
Map<String,String> map=new HashMap<>();
//調用Service方法新增用戶信息
Boolean flag=this.userService.deleteUserByIds(ids);
if(flag)
map.put("status", "200");
else
map.put("status", "500");
return map;
}
}
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習