spring mvc
使用maven新建项目,添加srpingmvc依赖
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.0.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.1.RELEASE</version> </dependency> </dependencies>
创建WEB-INF目录及web.xml文件
编辑web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <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/services.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
创建spring配置文件services.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" 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.xsd"> <context:component-scan base-package="org.mythsky.springdemo"></context:component-scan> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean> </beans>
编写HelloController
package org.mythsky.springdemo; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class HelloController { private static final Log logger= LogFactory.getLog(HelloController.class); @RequestMapping(value = "/hello") public ModelAndView hello(){ logger.info("hello 方法被调用"); ModelAndView mv=new ModelAndView(); mv.addObject("message","Hello World!"); mv.setViewName("/WEB-INF/views/welcome.jsp"); return mv; } }
新建一个jsp页面welcome.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>欢迎</title> </head> <body> <h3>${requestScope.message}</h3> </body> </html>
配置tomcat
运行tomcat,打开地址:http://localhost:8080/hello
结果
接着修改下services.xml的试图解析器配置
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean>
新建一个User类
package org.mythsky.springdemo.model; import java.io.Serializable; public class User implements Serializable { private String username; private String sex; private Integer age; public User() { super(); } public User(String username, String sex, Integer age) { this.username = username; this.sex = sex; this.age = age; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
UserController
package org.mythsky.springdemo.controller; import org.mythsky.springdemo.model.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; @Controller public class UserController { @RequestMapping(value = "/register",method = RequestMethod.GET) public String registerForm(Model model){ User user=new User("jack","男",28); model.addAttribute("command",user); return "registerForm"; } }
可以看到此时返回的是一个字符串registerForm,配合视图解析器的前缀和后缀会自动查找/WEB-INF/views/registerForm.jsp
新建registerForm.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%-- Created by IntelliJ IDEA. User: mythsky Date: 2017/11/18 Time: 14:58 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>注册</title> </head> <body> <form:form action="register" method="post"> <table> <tr> <td>姓名:</td> <td><form:input path="username"></form:input></td> </tr> <tr> <td>性别:</td> <td><form:input path="sex"></form:input></td> </tr> <tr> <td>年龄:</td> <td><form:input path="age"></form:input></td> </tr> </table> </form:form> </body> </html>
运行tomcat,打开地址:http://localhost:8080/register ,会看到User自动绑定到了页面上
这里是因为控制器里把user绑定到了command上,如果不是绑定到command上,而是换个名字,比如user,可以使用如下方式
model.addAttribute("user",user);
Idea很智能给出了提示。
查看页面源码可以看到模型的绑定
给user添加两个属性
private boolean reader; private List<String> courses;
修改控制器
User user=new User("jack","男",28); user.setReader(true); List<String> list=new ArrayList<String>(); list.add("javaee"); list.add("spring"); user.setCourses(list); model.addAttribute("user",user);
修改页面
<tr> <td>年龄:</td> <td><form:input path="age"></form:input></td> </tr> <tr> <td>选择课程:</td> <td> <form:checkbox path="courses" value="javaee" label="javee"></form:checkbox> <form:checkbox path="courses" value="spring" label="spring"></form:checkbox> <form:checkbox path="courses" value="mybatis" label="mybatis"></form:checkbox> </td> </tr> </table> <form:checkbox path="reader"></form:checkbox>已经阅读相关协议
查看结果
改用checkboxes效果也是一样的,需要修改控制器
User user=new User("jack","男",28); user.setReader(true); List<String> list=new ArrayList<String>(); list.add("javaee"); list.add("spring"); user.setCourses(list); List<String> courseList=new ArrayList<String>(); courseList.add("javaee"); courseList.add("spring"); courseList.add("mybatis"); model.addAttribute("user",user); model.addAttribute("courseList",courseList);
页面
<tr> <td>选择课程:</td> <td> <form:checkboxes path="courses" items="${courseList}"></form:checkboxes> </td> </tr>
select
新增Dept类
package org.mythsky.springdemo.model; public class Dept { private Integer id; private String name; public Dept() { } public Dept(Integer id, String name) { this.id = id; this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
在User中添加属性
private Integer deptId;
控制器添加方法
@RequestMapping(value = "/select",method = RequestMethod.GET) public String SelectForm(Model model){ User user=new User(); user.setDeptId(2); Map<Integer,String> dept=new HashMap<Integer, String>(); dept.put(1,"财务部"); dept.put(2,"开发部"); dept.put(3,"销售部"); model.addAttribute("user",user); model.addAttribute("dept",dept); return "selectForm"; }
添加selectForm.jsp页面
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%-- Created by IntelliJ IDEA. User: mythsky Date: 2017/11/18 Time: 15:52 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>select</title> </head> <body> <form:form modelAttribute="user" action="register" method="post"> <table> <tr> <td>选择部门:</td> <td> <form:select path="deptId" items="${dept}"></form:select> </td> </tr> </table> </form:form> </body> </html>
继续修改控制器
@RequestMapping(value = "/select",method = RequestMethod.GET) public String SelectForm(Model model){ User user=new User(); user.setDeptId(2); List<Dept> list=new ArrayList<Dept>(); list.add(new Dept(1,"财务部")); list.add(new Dept(2,"开发部")); list.add(new Dept(3,"销售部")); model.addAttribute("user",user); model.addAttribute("dept",list); return "selectForm"; }
修改页面
td> <form:select path="deptId"> <form:options items="${dept}" itemLabel="name" itemValue="id"></form:options> </form:select> </td>
效果与刚才一致。
errors
添加一个验证类
package org.mythsky.springdemo.validator; import org.mythsky.springdemo.model.User; import org.springframework.lang.Nullable; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; public class UserValidator implements Validator { public boolean supports(Class<?> aClass) { return User.class.equals(aClass); } public void validate(@Nullable Object o, Errors errors) { ValidationUtils.rejectIfEmpty(errors,"username",null,"用户名不能为空"); ValidationUtils.rejectIfEmpty(errors,"sex",null,"性别不能为空"); } }
控制器中添加验证
@InitBinder public void initBinder(DataBinder binder){ binder.setValidator(new UserValidator()); } @RequestMapping(value = "/register",method = RequestMethod.POST) public String register(@Validated User user,Errors errors){ if(errors.hasFieldErrors()) return "registerForm"; return "submit"; }
页面修改
<tr> <td>姓名:</td> <td><form:input path="username"></form:input></td> <td><font color="red"><form:errors path="username"></form:errors></font> </td> </tr> <tr> <td>性别:</td> <td><form:input path="sex"></form:input></td> <td><font color="red"><form:errors path="sex"></form:errors></font> </td> </tr> <tr> <td>年龄:</td> <td><form:input path="age"></form:input></td> </tr> <tr><td><input type="submit" value="提交"></td></tr>
查看结果
权限控制
User
package org.mythsky.security.domain; import java.util.Date; public class User { private Integer id; private String username; private String loginname; private String password; private Integer status; private Date createDate; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getLoginname() { return loginname; } public void setLoginname(String loginname) { this.loginname = loginname; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } }
UserService
package org.mythsky.security.service; import org.mythsky.security.domain.User; import org.springframework.stereotype.Service; @Service public class UserService { public User login(String loginname,String password){ User user=new User(); if(loginname.equals("admin")&&password.equals("admin")){ user.setId(1); user.setLoginname("admin"); user.setUsername("admin"); }else{ user=null; } return user; } }
HelloController
package org.mythsky.security.controllers; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class HelloController { private static final Log logger= LogFactory.getLog(HelloController.class); @RequestMapping(value = "/hello") public ModelAndView hello(){ logger.info("hello 方法被调用"); ModelAndView mv=new ModelAndView(); mv.addObject("message","Hello World!"); mv.setViewName("welcome"); return mv; } }
UserController
package org.mythsky.security.controllers; import org.mythsky.security.domain.User; import org.mythsky.security.service.UserService; 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.RequestParam; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpSession; @Controller public class UserController { @Autowired UserService userService; @RequestMapping("/loginForm") public String loginForm(){ return "loginForm"; } @RequestMapping("/login") public ModelAndView login(@RequestParam("loginname")String loginname, @RequestParam("password")String password, HttpSession session, ModelAndView mv){ User user=userService.login(loginname,password); if(user!=null){ session.setAttribute("user",user); mv.addObject("message",user.getLoginname()); mv.setViewName("redirect:/hello"); // mv.setViewName("welcome"); }else { mv.addObject("message","用户名或密码错误!请重新输入"); mv.setViewName("forward:/loginForm"); } return mv; } }
AuthorizedInterceptor
package org.mythsky.security.interceptor; import org.mythsky.security.domain.User; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AuthorizedInterceptor implements HandlerInterceptor { private static final String[] IGNORE_URL={"/loginForm","/login","/404.html"}; public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //默认用户没有登录 boolean flag=false; //获得请求的ServletPath String servletPath=request.getServletPath(); //判断是否需要拦截 for(String s:IGNORE_URL){ if(servletPath.contains(s)){ flag=true; break; } } //拦截请求 if(!flag){ //获取Session中的用户 User user=(User)request.getSession().getAttribute("user"); //判断用户是否已经登录 if(user==null){ //如果用户没有登录,跳转到登录页面 request.setAttribute("message","请先登录再访问网站!"); request.getRequestDispatcher("/loginForm").forward(request,response); return flag; }else { flag=true; } } return flag; } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <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/services.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
services.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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="org.mythsky.security"></context:component-scan> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/hello"/> <bean class="org.mythsky.security.interceptor.AuthorizedInterceptor"></bean> </mvc:interceptor> </mvc:interceptors> </beans>
loginForm.jsp
<%-- Created by IntelliJ IDEA. User: mythsky Date: 2018/8/19 Time: 18:28 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <html> <head> <title>登录</title> </head> <body> <form:form method="post" action="login"> <table> <tr> <td>登录名:</td> <td><input type="text" name="loginname"></td> </tr> <tr> <td>密 码:</td> <td><input type="password" name="password"></td> </tr> <tr> <td><input type="submit" value="提交"> </td> </tr> </table> </form:form> </body> </html>
welcome.jsp
<%-- Created by IntelliJ IDEA. User: mythsky Date: 2018/8/19 Time: 17:40 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>欢迎</title> </head> <body> <h3>${requestScope.message}</h3> </body> </html>