使用背景:
创建一个Controller: LoginConstroller
public class LoginController extends AbstractController{
public ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response)throws Exception{
String userName=request.getParameter("username");
String pwd=request.getParameter("pwd");
String msg="";
ModelAndView mav=new ModelAndView("loginResult"); //注意要在/WEB-INF/jsp下面创建loginResult.jsp页面
if(!userName.equals("liuxi")){
msg="用户名不存在!";
}else if(!pwd.equals("8888")){
msg="密码不正确!";
}else{
msg="恭喜您登录成功!";
}
mav.addObject("msg",msg);
return mav;
}
}
配置web.xml:
<?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">
<servlet>
<servlet-name>sample</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sample</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
配置sample-servlet.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean name="/user/login.do" class="com.spring.web.controller.LoginController"/>
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix"><value>/WEB-INF/jsp/</value></property>
<property name="suffix"><value>.jsp</value></property>
<property name="viewClass">
<value>
org.springframework.web.servlet.view.JstlView
</value>
</property>
</bean>
</beans>
浏览器输入:http://localhost:8888/SpringWorld/user/login.do?username=liuxi&pwd=8888
结果:恭喜您登录成功!