javax.servlet.jarhttp.HttpServletResponse

Android: How to send HTTP GET request to Servlet using Apache Http Client >> the Open Tutorials
Sign In | Register the Open TutorialsTutorialsAndroidHTTPAndroid: How to send HTTP GET request to Servlet using Apache Http Client 21 September 2012 By Nithya Vasudevan 25,575 views 22 Comments
35 Flares × Contents1 Project Description2 Environment Used3 Prerequisites4 Servlet Project4.1 Servlet4.2 Start server4.3 Folder structure5 Android Project5.1 strings.xml5.2 XML layout file5.3 Activity5.4 AndroidManifest.xml5.5 Android Project Folder Structure6 OutputProject DescriptionIn this Android tutorial, we will see how to make a simple Http GET request to Servlet using Apache Http Client (DefaultHttpClient) and display the response in TextView.We use android.os.AsyncTask to perform this task.Environment UsedAndroid SDK 4.0.3 / 4.1 Jelly BeanAndroid Development Tools (ADT) Plugin for Eclipse (ADT version 20.0.0)Refer this link to setup the Android development environmentPrerequisitesHelloWorld ExampleHow to create a Servlet with Eclipse and TomcatServlet ProjectCreate a new Dynamic Web Project and name it as “HttpGetServlet“.ServletCreate a new Servlet and name it as “HelloWorldServlet” in package “com.theopentutorials.servlets” and copy the following code.package com.theopentutorials.
import java.io.IOE
import java.io.PrintW
import javax.servlet.ServletE
import javax.servlet.http.HttpS
import javax.servlet.http.HttpServletR
import javax.servlet.http.HttpServletR
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HelloWorldServlet() {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println(&Hello Android !!!!&);
Start serverDeploy the project in server and start/restart the server. You can refer the link mentioned in prerequisite section to do this.Folder structureThe complete folder structure of this Servlet project is shown below. Android ProjectCreate an Android project and name it as “SimpleHttpGetServlet“.strings.xmlOpen res/values/string.xml and replace it with following content.
&?xml version=&1.0& encoding=&utf-8&?&
&resources&
&string name=&hello&&Accessing Servlet from Android&/string&
&string name=&app_name&&SimpleHttpGetServlet&/string&
&string name=&button&&Invoke Servlet&/string&
&/resources&
XML layout fileThis application uses XML layout file (main.xml) to display the response from Servlet.Open main.xml file in res/layout and copy the following content.
&?xml version=&1.0& encoding=&utf-8&?&
&LinearLayout xmlns:android=&/apk/res/android&
android:layout_width=&fill_parent&
android:layout_height=&fill_parent&
android:orientation=&vertical& &
android:layout_width=&fill_parent&
android:layout_height=&wrap_content&
android:text=&@string/hello& /&
android:id=&@+id/button&
android:layout_width=&fill_parent&
android:layout_height=&wrap_content&
android:text=&@string/button& /&
android:id=&@+id/outputTxt&
android:layout_width=&fill_parent&
android:layout_height=&wrap_content&
android:textColor=&#CC0033&
android:textSize=&16sp&
android:textStyle=&bold& /&
&/LinearLayout&
ActivityIn src folder, create a new Class and name it as “HttpGetServletActivity” in the package “com.theopentutorials.android” and copy the following code.From Android 3.x Honeycomb or later, you cannot perform Network IO on the UI thread and doing this throws android.os.NetworkOnMainThreadException. You must use Asynctask instead as shown below.
package com.theopentutorials.
import java.io.IOE
import java.io.UnsupportedEncodingE
import org.apache.http.HttpE
import org.apache.http.HttpR
import org.apache.http.client.ClientProtocolE
import org.apache.http.client.methods.HttpG
import org.apache.http.impl.client.DefaultHttpC
import org.apache.http.util.EntityU
import android.app.A
import android.os.AsyncT
import android.os.B
import android.view.V
import android.view.View.OnClickL
import android.widget.B
import android.widget.TextV
public class HttpGetServletActivity extends Activity implements OnClickListener{
TextView outputT
public static final String URL = &http://10.0.2.2:8080/HttpGetServlet/HelloWorldServlet&;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewsById();
button.setOnClickListener(this);
private void findViewsById() {
button = (Button) findViewById(R.id.button);
outputText = (TextView) findViewById(R.id.outputTxt);
public void onClick(View view) {
GetXMLTask task = new GetXMLTask();
task.execute(new String[] { URL });
private class GetXMLTask extends AsyncTask&String, Void, String& {
protected String doInBackground(String... urls) {
String output =
for (String url : urls) {
output = getOutputFromUrl(url);
private String getOutputFromUrl(String url) {
String output =
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
output = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
protected void onPostExecute(String output) {
outputText.setText(output);
Whenever we need to perform lengthy operation or any background operation we can use Asyntask which executes a task in background and publish results on the UI thread without having to manipulate threads and/or handlers.In onClick(), we create and execute the task to make Http request and get response. The task’s execute method invokes doInBackground() where we use Apache Http Client API to execute the Http GET request to Servlet and get output response and return it.Once the background computation finishes, onPostExecute() is invoked on the UI thread which sets the output text in TextView. We are running the remote server in the local machine itself (localhost). So you may try to access the resources using http://localhost:8080, but you may get “Connection refused” (failed to connect to localhost/127.0.0.1) exception because our code is running in an emulator so localhost refers to the emulator itself and not the machine which is running the Tomcat/Apache server. So to access local machine from emulator, you have to use 10.0.2.2 IP address which points to the machine which has the running emulator. Android includes two HTTP clients:
HttpURLConnection and Apache HTTP Client. For Gingerbread and later, HttpURLConnection is the best choice. Refer this link for HttpURLConnection
example.AndroidManifest.xmlDefine the activity in AndroidManifest.xml file. To access internet from Android application set the android.permission.INTERNET permission in manifest file as shown below.
&?xml version=&1.0& encoding=&utf-8&?&
&manifest xmlns:android=&/apk/res/android&
package=&com.theopentutorials.android&
android:versionCode=&1&
android:versionName=&1.0& &
&uses-sdk android:minSdkVersion=&15& /&
&uses-permission android:name=&android.permission.INTERNET& /&
&application
android:icon=&@drawable/ic_launcher&
android:label=&@string/app_name& &
android:name=&.HttpGetServletActivity&
android:label=&@string/app_name& &
&intent-filter&
&action android:name=&android.intent.action.MAIN& /&
&category android:name=&android.intent.category.LAUNCHER& /&
&/intent-filter&
&/activity&
&/application&
&/manifest&
Android Project Folder StructureThe complete folder structure of this example is shown below. OutputRun your Android application Related posts:Android: How to send HTTP GET request to Servlet using HttpURLConnection Android: Sending data from one Activity to another How to parse remote XML using SAX parser with Android AsyncTask Android: How to load Image from URL in ImageView? Tags: Android 4 Examples, Android Apache Http Client Example, Android Asynctask Example, Android DefaultHttpClient Example, Android Examples, Android Http Example, Android Http Get request to Servlet, Android Servlet ExampleFollow @opentutorialsPopular PostsHow to create a Servlet with Eclipse and Tomcat Pagination in Servlet and JSP Android: Custom ListView with Image and Text using ArrayAdapter How to create a simple EJB3 project in Eclipse (JBoss 7.1) Android: Expandable List View Example How to create and consume a simple Web Service using JAX WS Generate Java class from XML Schema using JAXB 'xjc' command How to configure Apache Tomcat in Eclipse IDE? How to create a simple Restful Web Service using Jersey JAX RS API How to create EJB3 JPA Project in Eclipse (JBoss AS 7.1) Recent CommentsBACK TO TOP &Spring拦截器中通过request获取到该请求对应Controller中的method对象 - 青葱岁月 - ITeye技术网站
博客分类:
背景:项目使用Spring 3.1.0.RELEASE,从dao到Controller层全部是基于注解配置。我的需求是想在自定义的Spring拦截器中通过request获取到该请求对应于Controller中的目标method方法对象。Controller和拦截器代码如下:
AdminController
@Controller
@RequestMapping("/admin")
public class AdminController {
* init:初始页面. &br/&
* @author chenzhou
* @param request 请求
* @param response 响应
* @return 登陆页
* @since JDK 1.6
@RequestMapping("/init")
public ModelAndView init(HttpServletRequest request,
HttpServletResponse response){
Map&String, Object& model = new HashMap&String, Object&();
List&Role& roleList = this.adminService.getRoleList();
model.put("roleList", roleList);
return new ModelAndView(this.getLoginPage(), model);
LoginInterceptor
public class LoginInterceptor extends HandlerInterceptorAdapter {
* This implementation always returns &code&true&/code&.
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
* This implementation is empty.
public void postHandle(
HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws Exception {
* This implementation is empty.
public void afterCompletion(
HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
servlet xml配置文件定义:
&bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" /&
&bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/&
&bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"&
&property name="interceptors"&
&bean class="com.chenzhou.examples.erm.util.interceptor.LoginInterceptor"/&
&/property&
我的需求是想在preHandle方法中通过request获取该请求访问的目标Controller中的方法对象。之前找了很久也没有找到比较好的方案,就采取了最老土的通过比较requestURL和Controller类和方法上的RequestMappingURL来进行获取,这样也能勉强实现,但是这种方式我自己都觉得特别恶心。首先,这种方式需要使用反射来获取Controller中的所有方法,然后遍历method数组,逐个进行RequestMappingURL的比对,效率低下。其次,如果RequestMapping定义了类似于@RequestMapping("/{id}")这种动态参数url,则无法进行比较。
因为上面这种方式不好,我就一直想找一个更好的方案。不得已只能向人求助,第一个就想到了Iteye上对于Spring研究得很熟悉的龙年兄,我相信经常上iteye的博友们对龙年兄应该都很熟悉。龙年兄给了我一个方案,就是通过把handler对象转换为HandlerMethod类型,然后直接getMethod,代码如下:
* This implementation always returns &code&true&/code&.
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("*********************preHandle********************");
System.out.println(handler.getClass());
HandlerMethod handlerMethod = (HandlerMethod)
System.out.println(handlerMethod.getMethod());
注:HandlerMethod类是Spring 3.1.0.RELEASE版本中才有的,之前我使用的Spring 3.0.6.RELEASE版本,里面是找不到这个类的
根据龙年兄提供的方法,测试之后报错,报错信息如下:
*********************preHandle********************
class com.chenzhou.examples.erm.web.AdminController
16:28:25 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet erm threw exception
java.lang.ClassCastException: com.chenzhou.examples.erm.web.AdminController cannot be cast to org.springframework.web.method.HandlerMethod
at com.chenzhou.examples.erm.util.interceptor.LoginInterceptor.preHandle(LoginInterceptor.java:37)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:891)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
根据错误提示可以看出是HandlerMethod handlerMethod = (HandlerMethod)这一步报错了,根据System.out.println(handler.getClass());打印的结果可以得知handler是该请求访问的Controller类,无法转换成HandlerMethod对象。这次还是龙年兄帮我找出了原因,解决方案是使用
&bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"& 替换 &bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/&
因为DefaultAnnotationHandlerMapping只能返回Controller对象,不会映射到Controller中的方法级别。替换之后servlet xml配置如下:
&bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" /&
&bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/&
&bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"&
&property name="interceptors"&
&bean class="com.chenzhou.examples.erm.util.interceptor.LoginInterceptor"/&
&/property&
重启tomcat测试之后发现再次报错,报了另外一个错误,具体信息如下:
16:39:39 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet erm threw exception
javax.servlet.ServletException: No adapter for handler [public org.springframework.web.servlet.ModelAndView com.chenzhou.examples.erm.web.AdminController.init(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)]: Does your handler implement a supported interface like Controller?
这一次,请求根本没有到达拦截器容器就已经报错了,错误提示的意思是找不到handler对象对应的Adapter类。我在RequestMappingHandlerMapping类对应的spring-webmvc-3.1.0.RELEASE.jar 包里找到了该类对应的Adapter类:RequestMappingHandlerAdapter,然后在servlet xml中进行了配置:
&bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" /&
&bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/&
&bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"&
&property name="interceptors"&
&bean class="com.chenzhou.examples.erm.util.interceptor.LoginInterceptor"/&
&/property&
&bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/&
然后重新启动tomcat后访问http://localhost:8080/erm/admin/init 结果正常,控制台日志信息如下:
*********************preHandle********************
class org.springframework.web.method.HandlerMethod
public org.springframework.web.servlet.ModelAndView com.chenzhou.examples.erm.web.AdminController.init(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
从日志信息可以看出,handler对象在经过类型转换后转换成了HandlerMethod类型,通过handler.getMethod方法,获取到了该请求访问的方法为com.chenzhou.examples.erm.web.AdminController.init
注:非常感谢jinnianshilongnian 开涛兄的帮助。
浏览 15810
3.0& 没有对应的 handlerMethod 类& ,具体解决办法请参考我的博客三个拦截器处理三个注解搞定基于注解的权限控制,适用性比较通用于Springmvc web项目
楼主,你这样处理,是不是就是为了解决,SPRING AOP不能针对CONTROLLER生效的问题,求回复!也可以这么说吧,当时是为了做权限控制发现aop对Controller不生效,后来就采用了拦截器的方式。
谢谢lz,我google了好久 不客气
感谢楼主无私分享,google了好久了。谢谢鼓励
楼主的这种分享方式真心不错,分享知识,也是一种艺术。这种方式的分享让人受益很大。谢谢鼓励!
针对springmvc3.0版本AnnotationMethodHandlerAdapter可以试下下面方法:Class handlerClass = ClassUtils.getUserClass(handler);
ServletHandlerMethodResolver resolver = new ServletHandlerMethodResolver(handlerClass);
Method handlerMethod = methodResolver.resolveHandlerMethod(request);呵呵,抱歉没注意到ServletHandlerMethodResolver是一个内部私有类
chenzhou123520
浏览: 630875 次
来自: 北京
再次感谢大家,也祝福大家(不管是留在圈内的还是跳出来的),一起 ...
有没有好的办法,谢谢
不起作用,我这边实验的是ajax的响应时间过长,就会被拦截(我 ...
恭喜楼主,我也是从帝都到深圳的 不过还没转行,呵呵呵。。Spring3.0MVC和Hibernate基于annotation注解的整合 - 终于改了这名称 - ITeye技术网站
博客分类:
springmvc和hibernate的annotation集合:
首先web.xml
&?xml version="1.0" encoding="UTF-8"?&
&web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="/xml/ns/javaee" xmlns:web="/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="/xml/ns/javaee /xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"&
&display-name&hibernateAspringmvc&/display-name&
&context-param&
&param-name&contextConfigLocation&/param-name&
&param-value&classpath*:applicationContext*.xml&/param-value&
&/context-param&
&listener&
&listener-class&org.springframework.web.context.ContextLoaderListener&/listener-class&
&/listener&
&!-- this is 'spring' name for your spring-servlet.xml --&
&servlet-name&spring&/servlet-name&
&servlet-class&org.springframework.web.servlet.DispatcherServlet&/servlet-class&
&load-on-startup&1&/load-on-startup&
&/servlet&
&servlet-mapping&
&servlet-name&spring&/servlet-name&
&url-pattern&*.xl&/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&
然后是applicationContext.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:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd"
default-autowire="byName" default-lazy-init="true"&
&!-- this pack must include xxx-servlet.xml's pack. --&
&context:component-scan base-package="org.xlaohe1" /&
&bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"&
&property name="driverClassName" value="com.mysql.jdbc.Driver" /&
&property name="url" value="jdbc:mysql://localhost:3306/test" /&
&property name="username" value="root" /&
&property name="password" value="root" /&
&bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"&
&property name="dataSource" ref="dataSource" /&
&!-- 这几句在spring hibernate的注解整合中可以不需要 因为下面的2就是扫描指定路劲下的实体进行映射 --&
&!-- 1======================= --&
&property name="namingStrategy"&
&bean class="org.hibernate.cfg.ImprovedNamingStrategy" /&
&/property&
&property name="annotatedClasses"&&!-- the must have. before this is mapping,now is entity --&
&value&org.xlaohe1.model.User&/value&
&/property&
&!-- 1======================= --&
&property name="hibernateProperties"&
&prop key="hibernate.dialect"&org.hibernate.dialect.MySQLDialect&/prop&
&prop key="hibernate.show_sql"&false&/prop&
&prop key="hibernate.cache.provider_class"&org.hibernate.cache.EhCacheProvider&/prop&
&prop key="hibernate.cache.use_query_cache"&false&/prop&
&prop key="hibernate.jdbc.batch_size"&50&/prop&
&prop key="hibernate.cache.use_second_level_cache"&false&/prop&
&/property&
&!-- 2======================= --&
&!-- 自动扫描指定位置下的实体文件进行映射 --&
&property name="packagesToScan" value="org.xlaohe1.model" /&
&!-- 2======================= --&
&bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager"&
&property name="sessionFactory" ref="sessionFactory" /&
&tx:annotation-driven transaction-manager="transactionManager" /&
spring-serlvet.xml
&?xml version="1.0" encoding="UTF-8"?&
&beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-3.0.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-3.0.xsd"&
&!-- 对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 --&
&context:component-scan base-package="org.xlaohe1.web"/&
&!--启动Spring MVC的注解功能,完成请求和注解POJO的映射
&bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/&
&mvc:annotation-driven/&
对模型视图名称的解析,即在模型视图名称添加前后缀
&bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"/&--&
&bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"&
&property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/&
&property name="prefix" value="/WEB-INF/jsp/"/&
&property name="suffix" value=".jsp"/&
entity:
package org.xlaohe1.
import javax.persistence.C
import javax.persistence.E
import javax.persistence.GeneratedV
import javax.persistence.GenerationT
import javax.persistence.Id;
import javax.persistence.T
@Table(name = "users", catalog = "test")
public class User {
public User() {
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id")
public Integer getId() {
public void setId(Integer id) {
@Column(name = "username")
public String getUsername() {
public void setUsername(String username) {
this.username =
@Column(name = "password")
public String getPassword() {
public void setPassword(String password) {
this.password =
@Column(name = "age")
public Integer getAge() {
public void setAge(Integer age) {
this.age =
userdaoimpl
package org.xlaohe1.dao.
import java.util.L
import org.springframework.orm.hibernate3.support.HibernateDaoS
import org.springframework.stereotype.R
import org.xlaohe1.dao.IUserD
import org.xlaohe1.model.U
@Repository
public class UserDaoImpl extends HibernateDaoSupport implements IUserDao {
@SuppressWarnings("unchecked")
public List&User& findAllUsers() {
String hql = "FROM User";
return getHibernateTemplate().find(hql);
userserviceimpl
package org.xlaohe1.service.
import java.util.L
import org.springframework.beans.factory.annotation.A
import org.springframework.stereotype.S
import org.springframework.transaction.annotation.T
import org.xlaohe1.dao.IUserD
import org.xlaohe1.model.U
import org.xlaohe1.service.IUserS
@Service @Transactional
public class UserServiceImpl implements IUserService {
@Autowired IUserDao userD
//@Transactional(propagation=Propagation.SUPPORTS,readOnly=true)
public List&User& findAllUsers() {
return userDao.findAllUsers();
usercontroller
package org.xlaohe1.
import java.util.L
import javax.servlet.http.HttpServletR
import javax.servlet.http.HttpServletR
import org.springframework.beans.factory.annotation.A
import org.springframework.stereotype.C
import org.springframework.ui.ModelM
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.servlet.ModelAndV
import org.xlaohe1.model.U
import org.xlaohe1.service.IUserS
@Controller
public class UserController {
@Autowired
IUserService userS
public UserController() {
@RequestMapping(value = "/show")
public ModelAndView myMethod(HttpServletRequest request,
HttpServletResponse response, ModelMap modelMap) throws Exception {
List&User& ulst = userService.findAllUsers();
modelMap.put("users", ulst);
return new ModelAndView("showUser", modelMap);
@RequestMapping(value = "/t")
public ModelAndView t() {
return new ModelAndView("t");
有意见和建议请留下..
浏览 11656
reggie_ysq 写道一摸一样的代码和配置文件,但是总是有这个错,好汉给点建议啊首先检查你的jar包是否正确,然后在看看你的配置
&context:component-scan base-package="org.xlaohe1.web"/& 这个不能写错,你的dao和service的注解要写对最后你的controoler的Autowired是接口的不是实现主要你的Autowired地方看看可否把你的lib包用到的jar 贴出来啊? 配置,代码真的一样。 估计和包有关系吧。
一摸一样的代码和配置文件,但是总是有这个错,好汉给点建议啊首先检查你的jar包是否正确,然后在看看你的配置
&context:component-scan base-package="org.xlaohe1.web"/& 这个不能写错,你的dao和service的注解要写对最后你的controoler的Autowired是接口的不是实现主要你的Autowired地方看看
showUser.jsp代码能否贴出来?
&%@page import="org.springframework.ui.ModelMap"%&
&%@ page language="java" contentType="text/ charset=utf-8"
pageEncoding="utf-8"%&
&%@ taglib uri="/jsp/jstl/core" prefix="c"%&
&!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&
&meta http-equiv="Content-Type" content="text/ charset=utf-8"&
&title&在此处插入标题&/title&
&table border="1"&
&c:forEach var="list" items="${users}"&
&td&${list.id }&/td&
&td&${list.username }&/td&
&td&${list.password }&/td&
&td&${list.age }&/td&
&/c:forEach&
showUser page.
${loginUser }
&%=request.getAttribute("loginUser") %&
&a href="t.xl"&remove&/a&
请问一下你的spring-servlet是放在web-inf下面吗?对的。和web.xml同级。有时间我会加上结构图的。
&!-- this is 'spring' name for your spring-servlet.xml --&
&servlet-name&spring&/servlet-name&
&servlet-class&org.springframework.web.servlet.DispatcherServlet&/servlet-class&
&load-on-startup&1&/load-on-startup&
&/servlet&
浏览: 45191 次
来自: 来处
不错,谢谢!
折腾了好久好久,终于在看了楼主这篇文章后解决了问题,感激ing ...
lifeiez 写道请教高人:前台提交一个图片到后台,@Req ...
请教高人:前台提交一个图片到后台,@RequestMappin ...

我要回帖

更多关于 javax.servlet.jar 的文章

 

随机推荐